Documentation
¶
Index ¶
- Constants
- Variables
- func AbandonInterruptedToolExecutionRecords(sessionDir, sessionID, localTurnID string) (int64, error)
- func AnnotateSessionRunError(sessionDir, runID, message string) (bool, error)
- func AppendInputResourceEventTx(tx *dao.Tx, event InputResourceEvent) error
- func AppendKnowledgeFileGraph(graph *KnowledgeGraphSnapshot, source KnowledgeFileGraph)
- func BindSession(sessionDir, sessionID, channelType, channelID string) error
- func ClearKnowledgeBaseIndex(ctx context.Context, sessionDir, baseID string) error
- func CloseDatabases() error
- func CommitEventIntent(ctx context.Context, sessionDir string, spec EventIntentSpec, ...) error
- func CompareAndSwapResponseSessionState(sessionDir string, state ResponseSessionState, expectedVersion int64) (bool, error)
- func ConsumeESMGuidance(sessionDir, sessionID string, ids []string) error
- func ConvergeSessionRunRecovery(sessionDir string, run SessionRun, terminalEvent SessionRunEvent, ...) error
- func ConvergeSessionRunRecoveryContext(ctx context.Context, sessionDir string, run SessionRun, ...) error
- func CountAll(sessionDir string) (int, error)
- func CountWithMessages(sessionDir string, opts ...ListOption) (int, error)
- func CreateDeliveryPlan(ctx context.Context, sessionDir string, plan DeliveryPlan) error
- func CreateExecutionIntentAndSessionRun(sessionDir string, intent ExecutionIntent, run SessionRun) error
- func CreateExecutionIntentAndSessionRunEvent(sessionDir string, intent ExecutionIntent, run SessionRun, ...) (string, error)
- func CreateExecutionIntentAndSessionRunEventWithTurn(sessionDir string, intent ExecutionIntent, run SessionRun, ...) (string, error)
- func CreateSessionRun(sessionDir string, run SessionRun) error
- func CreateSessionRunAndEvent(sessionDir string, run SessionRun, event SessionRunEvent) (string, error)
- func CreateSessionRunAndEventWithTurn(sessionDir string, run SessionRun, event SessionRunEvent, ...) (string, error)
- func DecisionEventType(status string) string
- func DecodeEventRecord(record EventRecord) (interface{}, error)
- func DeleteKnowledgeBase(ctx context.Context, sessionDir, id string) error
- func DeleteProject(sessionDir, id string) error
- func DeleteSession(path string, sessionDir string) error
- func DeleteSessionWithMutation(path string, sessionDir string, guard *RuntimeLeaseGuard) error
- func DeleteWorktreeRecord(sessionDir, id string) error
- func DigestEventBatch(events []EventRecord) (string, error)
- func EndConversationTurn(sessionDir, sessionID, turnID, status, stopReason string, endedAt time.Time) error
- func EnsureCurrentSchema(db *sql.DB) error
- func EnsureKnowledgeBaseSchema(db *sql.DB) error
- func FillSessionDetailPreviews(sessionDir string, details []SessionDetail)
- func FinishSessionRunAndConversationTurn(sessionDir string, run SessionRun, event SessionRunEvent, ...) (string, error)
- func ForgetEventStoreCaches(sessionDir string)
- func GenerateID() string
- func GetChannelToolGeneration(sessionDir, sessionID string) (int64, error)
- func IsDecisionEventType(eventType string) bool
- func IsNonTerminalSessionRunStatus(status string) bool
- func IsTerminalSessionRunStatus(status string) bool
- func KnowledgeBaseDatabasePath(sessionDir, knowledgeBaseID string) (string, error)
- func LatestAdditionalDirectoriesByID(sessionDir, sessionID string) ([]string, error)
- func LatestSessionBindings(sessionDir string, sessionIDs []string) (map[string]SessionBindings, error)
- func LatestSessionRunEventSeq(sessionDir, runID string) (int64, error)
- func LatestSessionTitle(sessionDir, sessionID string) (string, string, error)
- func LeaseLostCount() uint64
- func ListFailedTransientDeliveryOperations(ctx context.Context, sessionDir, platform string) ([]string, error)
- func ListLatestSessionRuns(ctx context.Context, sessionDir string, sessionIDs []string) (map[string]SessionRun, error)
- func ListResponseReplayItems(sessionDir, sessionID string, limit int) ([]json.RawMessage, error)
- func ListSessionMetadata(sessionDir string, sessionIDs []string) (map[string]SessionMetadata, error)
- func LockRuntime(sessionDir, sessionID string) func()
- func LockSessionData(sessionDir, sessionID string) func()
- func MarkRuntimeOwnershipUncertain(databaseIdentity, sessionID string)
- func MarkSessionRunRecoveryComplete(sessionDir, sessionID, runID string) error
- func MarkSessionRunRecoveryCompleteContext(ctx context.Context, sessionDir, sessionID, runID string) error
- func MarkSessionRunRecoveryDetached(sessionDir, sessionID, runID string) error
- func MarkSessionRunRecoveryDetachedContext(ctx context.Context, sessionDir, sessionID, runID string) error
- func MarkSessionRunRecoveryFailed(sessionDir, sessionID, runID, message string, nextRetryAt time.Time) error
- func MarkSessionRunRecoveryFailedContext(ctx context.Context, sessionDir, sessionID, runID, message string, ...) error
- func NextSessionRunAttempt(sessionDir, sessionID, intentID string) (int, error)
- func NonTerminalSessionRunStatuses() []string
- func NotifyRuntimeStateChanged(sessionDir, sessionID, origin string)
- func OpenBunDatabase(path string) (*dao.Database, error)
- func OpenRootDB(sessionDir string) (*dao.Database, error)
- func OpenStandaloneDB(path string) (*dao.Database, error)
- func PrepareEventIntent(ctx context.Context, sessionDir string, spec EventIntentSpec) error
- func PrimeRuntimeOwnership(databaseIdentity, sessionID string, lease *RuntimeLeaseSnapshot, ...)
- func ProjectSessionCounts(sessionDir string) (map[string]int, error)
- func QueryRootDatabase(sessionDir string, fn func(*dao.Database) error) error
- func RebuildEventProjection(ctx context.Context, sessionDir, sessionID string, guard *RuntimeLeaseGuard) error
- func ReclaimInterruptedToolExecution(sessionDir, executionKey string) (bool, error)
- func ReconcileEventIntents(ctx context.Context, sessionDir, sessionID, runID string, ...) error
- func RefreshDeliveryIntentStatus(ctx context.Context, sessionDir, intentID string) error
- func RemoveEventStore(sessionDir, sessionID string) error
- func ReopenFailedDeliveryOperation(ctx context.Context, sessionDir, operationID string, now time.Time) (bool, error)
- func RequestToolExecutionRecovery(sessionDir, sessionID, localTurnID string, providerCallIDs []string) (int64, error)
- func RequeueDeliveryOperation(ctx context.Context, sessionDir, operationID, owner string, epoch int64, ...) error
- func RootDatabasePath(sessionDir string) string
- func RunAssistantEntryID(runID string) string
- func RunAssistantMessageFingerprint(runID string, message provider.Message) string
- func RunTerminalEventID(runID, eventType string) string
- func RunUserEntryID(runID string) string
- func RuntimeDatabaseIdentity(sessionDir string) string
- func RuntimeLeaseHeldByCurrentProcess(sessionDir, sessionID string) bool
- func RuntimeLeaseLost(sessionDir, sessionID string) <-chan struct{}
- func RuntimeOwnerInstanceID() string
- func SaveESMGuidance(sessionDir string, g ESMGuidance) error
- func SaveExecutionIntent(sessionDir string, intent ExecutionIntent) error
- func SaveInputResourceEvent(ctx context.Context, sessionDir string, event InputResourceEvent) error
- func SaveResponseItem(sessionDir string, item ResponseItemArchive) error
- func SaveResponseRun(sessionDir string, run ResponseRun) error
- func SaveResponseTurn(sessionDir string, turn ResponseTurn) error
- func SaveSessionCapabilities(sessionDir string, caps SessionCapabilities) error
- func SaveSessionCapabilityEvent(sessionDir string, ev SessionCapabilityEvent) (string, error)
- func SaveSessionRun(sessionDir string, run SessionRun) error
- func SaveSessionRunEvent(sessionDir string, ev SessionRunEvent) (string, error)
- func SetChannelTools(sessionDir, sessionID string, tools []ChannelToolConfig) error
- func SetSessionMetadata(sessionDir, sessionID string, metadata SessionMetadata) error
- func StartConversationTurn(sessionDir string, turn ConversationTurn) error
- func SubscribeRuntimeLeaseLogs(sink func(string)) func()
- func SubscribeRuntimeLeaseNotifications(handler func(RuntimeLeaseNotification)) func()
- func TerminalSessionRunStatuses() []string
- func TransferBinding(sessionDir, channelType, channelID, fromSessionID, toSessionID string) error
- func TryLockRuntime(sessionDir, sessionID string) (func(), bool)
- func TryLockRuntimes(sessionDir string, sessionIDs []string) (func(), bool)
- func UnbindSession(sessionDir, sessionID string) error
- func UpdateDeliveryOperation(ctx context.Context, sessionDir, operationID, owner string, epoch int64, ...) error
- func UpdateDeliveryOperationProgress(ctx context.Context, sessionDir, operationID, owner string, epoch int64, ...) error
- func UpdateSessionRunErrorInfo(sessionDir, runID string, info json.RawMessage) error
- func UpdateSessionRunProgress(sessionDir, runID string, progress json.RawMessage) error
- func UpdateSessionRunStatus(sessionDir, runID, status, message string, finishedAt *time.Time) error
- func UpdateSessionRunUsage(sessionDir, runID string, usage, contextUsage json.RawMessage) error
- func UpdateToolExecutionRecord(sessionDir string, record ToolExecutionRecord) error
- func UpdateWorktreeStatus(sessionDir, id, status, errMsg string) error
- func ValidateRuntimeLease(sessionDir, sessionID, runID string, purpose RuntimeLeasePurpose) error
- func ValidateRuntimeLeaseContext(ctx context.Context, sessionDir, sessionID, runID string, ...) error
- func ValidateWorkDir(workDir string) (string, error)
- func WatchDatabaseRebuilds(onNotice func(DatabaseRecovery)) func()
- func WriteRootDatabase(ctx context.Context, sessionDir string, fn func(*dao.Tx) error) error
- type ActiveRuntimeLease
- type AdditionalDirectoriesEntry
- type ArchivedFile
- type Binding
- type BranchSummaryEntry
- type ChannelToolConfig
- type CompactionEntry
- type ContentOverrideEntry
- type ConversationTurn
- type DatabaseIndexRepair
- type DatabaseRecovery
- type DeliveryFailure
- type DeliveryIntent
- type DeliveryOperation
- func ClaimDeliveryOperation(ctx context.Context, sessionDir, operationID, owner string, now time.Time, ...) (*DeliveryOperation, error)
- func GetDeliveryOperation(ctx context.Context, sessionDir, operationID string) (*DeliveryOperation, error)
- func ListDueDeliveryOperations(ctx context.Context, sessionDir string, now time.Time) ([]DeliveryOperation, error)
- type DeliveryPlan
- type ESMGuidance
- type EntryBase
- type EntryType
- type EventBatch
- type EventIntentSpec
- type EventManifest
- type EventRecord
- type EventStore
- func (s *EventStore) Append(batchID, sessionID, runID, turnID string, events []EventRecord) (EventBatch, error)
- func (s *EventStore) Inspect() ([]EventBatch, error)
- func (s *EventStore) NextSequence() (int64, error)
- func (s *EventStore) Path() string
- func (s *EventStore) Scan() ([]EventBatch, error)
- type EventStoreInspection
- type EventStoreStats
- type ExecutionIntent
- type ForkKind
- type ForkOptions
- type ForkResult
- type GeneratedArtifact
- type Header
- type IdentityLocks
- type InputResourceEvent
- type KnowledgeBase
- func CreateKnowledgeBase(ctx context.Context, sessionDir string, spec KnowledgeBaseSpec) (KnowledgeBase, error)
- func GetKnowledgeBase(ctx context.Context, sessionDir, id string) (KnowledgeBase, error)
- func ListKnowledgeBases(ctx context.Context, sessionDir string) ([]KnowledgeBase, error)
- func UpdateKnowledgeBase(ctx context.Context, sessionDir, id string, spec KnowledgeBaseSpec) (KnowledgeBase, error)
- type KnowledgeBaseSpec
- type KnowledgeChunk
- type KnowledgeDiffSummary
- type KnowledgeDiscoveryEntry
- type KnowledgeDiscoverySummary
- type KnowledgeEdge
- type KnowledgeEntityAlias
- type KnowledgeEvidence
- type KnowledgeFile
- type KnowledgeFileGraph
- type KnowledgeGraphQuery
- type KnowledgeGraphReusePlan
- type KnowledgeGraphSnapshot
- type KnowledgeNode
- type KnowledgeSnapshot
- func GetKnowledgeSnapshot(ctx context.Context, sessionDir, id string) (KnowledgeSnapshot, error)
- func ReuseKnowledgeSnapshotIfFilesMatch(ctx context.Context, sessionDir, baseID string, expectedRevision int64, ...) (KnowledgeSnapshot, bool, error)
- func StoreKnowledgeGraphSnapshot(ctx context.Context, sessionDir string, graph KnowledgeGraphSnapshot) (KnowledgeSnapshot, error)
- type KnowledgeSource
- type KnowledgeUncertainty
- type LabelEntry
- type LeaseHeartbeatHealth
- type LeftBehindEntry
- type ListOption
- type Manager
- func ContinueRecent(cwd, sessionDir string) (*Manager, error)
- func CreateBound(workDir, sessionDir, channelType, channelID string) (*Manager, error)
- func New(cwd, sessionDir string) *Manager
- func NewSubAgent(cwd, sessionDir string) *Manager
- func Open(path string) (*Manager, error)
- func OpenByID(cwd, sessionDir, sessionID string) (*Manager, error)
- func OpenByIDExact(sessionDir, sessionID string) (*Manager, error)
- func OpenByPathOrID(cwd, sessionDir, value string) (*Manager, error)
- func RotateBoundSession(sessionDir, channelType, channelID, oldSessionID string) (*Manager, error)
- func (m *Manager) AppendAdditionalDirectories(directories []string) (string, error)
- func (m *Manager) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int) (string, error)
- func (m *Manager) AppendContentOverride(targetEntryID string, msg provider.Message, reason, code string) (string, error)
- func (m *Manager) AppendEventStoreEntries(ctx context.Context, runID, turnID string, entries []interface{}) ([]string, error)
- func (m *Manager) AppendMessage(msg provider.Message) (string, error)
- func (m *Manager) AppendMessages(msgs []provider.Message) ([]string, error)
- func (m *Manager) AppendModeChange(mode string) (string, error)
- func (m *Manager) AppendModelChange(providerName, modelID string) (string, error)
- func (m *Manager) AppendSessionInfo(name string) (string, error)
- func (m *Manager) AppendSessionTitle(name, source string) (string, error)
- func (m *Manager) AppendThinkingLevelChange(level string) (string, error)
- func (m *Manager) ConvergeEventStore(ctx context.Context) error
- func (m *Manager) EndConversationTurn(turnID, status, stopReason string) error
- func (m *Manager) GetExpertID() string
- func (m *Manager) GetFile() string
- func (m *Manager) GetHeader() *Header
- func (m *Manager) GetLatestAdditionalDirectories() (AdditionalDirectoriesEntry, bool)
- func (m *Manager) GetLatestCompaction() (CompactionEntry, bool)
- func (m *Manager) GetLatestModeChange() (ModeChangeEntry, bool)
- func (m *Manager) GetLatestModelChange() (ModelChangeEntry, bool)
- func (m *Manager) GetLatestSessionInfo() (SessionInfoEntry, bool)
- func (m *Manager) GetLatestThinkingLevelChange() (ThinkingLevelChangeEntry, bool)
- func (m *Manager) GetLeafID() *string
- func (m *Manager) GetMessages() []provider.Message
- func (m *Manager) GetReplayState() ReplayState
- func (m *Manager) GetSessionDir() string
- func (m *Manager) Init() error
- func (m *Manager) InitWithBinding(channelType, channelID string) error
- func (m *Manager) InitWithID(id string) error
- func (m *Manager) InitWithIDAndBinding(id, channelType, channelID string) error
- func (m *Manager) MigrateToEventStore(ctx context.Context) error
- func (m *Manager) RecordUsage(provider, protocol, model string, ...) error
- func (m *Manager) RecordUsageFromProviderUsage(provider, protocol, model string, usage *provider.Usage, durationMs int) error
- func (m *Manager) Reload() error
- func (m *Manager) SetExpertBinding(expertID string) error
- func (m *Manager) SetSessionBinding(channelType, channelID string) error
- func (m *Manager) SetWorkDir(cwd string) error
- func (m *Manager) StartConversationTurn(turnID, intentID, runID string) error
- type MemoryStore
- func (m *MemoryStore) AppendAdditionalDirectories(directories []string) (string, error)
- func (m *MemoryStore) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int) (string, error)
- func (m *MemoryStore) AppendMessage(msg provider.Message) (string, error)
- func (m *MemoryStore) AppendModeChange(mode string) (string, error)
- func (m *MemoryStore) AppendModelChange(providerName, modelID string) (string, error)
- func (m *MemoryStore) AppendSessionInfo(name string) (string, error)
- func (m *MemoryStore) AppendThinkingLevelChange(level string) (string, error)
- func (m *MemoryStore) GetFile() string
- func (m *MemoryStore) GetHeader() *Header
- func (m *MemoryStore) GetLatestAdditionalDirectories() (AdditionalDirectoriesEntry, bool)
- func (m *MemoryStore) GetLatestCompaction() (CompactionEntry, bool)
- func (m *MemoryStore) GetLatestModeChange() (ModeChangeEntry, bool)
- func (m *MemoryStore) GetLatestModelChange() (ModelChangeEntry, bool)
- func (m *MemoryStore) GetLatestThinkingLevelChange() (ThinkingLevelChangeEntry, bool)
- func (m *MemoryStore) GetLeafID() *string
- func (m *MemoryStore) GetMessages() []provider.Message
- func (m *MemoryStore) GetReplayState() ReplayState
- func (m *MemoryStore) Init() error
- func (m *MemoryStore) InitWithID(id string) error
- type MessageEntry
- type ModeChangeEntry
- type ModelChangeEntry
- type Project
- type ReplayState
- type ResetReport
- type ResponseItemArchive
- type ResponseReplayTurn
- type ResponseRun
- type ResponseSessionState
- type ResponseTurn
- type RuntimeLeaseBinding
- func BindRuntimeLeaseToExistingRun(sessionDir, sessionID, runID string) (RuntimeLeaseBinding, error)
- func CurrentRuntimeLeaseBinding(sessionDir, sessionID string) (RuntimeLeaseBinding, bool)
- func HeldRuntimeLeaseBinding(sessionDir, sessionID string) (RuntimeLeaseBinding, <-chan struct{}, bool)
- func RetainRuntimeLease(sessionDir, sessionID, runID string) (RuntimeLeaseBinding, func(), bool, error)
- type RuntimeLeaseBusStats
- type RuntimeLeaseGroup
- type RuntimeLeaseGuard
- func AcquireContentWriteReservation(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
- func AcquireExecutionAdmission(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
- func AcquireFork(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
- func AcquireMutation(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
- func AcquireRecovery(sessionDir, sessionID, expectedRunID string) (*RuntimeLeaseGuard, error)
- func AcquireRecoveryContext(ctx context.Context, sessionDir, sessionID, expectedRunID string) (*RuntimeLeaseGuard, error)
- type RuntimeLeaseNotification
- type RuntimeLeasePurpose
- type RuntimeLeaseSnapshot
- type RuntimeOwnershipEntry
- type RuntimeOwnershipLookup
- type RuntimeSubmission
- type RuntimeSubmissionError
- type SequencedMessage
- func ListSessionMessagesAfter(sessionDir, sessionID string, afterSeq int64, limit int) ([]SequencedMessage, error)
- func ListSessionMessagesBefore(sessionDir, sessionID string, beforeSeq int64, limit int) ([]SequencedMessage, error)
- func ListSessionMessagesLatest(sessionDir, sessionID string, limit int) ([]SequencedMessage, error)
- func ListSessionMessagesWithSeq(sessionDir, sessionID string) ([]SequencedMessage, error)
- type SequencedSessionCapabilityEvent
- type SequencedSessionRunEvent
- type SessionBindings
- type SessionCapabilities
- type SessionCapabilityEvent
- type SessionDetail
- type SessionExecutionFacts
- type SessionInfo
- type SessionInfoEntry
- type SessionMetadata
- type SessionRun
- func GetActiveSessionRun(sessionDir, sessionID string) (*SessionRun, error)
- func GetActiveSessionRunContext(ctx context.Context, sessionDir, sessionID string) (*SessionRun, error)
- func GetSessionRun(sessionDir, runID string) (*SessionRun, error)
- func GetSessionRunContext(ctx context.Context, sessionDir, runID string) (*SessionRun, error)
- func LatestSessionRunForIntent(sessionDir, sessionID, intentID string) (*SessionRun, error)
- func ListOrphanedSessionRuns(sessionDir string) ([]SessionRun, error)
- func ListOrphanedSessionRunsContext(ctx context.Context, sessionDir string) ([]SessionRun, error)
- func ListSessionRuns(sessionDir, sessionID string, limit int) ([]SessionRun, error)
- type SessionRunEvent
- type SessionRunRecovery
- type SessionRunRecoveryState
- type SessionWakeCoalescer
- type Store
- type ThinkingLevelChangeEntry
- type ToolExecutionRecord
- type TurnEndEntry
- type TurnStartEntry
- type Worktree
Constants ¶
const ( EventIntentPrepared = "prepared" EventIntentAppended = "appended" EventIntentCommitted = "committed" EventIntentAborted = "aborted" EventIntentRecoveryRequired = "recovery_required" EventStoreHealthy = "healthy" EventStoreReconciling = "reconciling" EventStoreBlocked = "blocked" EventStoreInconsistent = "inconsistent" EventStoreCorrupt = "corrupt" )
const ( KnowledgeNodeStatusFact = "fact" KnowledgeNodeStatusCandidate = "candidate" )
Knowledge node status values. A "fact" node is derived deterministically by the Runtime; a "candidate" node is a model assertion without locally verifiable evidence and is hidden from default query results.
const ( WorktreeStatusPending = "pending" WorktreeStatusReady = "ready" WorktreeStatusFailed = "failed" WorktreeStatusRemoved = "removed" )
Worktree lifecycle status values. A worktree's status is a resource lifecycle state, not a run state machine.
const CurrentVersion = 3
const KnowledgeGraphSchemaVersion = 2
Variables ¶
var ( ErrDeliveryLeaseLost = errors.New("delivery operation lease was lost") ErrDeliveryOperationBusy = errors.New("delivery operation is leased or not ready") ErrDeliveryOperationAbsent = errors.New("delivery operation was not found") )
var ( ErrForkSessionNotFound = errors.New("source session not found") ErrForkSessionActive = errors.New("source session is active") ErrForkNoCompletedTurn = errors.New("source session has no completed conversation turn") ErrForkInvalidBoundary = errors.New("fork boundary is invalid") ErrForkUnsupportedEntry = errors.New("fork contains unsupported entry") ErrForkIdempotencyRequired = errors.New("fork request ID is required") ErrForkIdempotencyTooLong = errors.New("fork request ID is too long") ErrForkIdempotencyConflict = errors.New("fork idempotency request conflicts") )
var ( ErrKnowledgeBaseNotFound = errors.New("knowledge base not found") ErrKnowledgeBaseUnindexed = errors.New("knowledge base has no completed index") ErrKnowledgeBaseConfigurationChanged = errors.New("knowledge base configuration changed during indexing") ErrKnowledgeBaseDisabled = errors.New("knowledge base is disabled") )
var ( ErrRuntimeLeaseBusy = errors.New("session runtime lease is held by another process") ErrRuntimeLeaseLost = errors.New("session runtime lease was lost") ErrRuntimeSessionNotFound = errors.New("session runtime lease requires an existing session") ErrSessionRunActive = errors.New("session has an active durable run") ErrSessionRecoveryRequired = errors.New("session has an active durable run that requires reconciliation") ErrSessionRecoveryNotNeeded = errors.New("session has no active durable run to recover") ErrRuntimeLeaseRunMismatch = errors.New("session runtime lease run does not match the active durable run") ErrRuntimeLeasePurpose = errors.New("session runtime lease purpose does not allow this operation") )
var ErrConversationTurnNotOpen = errors.New("conversation turn is not open")
var ErrEventIntentFenced = errors.New("session event intent lost its fenced owner")
var ErrEventStoreNotHealthy = errors.New("session event store is not healthy")
ErrEventStoreNotHealthy is returned by every EventStore *write* gate whose inspection does not come back `healthy`. It exists so callers can distinguish "this store cannot accept my bytes right now" from an unrelated failure without matching on message text, and so tests can pin that the write fence stays closed while the read path deliberately tolerates `reconciling`.
var ErrRuntimeSubmissionConflict = errors.New("runtime submission key conflicts with another request")
var ErrRuntimeSubmissionExists = errors.New("runtime submission already exists")
var ErrSessionIDExists = errors.New("session ID already exists")
ErrSessionIDExists means a new session attempted to reuse an existing ID. A duplicate must be rejected: updating the sessions row would merge the new header with the old entries and create a forked conversation.
var ErrSessionModified = errors.New("session was modified by another process")
Functions ¶
func AbandonInterruptedToolExecutionRecords ¶
func AbandonInterruptedToolExecutionRecords(sessionDir, sessionID, localTurnID string) (int64, error)
AbandonInterruptedToolExecutionRecords marks uncertain executions as explicitly abandoned. It never retries a tool or invents a tool output; callers use it only after they have established that no runtime owns the session lock. This makes a subsequent user-submitted run a new operation instead of silently replaying a potentially side-effecting call.
func AnnotateSessionRunError ¶
AnnotateSessionRunError records a terminal error reason on a run row that reached a terminal status without one (for example a background run abandoned after interrupted tool execution). It never changes the run status and is a no-op when the run already carries an error, so an earlier finalizer stays authoritative. It reports whether the annotation was applied.
func AppendInputResourceEventTx ¶
func AppendInputResourceEventTx(tx *dao.Tx, event InputResourceEvent) error
AppendInputResourceEventTx records a resource lifecycle event in the caller's transaction. Deterministic event IDs make retries safe after an unknown commit result.
func AppendKnowledgeFileGraph ¶
func AppendKnowledgeFileGraph(graph *KnowledgeGraphSnapshot, source KnowledgeFileGraph)
AppendKnowledgeFileGraph clones a file subgraph into graph. New IDs prevent a successor snapshot from sharing mutable identity with its source.
func BindSession ¶
func ClearKnowledgeBaseIndex ¶ added in v1.3.103
ClearKnowledgeBaseIndex removes the active snapshot and every graph row while preserving configuration and the source directory. It is idempotent: an already-unindexed base clears nothing and reports success.
func CloseDatabases ¶
func CloseDatabases() error
CloseDatabases checkpoints and closes all process-owned session connections.
func CommitEventIntent ¶ added in v1.3.105
func CommitEventIntent(ctx context.Context, sessionDir string, spec EventIntentSpec, verified *EventBatch, finalize func(*dao.Tx) error) error
CommitEventIntent closes the second half of the protocol. finalize runs in the same SQLite transaction as the fenced appended->committed transition, allowing Runtime to update Run/turn/decision state atomically.
verified, when non-nil, is the batch this process just appended and fsynced through AppendPreparedEventBatch. Supplying it lets the hot append path skip the whole-log Scan() that otherwise exists only to re-read a batch this process did not write (crash recovery, reconciliation). A nil batch always rescans, so recovery keeps its exhaustive verification.
func CompareAndSwapResponseSessionState ¶
func CompareAndSwapResponseSessionState(sessionDir string, state ResponseSessionState, expectedVersion int64) (bool, error)
CompareAndSwapResponseSessionState advances a session lineage only when the caller observed expectedVersion. It prevents two concurrent turns from silently branching a previous_response_id chain.
func ConsumeESMGuidance ¶
func ConvergeSessionRunRecovery ¶
func ConvergeSessionRunRecovery(sessionDir string, run SessionRun, terminalEvent SessionRunEvent, decisionEvents []SessionRunEvent, turnStatus, stopReason string) error
ConvergeSessionRunRecovery atomically records pending Decision resolutions, closes every open ConversationTurn owned by the Run, writes the terminal Run event and state, and completes the recovery record. The exact local purpose=recovery lease is revalidated inside the transaction so a stale recovery worker cannot commit after another owner takes over.
func ConvergeSessionRunRecoveryContext ¶
func ConvergeSessionRunRecoveryContext(ctx context.Context, sessionDir string, run SessionRun, terminalEvent SessionRunEvent, decisionEvents []SessionRunEvent, turnStatus, stopReason string) error
ConvergeSessionRunRecoveryContext is the cancellable form used by the bounded Runtime recovery coordinator.
func CountWithMessages ¶
func CountWithMessages(sessionDir string, opts ...ListOption) (int, error)
CountWithMessages returns the number of sessions that contain at least one persisted conversation message. Empty sessions can be created transiently during startup or request setup and are not user-visible history.
func CreateDeliveryPlan ¶
func CreateDeliveryPlan(ctx context.Context, sessionDir string, plan DeliveryPlan) error
CreateDeliveryPlan persists a plan outside terminalization only for recovery reconciliation and focused tools. Normal execution must attach the plan to FinishSessionRunAndConversationTurn instead.
func CreateExecutionIntentAndSessionRun ¶
func CreateExecutionIntentAndSessionRun(sessionDir string, intent ExecutionIntent, run SessionRun) error
CreateExecutionIntentAndSessionRun atomically admits an immutable execution intent with its first or linked Run. Runtime-owned callers use this instead of writing the two records independently, so a reconnect can always resolve a durable Run back to the request that created it.
func CreateExecutionIntentAndSessionRunEvent ¶
func CreateExecutionIntentAndSessionRunEvent(sessionDir string, intent ExecutionIntent, run SessionRun, event SessionRunEvent) (string, error)
CreateExecutionIntentAndSessionRunEvent atomically admits an immutable intent, its Run row, and (when supplied) the canonical started event. This prevents a process loss between the intent/run write and event publication from creating an accepted execution with no replay anchor.
func CreateExecutionIntentAndSessionRunEventWithTurn ¶
func CreateExecutionIntentAndSessionRunEventWithTurn(sessionDir string, intent ExecutionIntent, run SessionRun, event SessionRunEvent, turn ConversationTurn) (string, error)
CreateExecutionIntentAndSessionRunEventWithTurn atomically admits an immutable intent, its Run/event, and the conversation turn boundary.
func CreateSessionRun ¶
func CreateSessionRun(sessionDir string, run SessionRun) error
CreateSessionRun inserts one canonical run row. Unlike SaveSessionRun, this method never overwrites an existing identity; Runtime-owned lifecycle code must treat duplicate run IDs as an admission error.
func CreateSessionRunAndEvent ¶
func CreateSessionRunAndEvent(sessionDir string, run SessionRun, event SessionRunEvent) (string, error)
CreateSessionRunAndEvent atomically inserts a new canonical Run and its first event. Retry attempts use this path so a process loss cannot leave a durable attempt without a replay anchor.
func CreateSessionRunAndEventWithTurn ¶
func CreateSessionRunAndEventWithTurn(sessionDir string, run SessionRun, event SessionRunEvent, turn ConversationTurn) (string, error)
CreateSessionRunAndEventWithTurn atomically admits a Run, its first event, and a conversation turn boundary when the Run produces transcript output.
func DecisionEventType ¶
DecisionEventType returns the durable run-event type for a decision status.
func DecodeEventRecord ¶ added in v1.3.105
func DecodeEventRecord(record EventRecord) (interface{}, error)
DecodeEventRecord reverses EventRecordFromEntry. Only committed records should reach this function; physical batches are not canonical by themselves.
The switch is the closed set of entry types the EventStore can replay. A type that exists in the legacy schema but has no declared structure, reference rewrite policy, or provider projection — today `custom` and `custom_message` — must fail loudly here rather than decode into an opaque blob: migration routes every legacy row through this decoder, so an unsupported type refuses the export instead of silently dropping it from the child transcript. Fork already refuses the same pair for the same reason. Nothing in production writes those types today; see the named debt in the proposal.
func DeleteKnowledgeBase ¶
func DeleteProject ¶
func DeleteSession ¶
DeleteSession deletes a session only after acquiring its shared mutation lease. This keeps a direct caller from deleting a session that another process still owns for execution. Callers which already hold a mutation lease for a multi-session operation use DeleteSessionWithMutation instead.
func DeleteSessionWithMutation ¶
func DeleteSessionWithMutation(path string, sessionDir string, guard *RuntimeLeaseGuard) error
DeleteSessionWithMutation deletes a session while the caller holds its Runtime-owned mutation lease. It is for coordinated multi-session operations that cannot reacquire the process-local lock per child. The lease identity is checked again inside the deletion transaction before any session row is removed.
func DeleteWorktreeRecord ¶ added in v1.3.103
DeleteWorktreeRecord removes a registry row after the underlying git worktree has been deleted. A missing row is not an error.
func DigestEventBatch ¶ added in v1.3.105
func DigestEventBatch(events []EventRecord) (string, error)
DigestEventBatch returns the stable digest used by SQLite event intents.
func EndConversationTurn ¶
func EndConversationTurn(sessionDir, sessionID, turnID, status, stopReason string, endedAt time.Time) error
EndConversationTurn atomically writes turn/end and closes its boundary row.
func EnsureCurrentSchema ¶
EnsureCurrentSchema creates the current schema only for an empty database. Existing databases are validated but never migrated or otherwise modified.
Failures that mean the schema cannot be brought to the current version (an unappliable migration, or a table missing required columns) are marked with database.SchemaIncompatible. internal/db reacts by backing the database up and starting a new empty one; every other failure is reported unchanged.
func EnsureKnowledgeBaseSchema ¶
EnsureKnowledgeBaseSchema migrates one dedicated knowledge-base SQLite database. It intentionally does not invoke EnsureCurrentSchema, which owns the unrelated session/run database schema.
func FillSessionDetailPreviews ¶ added in v1.3.105
func FillSessionDetailPreviews(sessionDir string, details []SessionDetail)
FillSessionDetailPreviews loads EventStore preview/title projection for a page of already-listed details. Legacy SQLite previews are already present. It is the page-scoped completion step for WithDeferredEventStorePreview and is safe to call for sessions that are already complete.
func FinishSessionRunAndConversationTurn ¶
func FinishSessionRunAndConversationTurn(sessionDir string, run SessionRun, event SessionRunEvent, turnID, turnStatus, stopReason string) (string, error)
FinishSessionRunAndConversationTurn atomically closes a conversation turn, its Run row, and the terminal Run event. A missing or already-closed turn is tolerated for recovery/idempotent retries because an Agent may already have emitted the boundary before Runtime terminalization.
func ForgetEventStoreCaches ¶ added in v1.3.105
func ForgetEventStoreCaches(sessionDir string)
ForgetEventStoreCaches retires process-local append state after a reset or archival move. Cache entries are only an acceleration hint, never authority.
func GenerateID ¶
func GenerateID() string
GenerateID generates a random 16-character hex ID. IDs such as entries.id are UNIQUE across the whole shared sessions.db, so the previous 32-bit space made collisions plausible at tens of millions of entries; 64 bits keeps the birthday probability negligible.
func IsDecisionEventType ¶
IsDecisionEventType reports whether eventType belongs to the durable decision ledger, including the legacy serve names.
func IsNonTerminalSessionRunStatus ¶
IsNonTerminalSessionRunStatus reports whether a durable Run still requires execution, cancellation, or terminal persistence work.
func IsTerminalSessionRunStatus ¶
IsTerminalSessionRunStatus reports whether a durable Run status is terminal.
func KnowledgeBaseDatabasePath ¶
KnowledgeBaseDatabasePath derives the private SQLite file for exactly one knowledge base. The file lives beside sessions.db but is never attached to or queried through the session database.
func LatestAdditionalDirectoriesByID ¶
LatestAdditionalDirectoriesByID reads the replayed directory binding for a session without exposing SQLite details to protocol adapters.
func LatestSessionBindings ¶ added in v1.3.105
func LatestSessionBindings(sessionDir string, sessionIDs []string) (map[string]SessionBindings, error)
LatestSessionBindings reads the newest binding entries for the requested sessions without replaying their message transcripts. Legacy SQLite sessions are resolved by one indexed metadata query. EventStore sessions use the fingerprint-cached read-only display projection (the same one session lists use), falling back to the canonical session open only if that projection is unavailable. Missing sessions and corrupt metadata rows are omitted rather than failing the whole projection.
func LatestSessionRunEventSeq ¶
LatestSessionRunEventSeq returns the durable replay cursor for one Run. Callers use it to reconcile a disconnected adapter before requesting only the missing portion of the session event stream.
func LatestSessionTitle ¶
func LeaseLostCount ¶ added in v1.3.103
func LeaseLostCount() uint64
LeaseLostCount returns the process-wide count of leases lost to a fenced takeover. A healthy owner keeps it at zero.
func ListFailedTransientDeliveryOperations ¶
func ListFailedTransientDeliveryOperations(ctx context.Context, sessionDir, platform string) ([]string, error)
ListFailedTransientDeliveryOperations returns one platform's operations that exhausted their retry budget on a transport-level failure, in delivery order. Reconnect recovery uses it to grant another retry window.
func ListLatestSessionRuns ¶
func ListLatestSessionRuns(ctx context.Context, sessionDir string, sessionIDs []string) (map[string]SessionRun, error)
ListLatestSessionRuns returns the most recent durable Run of each given session as a read-only projection keyed by session ID. Sessions without any Run are absent from the result. Adapters use it to project sidebar run status (for example ACP session/list lastRun); Run lifecycle writes remain owned by the Runtime and all SQL stays in the DAO.
func ListResponseReplayItems ¶
func ListResponseReplayItems(sessionDir, sessionID string, limit int) ([]json.RawMessage, error)
ListResponseReplayItems returns the ordered, sanitized native items from completed Responses turns. Callers can pass this sequence to a provider's native replay path instead of reconstructing prior assistant output from plain transcript text.
func ListSessionMetadata ¶
func ListSessionMetadata(sessionDir string, sessionIDs []string) (map[string]SessionMetadata, error)
ListSessionMetadata returns the persisted project/pin metadata of the given sessions in one read-only query, keyed by session ID. Sessions without a metadata row are absent from the result. All SQL stays in the DAO.
func LockRuntime ¶
func LockRuntime(sessionDir, sessionID string) func()
LockRuntime waits for the single-session lease. It is intentionally implemented as retrying TryLockRuntime so no database transaction remains open while an execution is running.
func LockSessionData ¶
func LockSessionData(sessionDir, sessionID string) func()
LockSessionData serializes short persistence mutations inside one process. Cross-process data consistency still comes from SQLite transactions.
func MarkRuntimeOwnershipUncertain ¶ added in v1.3.103
func MarkRuntimeOwnershipUncertain(databaseIdentity, sessionID string)
MarkRuntimeOwnershipUncertain forces the next lookup for a session to re-read SQLite. Adapters and reconciliation call it when they learn the view may have drifted (for example after a database rebuild).
func MarkSessionRunRecoveryComplete ¶
MarkSessionRunRecoveryComplete records successful fenced convergence.
func MarkSessionRunRecoveryDetached ¶
MarkSessionRunRecoveryDetached records that a canonical remote record was retained. The response record, not this marker, remains the evidence used to decide whether the provider execution is still recoverable.
func MarkSessionRunRecoveryFailed ¶
func MarkSessionRunRecoveryFailed(sessionDir, sessionID, runID, message string, nextRetryAt time.Time) error
MarkSessionRunRecoveryFailed persists a retryable failure under the same fenced recovery owner. A zero nextRetryAt means retry as soon as a Runtime coordinator observes the row again.
func NextSessionRunAttempt ¶
NextSessionRunAttempt returns the next ordered user-visible attempt for an ExecutionIntent. Callers must hold their Runtime admission lock while using the returned value and creating the Run, so two retry commands cannot select the same attempt number.
func NonTerminalSessionRunStatuses ¶
func NonTerminalSessionRunStatuses() []string
NonTerminalSessionRunStatuses returns the canonical durable statuses that keep a Session busy. Callers receive a copy so the shared definition cannot be mutated outside this package.
func NotifyRuntimeStateChanged ¶
func NotifyRuntimeStateChanged(sessionDir, sessionID, origin string)
NotifyRuntimeStateChanged wakes local observers after a durable Run state transition. It never carries Run content and never changes ownership. An empty sessionDir publishes an unscoped notification (receivers then fall back to SQLite); a non-empty one scopes it to the canonical database identity.
func OpenBunDatabase ¶
OpenBunDatabase returns the process-wide Bun connection for path. New data access code should use this entry point and put queries in a DAO.
func OpenRootDB ¶
OpenRootDB opens the shared sessions.db through the DAO-owned database handle. Callers must not close it; use CloseDatabases for lifecycle control.
func OpenStandaloneDB ¶
OpenStandaloneDB opens a configured standalone Bun connection. It is only intended for offline integrity checks; normal runtime code uses OpenRootDB.
func PrepareEventIntent ¶ added in v1.3.105
func PrepareEventIntent(ctx context.Context, sessionDir string, spec EventIntentSpec) error
func PrimeRuntimeOwnership ¶ added in v1.3.103
func PrimeRuntimeOwnership(databaseIdentity, sessionID string, lease *RuntimeLeaseSnapshot, runID, runStatus string)
PrimeRuntimeOwnership records the authoritative SQLite view for one session and clears any uncertainty, so a fresh read immediately benefits later reads. A nil, inactive, or expired lease clears the entry (a subsequent lookup then reports "unknown" and re-reads, which is the safe direction).
func ProjectSessionCounts ¶
ProjectSessionCounts returns how many sessions are currently assigned to each project. It is a read-only projection for project listings.
func QueryRootDatabase ¶
QueryRootDatabase runs a read operation against a session root's DAO-owned database. The callback must not retain the handle after it returns.
func RebuildEventProjection ¶ added in v1.3.105
func RebuildEventProjection(ctx context.Context, sessionDir, sessionID string, guard *RuntimeLeaseGuard) error
RebuildEventProjection reconstructs the SQLite metadata index from committed EventStore batches. It requires a local mutation or recovery lease so a projection rebuild cannot race a live writer or silently authorize a stale process.
func ReclaimInterruptedToolExecution ¶
ReclaimInterruptedToolExecution atomically reopens a tool record after a process interruption. Read-only running/interrupted records are eligible automatically; side-effecting records require the explicit retry_requested state set by the confirmation API.
func ReconcileEventIntents ¶ added in v1.3.105
func ReconcileEventIntents(ctx context.Context, sessionDir, sessionID, runID string, guard *RuntimeLeaseGuard, finalize func(*dao.Tx, EventBatch) error) error
ReconcileEventIntents lets a fenced recovery owner settle event intents for one orphaned Run. Complete bytes are adopted and committed; a prepared intent with no bytes is safely aborted; an appended intent with missing bytes is preserved as recovery_required because its prior commit cannot be inferred.
func RefreshDeliveryIntentStatus ¶
RefreshDeliveryIntentStatus recomputes the intent aggregate after an operation result. An intent is delivered only when all operations are delivered/unsupported; failed and uncertain operations remain visible.
func RemoveEventStore ¶ added in v1.3.105
RemoveEventStore removes one session's content store after its canonical session row has been deleted under the Runtime mutation lease.
func ReopenFailedDeliveryOperation ¶
func ReopenFailedDeliveryOperation(ctx context.Context, sessionDir, operationID string, now time.Time) (bool, error)
ReopenFailedDeliveryOperation returns an operation that exhausted its retry budget to retry_wait and restarts its retry window. Reconnect recovery and an explicit operator retry both use it; only a failed operation can be reopened so an in-flight or delivered operation is never clobbered.
func RequestToolExecutionRecovery ¶
func RequestToolExecutionRecovery(sessionDir, sessionID, localTurnID string, providerCallIDs []string) (int64, error)
RequestToolExecutionRecovery marks selected interrupted tool calls for an explicit user-confirmed retry. It never changes completed records and does not itself execute any tool.
func RequeueDeliveryOperation ¶
func RequeueDeliveryOperation(ctx context.Context, sessionDir, operationID, owner string, epoch int64, nextAttemptAt time.Time, failureCode string) error
RequeueDeliveryOperation releases a fenced lease for an explicit retry. It is used by recovery when a provider call did not yield a trustworthy result.
func RootDatabasePath ¶
RootDatabasePath returns the shared sessions.db path for a session root. Keeping path derivation here prevents adapters and DAOs from duplicating session directory rules.
func RunAssistantEntryID ¶
RunAssistantEntryID is the deterministic transcript identity for the final assistant entry committed by a Runtime-owned conversation Run. Keeping the identity tied to the Run makes terminal retries and recovery idempotent.
func RunAssistantMessageFingerprint ¶
RunAssistantMessageFingerprint returns a stable digest for an assistant message. It is useful to validate a recovery payload without persisting the message in a separate adapter-owned table.
func RunTerminalEventID ¶
RunTerminalEventID is the deterministic lifecycle event identity for a terminal Run. Event type is included so a cancelled recovery cannot collide with a previously selected terminal outcome.
func RunUserEntryID ¶
RunUserEntryID is the deterministic transcript identity for a Run's admitted user message. Retries do not create another user entry.
func RuntimeDatabaseIdentity ¶
RuntimeDatabaseIdentity returns the normalized SQLite identity used to scope process-local execution and recovery registries.
func RuntimeLeaseHeldByCurrentProcess ¶ added in v1.3.103
RuntimeLeaseHeldByCurrentProcess reports whether this process currently holds a live (not released, not lost) runtime lease for the session. It is an in-process diagnostic/wait signal only: durable authority still comes exclusively from the fenced owner/epoch/token CAS in SQLite.
func RuntimeLeaseLost ¶
func RuntimeLeaseLost(sessionDir, sessionID string) <-chan struct{}
RuntimeLeaseLost returns the loss signal for the current process lease. It is intentionally read-only; callers use it to cancel work while every durable write still performs its own epoch/token fence check.
func RuntimeOwnerInstanceID ¶ added in v1.3.103
func RuntimeOwnerInstanceID() string
RuntimeOwnerInstanceID returns this process's runtime owner identity. It is stable for the process lifetime and changes after a restart, so a restarted process is a distinct origin whose sequence restarts.
func SaveESMGuidance ¶
func SaveESMGuidance(sessionDir string, g ESMGuidance) error
func SaveExecutionIntent ¶
func SaveExecutionIntent(sessionDir string, intent ExecutionIntent) error
func SaveInputResourceEvent ¶
func SaveInputResourceEvent(ctx context.Context, sessionDir string, event InputResourceEvent) error
SaveInputResourceEvent appends a resource lifecycle event outside a larger transaction. Runtime admission paths should use AppendInputResourceEventTx.
func SaveResponseItem ¶
func SaveResponseItem(sessionDir string, item ResponseItemArchive) error
func SaveResponseRun ¶
func SaveResponseRun(sessionDir string, run ResponseRun) error
func SaveResponseTurn ¶
func SaveResponseTurn(sessionDir string, turn ResponseTurn) error
func SaveSessionCapabilities ¶
func SaveSessionCapabilities(sessionDir string, caps SessionCapabilities) error
SaveSessionCapabilities persists per-session runtime capability state.
func SaveSessionCapabilityEvent ¶
func SaveSessionCapabilityEvent(sessionDir string, ev SessionCapabilityEvent) (string, error)
SaveSessionCapabilityEvent appends a capability transition event to the independent event table.
func SaveSessionRun ¶
func SaveSessionRun(sessionDir string, run SessionRun) error
func SaveSessionRunEvent ¶
func SaveSessionRunEvent(sessionDir string, ev SessionRunEvent) (string, error)
SaveSessionRunEvent appends a run lifecycle event to the independent run event table.
func SetChannelTools ¶
func SetChannelTools(sessionDir, sessionID string, tools []ChannelToolConfig) error
func SetSessionMetadata ¶
func SetSessionMetadata(sessionDir, sessionID string, metadata SessionMetadata) error
func StartConversationTurn ¶
func StartConversationTurn(sessionDir string, turn ConversationTurn) error
StartConversationTurn atomically writes turn/start and its boundary row.
func SubscribeRuntimeLeaseLogs ¶
func SubscribeRuntimeLeaseLogs(sink func(string)) func()
SubscribeRuntimeLeaseLogs receives UDP diagnostics without writing them to the process-wide logger. Serve uses this to expose the messages in WebUI; TUI, CLI, and channel transports must not receive protocol diagnostics.
func SubscribeRuntimeLeaseNotifications ¶
func SubscribeRuntimeLeaseNotifications(handler func(RuntimeLeaseNotification)) func()
SubscribeRuntimeLeaseNotifications receives best-effort notifications from other local processes. It is deliberately optional: a bind failure simply leaves durable SQLite replay as the synchronization path.
func TerminalSessionRunStatuses ¶
func TerminalSessionRunStatuses() []string
TerminalSessionRunStatuses returns the canonical terminal Run statuses. Callers receive a copy so the shared definition cannot be mutated.
func TransferBinding ¶
TransferBinding atomically moves a channel identity from one session to another.
func TryLockRuntime ¶
TryLockRuntime serializes one session across all processes. The process-local mutex remains a fast path, while the SQLite lease is the authority and is automatically renewed until release or lease loss.
func TryLockRuntimes ¶
TryLockRuntimes acquires multiple session leases in sorted order. Different sessions remain independently concurrent; ordering only applies to an operation that explicitly spans more than one session.
func UnbindSession ¶
UnbindSession makes a channel-bound session local while retaining its history.
func UpdateDeliveryOperation ¶
func UpdateDeliveryOperation(ctx context.Context, sessionDir, operationID, owner string, epoch int64, status, providerAssetID, providerMessageID string, providerState json.RawMessage, failureCode string, nextAttemptAt *time.Time) error
UpdateDeliveryOperation applies a fenced provider result. Terminal updates are idempotent when a retry repeats the same result after an unknown commit.
func UpdateDeliveryOperationProgress ¶
func UpdateDeliveryOperationProgress(ctx context.Context, sessionDir, operationID, owner string, epoch int64, status, providerAssetID, providerMessageID string, providerState json.RawMessage, failureCode string) error
UpdateDeliveryOperationProgress persists an in-flight provider phase while retaining the current lease. A subsequent terminal update must use the same owner and epoch, so a stale worker remains fenced throughout upload/send.
func UpdateSessionRunErrorInfo ¶
func UpdateSessionRunErrorInfo(sessionDir, runID string, info json.RawMessage) error
UpdateSessionRunErrorInfo stores the structured terminal/recovery error independently of the compatibility Error summary column.
func UpdateSessionRunProgress ¶
func UpdateSessionRunProgress(sessionDir, runID string, progress json.RawMessage) error
UpdateSessionRunProgress persists the latest non-terminal retry/recovery projection. Terminal callers should clear it with an empty object.
func UpdateSessionRunStatus ¶
func UpdateSessionRunUsage ¶
func UpdateSessionRunUsage(sessionDir, runID string, usage, contextUsage json.RawMessage) error
UpdateSessionRunUsage persists token and context-window usage independently from terminalization so reconnects can inspect partial or recovered runs.
func UpdateToolExecutionRecord ¶
func UpdateToolExecutionRecord(sessionDir string, record ToolExecutionRecord) error
func UpdateWorktreeStatus ¶ added in v1.3.103
UpdateWorktreeStatus records a lifecycle transition. Unknown ids are a no-op so a concurrently removed worktree never fails a terminal write.
func ValidateRuntimeLease ¶
func ValidateRuntimeLease(sessionDir, sessionID, runID string, purpose RuntimeLeasePurpose) error
ValidateRuntimeLease is the context-free compatibility wrapper.
func ValidateRuntimeLeaseContext ¶
func ValidateRuntimeLeaseContext(ctx context.Context, sessionDir, sessionID, runID string, purpose RuntimeLeasePurpose) error
ValidateRuntimeLeaseContext rechecks the process-owned lease binding in a fresh SQLite transaction. It is the final Runtime fence before a side effect; callers must not treat client-provided identity as authority.
func ValidateWorkDir ¶ added in v1.3.105
ValidateWorkDir verifies that a durable session work directory exists now. Authorization remains an entry-point policy concern; this boundary only prevents a session header from retaining an unusable filesystem path.
func WatchDatabaseRebuilds ¶
func WatchDatabaseRebuilds(onNotice func(DatabaseRecovery)) func()
WatchDatabaseRebuilds retires this process's cached connection when another process on this host rebuilds a database after a failed migration. Without it, a long-running process keeps reading and writing the replaced file through its open handle (a deleted inode on Unix) until it restarts.
onNotice, when non-nil, receives each peer notice for UI rendering and is the only user-facing channel used (the notice is always recorded for TakeDatabaseRecoveries); without it the notice is logged. The returned function unsubscribes. The watcher is advisory: a missed datagram only means the stale handle is retired later, after a restart.
Types ¶
type ActiveRuntimeLease ¶
type ActiveRuntimeLease struct {
SessionID string
OwnerID string
OwnerPID int
OwnerKind string
RunID string
Purpose string
ExpiresAt time.Time
}
ActiveRuntimeLease is one session lease still recorded as active in a session database. It names the process that holds it, so destructive maintenance can refuse while another mothx process may still be executing a run there.
func ActiveRuntimeLeases ¶
func ActiveRuntimeLeases(sessionDir string) ([]ActiveRuntimeLease, error)
ActiveRuntimeLeases reports leases still marked active in a session directory's database. A directory with no database holds nothing and is not an error, so this is safe to call before the first run or after a reset.
The check is deliberately narrow: a lease exists only while a process is admitted or executing a run, so an idle TUI, serve, or ACP process holding the same directory open is not reported here. It opens the file read-only and never migrates, repairs, or initializes it: a safety preflight cannot modify the database it is deciding whether to archive.
func (ActiveRuntimeLease) Describe ¶
func (lease ActiveRuntimeLease) Describe() string
Describe renders the holder in one line for an operator-facing refusal.
type AdditionalDirectoriesEntry ¶
AdditionalDirectoriesEntry records the complete ordered directory set granted to a session. Replacements are replayable session entries.
type ArchivedFile ¶
type ArchivedFile struct {
// From is the path the file had in the session directory.
From string
// To is the archive path it was renamed to, beside From.
To string
}
ArchivedFile is one sessions.db file a reset renamed.
type Binding ¶
type Binding struct {
SessionID string `json:"sessionId"`
ChannelType string `json:"channelType"`
ChannelID string `json:"channelId"`
}
Binding describes a current external channel binding.
func FindBinding ¶
func FindBindingBySessionID ¶
FindBindingBySessionID returns the current external binding for a session.
func ListBindings ¶
type BranchSummaryEntry ¶
type BranchSummaryEntry struct {
EntryBase
Summary string `json:"summary"`
FromID string `json:"fromId"`
}
BranchSummaryEntry records a branch switch summary.
type ChannelToolConfig ¶
ChannelToolConfig describes one persisted tool selection for a channel session.
func ListChannelTools ¶
func ListChannelTools(sessionDir, sessionID string) ([]ChannelToolConfig, error)
type CompactionEntry ¶
type CompactionEntry struct {
EntryBase
Summary string `json:"summary"`
FirstKeptEntry string `json:"firstKeptEntryId"`
TokensBefore int `json:"tokensBefore"`
SummaryVersion int `json:"summaryVersion,omitempty"`
PreviousCompactionID string `json:"previousCompactionId,omitempty"`
LastSummarizedEntry string `json:"lastSummarizedEntryId,omitempty"`
}
CompactionEntry records a context compaction.
type ContentOverrideEntry ¶
type ContentOverrideEntry struct {
EntryBase
TargetEntryID string `json:"targetEntryId"`
Message provider.Message `json:"message"`
Reason string `json:"reason,omitempty"`
Code string `json:"code,omitempty"`
}
ContentOverrideEntry records an append-only, replayable replacement of a previously persisted message entry's content. Replay substitutes Message for the target entry; the original entry stays in the log for audit. It is used when a provider permanently refuses content (for example an image flagged by content inspection) and the conversation must continue without it.
Replacements are replayable session entries, exactly like directory grants: the log is never mutated or truncated, only overlaid on replay.
type ConversationTurn ¶
type ConversationTurn struct {
ID string
SessionID string
IntentID string
RunID string
Attempt int
Kind string
Status string
StartSeq int64
EndSeq *int64
StartedAt time.Time
EndedAt *time.Time
}
ConversationTurn is the durable boundary index used by Session fork resolution. It is intentionally separate from SessionRun because a Run may execute tools or maintenance work without producing a conversation turn.
func ListConversationTurns ¶
func ListConversationTurns(sessionDir, sessionID string) ([]ConversationTurn, error)
ListConversationTurns returns boundary rows in transcript order.
type DatabaseIndexRepair ¶
type DatabaseIndexRepair = database.IndexRepair
DatabaseIndexRepair reports a stale secondary index internal/db rebuilt while opening a database. Nothing is lost - index contents are derived from the table rows - but the file has already survived a failed write, which a front-end should surface once.
func TakeDatabaseIndexRepairs ¶
func TakeDatabaseIndexRepairs() []DatabaseIndexRepair
TakeDatabaseIndexRepairs returns and clears the index repairs recorded since the last call. Only this process's own repairs are reported: a repair replaces no file, so peers never announce them (unlike a migration rebuild, which must retire every other process's cached connection).
type DatabaseRecovery ¶
type DatabaseRecovery = database.MigrationRecovery
DatabaseRecovery reports a sessions database that failed schema migration and was therefore backed up and rebuilt by internal/db. The previous data stays in BackupPath.
func TakeDatabaseRecoveries ¶
func TakeDatabaseRecoveries() []DatabaseRecovery
TakeDatabaseRecoveries returns the database recoveries recorded since the last call and clears them, so a front-end can tell the user exactly once what was backed up and why. internal/db also logs each recovery.
The list covers both databases this process rebuilt itself and rebuilds other mothx processes announced over the advisory bus (those entries have Peer set).
type DeliveryFailure ¶
type DeliveryFailure struct {
OperationID string
IntentID string
SessionID string
RunID string
Platform string
TargetID string
OperationKind string
Status string
FailureCode string
AttemptCount int
UpdatedAt time.Time
}
DeliveryFailure is the operator-facing view of one delivery operation that needs attention. It never carries payload, provider state, or transport context.
func ListDeliveryFailures ¶
func ListDeliveryFailures(ctx context.Context, sessionDir, sessionID string, limit int) ([]DeliveryFailure, error)
ListDeliveryFailures lists operations that need operator attention (failed or uncertain), optionally narrowed to one session.
type DeliveryIntent ¶
type DeliveryIntent struct {
ID string
SessionID string
RunID string
Platform string
TargetID string
ReplyMessageID string
TransportContext json.RawMessage
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
DeliveryIntent is the run-level durable outbox identity. TransportContext is opaque Runtime-owned state and must never be projected into prompts or ordinary logs.
type DeliveryOperation ¶
type DeliveryOperation struct {
ID string
IntentID string
OperationKey string
ArtifactID string
OperationKind string
Sequence int
DependsOn string
IdempotencyKey string
PayloadDigest string
Status string
ProviderAssetID string
ProviderMessageID string
ProviderState json.RawMessage
AttemptCount int
NextAttemptAt *time.Time
FailureCode string
// RetryWindowStartedAt restarts the transient retry budget after an explicit
// retry; nil means the budget started at CreatedAt.
RetryWindowStartedAt *time.Time
LeaseOwner string
LeaseEpoch int64
LeaseExpiresAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
DeliveryOperation is one ordered, independently recoverable outbox step.
func ClaimDeliveryOperation ¶
func ClaimDeliveryOperation(ctx context.Context, sessionDir, operationID, owner string, now time.Time, lease time.Duration) (*DeliveryOperation, error)
ClaimDeliveryOperation atomically claims the next due operation. The lease epoch is incremented on every claim, so a delayed worker cannot overwrite a later retry after its lease expires.
func GetDeliveryOperation ¶
func GetDeliveryOperation(ctx context.Context, sessionDir, operationID string) (*DeliveryOperation, error)
GetDeliveryOperation loads one operation without exposing transport credentials or requiring callers to know its parent intent ID.
func ListDueDeliveryOperations ¶
func ListDueDeliveryOperations(ctx context.Context, sessionDir string, now time.Time) ([]DeliveryOperation, error)
ListDueDeliveryOperations returns recoverable operations whose retry time is due or whose previous worker lease has expired. It is intentionally a read; callers must claim each row through ClaimDeliveryOperation before executing.
type DeliveryPlan ¶
type DeliveryPlan struct {
Intent DeliveryIntent
Operations []DeliveryOperation
}
DeliveryPlan is created in the same transaction that terminalizes its Run.
func GetDeliveryPlan ¶
func GetDeliveryPlan(ctx context.Context, sessionDir, intentID string) (*DeliveryPlan, error)
GetDeliveryPlan loads one intent and its operations in execution order.
type ESMGuidance ¶
type ESMGuidance struct {
ID string `json:"id"`
SessionID string `json:"sessionId"`
ObjectiveVersion string `json:"objectiveVersion,omitempty"`
Guidance string `json:"guidance"`
Status string `json:"status"`
CreatedAt time.Time `json:"createdAt"`
ConsumedAt *time.Time `json:"consumedAt,omitempty"`
}
func ListESMGuidance ¶
func ListESMGuidance(sessionDir, sessionID, status string, limit int) ([]ESMGuidance, error)
type EntryBase ¶
type EntryBase struct {
Type EntryType `json:"type"`
ID string `json:"id"`
ParentID *string `json:"parentId"`
Timestamp time.Time `json:"timestamp"`
}
EntryBase contains common fields for all session entries.
type EntryType ¶
type EntryType string
EntryType identifies the type of a session entry.
const ( EntrySession EntryType = "session" EntryMessage EntryType = "message" EntryModelChange EntryType = "model_change" EntryModeChange EntryType = "mode_change" EntryThinkingChange EntryType = "thinking_level_change" EntryAdditionalDirectories EntryType = "additional_directories" EntryCompaction EntryType = "compaction" EntryContentOverride EntryType = "content_override" EntryBranchSummary EntryType = "branch_summary" EntryCustom EntryType = "custom" EntryCustomMessage EntryType = "custom_message" EntryLabel EntryType = "label" EntrySessionInfo EntryType = "session_info" EntryTurnStart EntryType = "turn_start" EntryTurnEnd EntryType = "turn_end" )
type EventBatch ¶ added in v1.3.105
type EventBatch struct {
BatchID string
SeqFrom int64
SeqTo int64
Events []EventRecord
Digest string
}
EventBatch is a physically complete append batch. It is still pending until the SQLite control plane records its fenced commit marker.
func AppendPreparedEventBatch ¶ added in v1.3.105
func AppendPreparedEventBatch(ctx context.Context, sessionDir string, spec EventIntentSpec, events []EventRecord) (EventBatch, error)
AppendPreparedEventBatch implements the first half of the cross-storage protocol: reserve the batch in SQLite, then append and fsync its bytes. If the file operation fails, the prepared intent is intentionally retained for reconciliation instead of being guessed into aborted.
func ReadCommittedEventBatches ¶ added in v1.3.105
func ReadCommittedEventBatches(ctx context.Context, sessionDir, sessionID string) ([]EventBatch, error)
ReadCommittedEventBatches returns only content whose SQLite intent is committed. Physically appended but in-doubt bytes are deliberately excluded from replay until reconciliation settles them.
type EventIntentSpec ¶ added in v1.3.105
type EventIntentSpec struct {
ID string
SessionID string
RunID string
TurnID string
SeqFrom int64
SeqTo int64
Digest string
OwnerInstanceID string
LeaseEpoch int64
LeaseTokenHash string
}
EventIntentSpec is the SQLite control-plane reservation for one event batch. OwnerInstanceID, LeaseEpoch, and LeaseTokenHash must come from the Runtime's current fenced binding; callers must never accept them from a protocol peer.
type EventManifest ¶ added in v1.3.105
type EventManifest struct {
SchemaVersion int `json:"schemaVersion"`
Active []string `json:"active"`
NextSeq int64 `json:"nextSeq"`
UpdatedAt string `json:"updatedAt,omitempty"`
}
EventManifest records which sealed segments are part of the current rebuildable physical layout. It is never canonical replay state: SQLite intents decide committed batches, and a missing/stale manifest can be reconstructed by scanning the segment directory.
type EventRecord ¶ added in v1.3.105
type EventRecord struct {
EventID string `json:"eventId"`
SessionID string `json:"sessionId"`
RunID string `json:"runId,omitempty"`
TurnID string `json:"turnId,omitempty"`
Kind string `json:"kind"`
ParentSeq int64 `json:"parentSeq,omitempty"`
Payload json.RawMessage `json:"payload"`
CreatedAt time.Time `json:"createdAt"`
}
EventRecord is the front-end-neutral content event persisted by EventStore. Payload is intentionally opaque here; Agent Runtime owns its schema.
func EventRecordFromEntry ¶ added in v1.3.105
func EventRecordFromEntry(entry interface{}, sessionID, runID, turnID string) (EventRecord, error)
EventRecordFromEntry preserves the existing Session entry schema inside the EventStore payload. Keeping the entry envelope intact makes the first storage migration lossless: replay semantics stay in one place while the physical payload leaves the shared SQLite B-tree.
type EventStore ¶ added in v1.3.105
type EventStore struct {
// contains filtered or unexported fields
}
EventStore is the session-scoped append-only content store. It is not an ownership mechanism: callers must already hold the Runtime fenced lease. SQLite intent/commit records remain the authority for deciding which batches are canonical; Scan only reports physically complete batches.
func NewEventStore ¶ added in v1.3.105
func NewEventStore(sessionDir, sessionID string) (*EventStore, error)
NewEventStore opens the event store for one session. The directory is kept outside sessions.db so content corruption has a session-sized blast radius.
func (*EventStore) Append ¶ added in v1.3.105
func (s *EventStore) Append(batchID, sessionID, runID, turnID string, events []EventRecord) (EventBatch, error)
Append writes one bounded batch. The footer is written only after every event line, so a scanner can distinguish a complete batch from a crash tail. It does not mark the batch canonical; the SQLite commit protocol does that.
func (*EventStore) Inspect ¶ added in v1.3.105
func (s *EventStore) Inspect() ([]EventBatch, error)
Inspect reports physically complete batches without mutating the store. It is the read-only counterpart of Scan and is what reconciliation and session load must use: those paths run without the fenced writer lease, so they may neither truncate a crash tail nor materialise the rebuildable manifest. Corruption classification is identical to Scan; only the filesystem side effects differ.
func (*EventStore) NextSequence ¶ added in v1.3.105
func (s *EventStore) NextSequence() (int64, error)
NextSequence returns the next event sequence after the last physically complete batch. It is a reservation hint; the SQLite event intent and the fenced writer are what make the reservation authoritative.
func (*EventStore) Path ¶ added in v1.3.105
func (s *EventStore) Path() string
Path returns the private directory owned by this EventStore. Callers should use RemoveEventStore for lifecycle cleanup rather than deleting children.
func (*EventStore) Scan ¶ added in v1.3.105
func (s *EventStore) Scan() ([]EventBatch, error)
Scan reports physically complete batches and repairs only an incomplete final tail. A malformed middle line is corruption and is never skipped.
type EventStoreInspection ¶ added in v1.3.105
type EventStoreInspection struct {
State string
Batches []EventBatch
Intents []dao.SessionEventIntentRecord
Reason string
}
EventStoreInspection combines physical event batches with their SQLite control-plane intents. It is a diagnostic/recovery projection, not an authorization decision; callers still need a current fenced lease.
func InspectEventStore ¶ added in v1.3.105
func InspectEventStore(ctx context.Context, sessionDir, sessionID string) (EventStoreInspection, error)
InspectEventStore is the first reconciliation boundary between the file EventStore and SQLite. It deliberately fails closed: an orphan batch, missing committed bytes, or a digest/sequence mismatch is never promoted to canonical session content.
type EventStoreStats ¶ added in v1.3.105
type EventStoreStats struct {
AppendBatches uint64
AppendEvents uint64
AppendBytes uint64
CacheHits uint64
CacheMisses uint64
// FullScans counts whole-log physical scans. A steady-state append path must
// not grow this with transcript size; it exists to pin that the hot path is
// O(1) instead of re-reading the ever-growing log per append.
FullScans uint64
}
EventStoreStats is a process-local write-pressure snapshot. It is advisory telemetry only: SQLite intents and event files remain the durable facts.
func EventStoreWriteStats ¶ added in v1.3.105
func EventStoreWriteStats() EventStoreStats
type ExecutionIntent ¶
type ExecutionIntent struct {
ID string
SessionID string
Source string
Model string
Mode string
WorkDir string
RequestFingerprint string
Request json.RawMessage
Policy json.RawMessage
CreatedAt time.Time
}
ExecutionIntent is the durable, adapter-neutral record of an accepted user request. Request and policy snapshots are opaque to session storage; the shared Runtime owns their interpretation.
func GetExecutionIntent ¶
func GetExecutionIntent(sessionDir, intentID string) (*ExecutionIntent, error)
type ForkOptions ¶
type ForkResult ¶
type ForkResult struct {
SessionID string `json:"sessionId"`
ParentSessionID string `json:"parentSessionId"`
ForkKind ForkKind `json:"forkKind"`
BoundarySeq int64 `json:"boundarySeq"`
SeedLength int64 `json:"seedLength"`
}
func ForkSession ¶
func ForkSession(ctx context.Context, sessionDir string, options ForkOptions) (ForkResult, error)
type GeneratedArtifact ¶
type GeneratedArtifact struct {
ID string
SessionID string
RunID string
Origin string
Kind string
Filename string
MediaType string
Bytes int64
Status string
CreatedAt time.Time
}
GeneratedArtifact is the canonical read-only projection of one persisted session attachment row. Despite the artifact-oriented name it projects any attachment origin/status; the bytes themselves stay in the Runtime-owned private store referenced by the attachment row and are never embedded here.
func ListGeneratedArtifacts ¶
func ListGeneratedArtifacts(ctx context.Context, sessionDir, sessionID string) ([]GeneratedArtifact, error)
ListGeneratedArtifacts returns every attachment persisted for sessionID whose lifecycle status is "generated", in durable creation order. Adapters use it for replay projections (for example ACP session/load); content access stays with the Runtime-owned attachment service and all SQL stays in the DAO.
func ListSessionAttachments ¶
func ListSessionAttachments(ctx context.Context, sessionDir, sessionID, status string) ([]GeneratedArtifact, error)
ListSessionAttachments returns metadata-only projections of the persisted attachment rows of one session, optionally filtered by lifecycle status (an empty status returns every row), in durable creation order. Adapters use it for listing surfaces (for example ACP mothx/attachment/list); content access stays with the Runtime-owned attachment service and all SQL stays in the DAO.
type Header ¶
type Header struct {
Type EntryType `json:"type"`
Version int `json:"version"`
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
Cwd string `json:"cwd"`
ParentSession string `json:"parentSession,omitempty"`
ChannelType string `json:"channelType,omitempty"`
ChannelID string `json:"channelId,omitempty"`
ForkBoundarySeq int64 `json:"forkBoundarySeq,omitempty"`
SeedLength int64 `json:"seedLength,omitempty"`
ForkKind string `json:"forkKind,omitempty"`
// ExpertID is the bound expert bundle name (empty = no expert identity).
// Persisted like the channel binding fields so reloads restore identity.
ExpertID string `json:"expertId,omitempty"`
}
Header is the first line of a session file.
type IdentityLocks ¶
type IdentityLocks struct {
// contains filtered or unexported fields
}
IdentityLocks serializes operations for one external channel identity. It is shared by inbound dispatch and session lifecycle management. Entries are evicted once the last holder releases them so the map does not grow without bound in long-running processes.
func NewIdentityLocks ¶
func NewIdentityLocks() *IdentityLocks
func (*IdentityLocks) Lock ¶
func (s *IdentityLocks) Lock(channelType, channelID string) func()
type InputResourceEvent ¶
type InputResourceEvent struct {
ID string
SessionID string
ResourceID string
RunID string
EventType string
Status string
Timestamp time.Time
Data json.RawMessage
}
InputResourceEvent is the canonical lifecycle projection for one Runtime materialized resource. Transport references are intentionally absent.
func ListInputResourceEvents ¶
func ListInputResourceEvents(ctx context.Context, sessionDir, sessionID string) ([]InputResourceEvent, error)
ListInputResourceEvents returns resource lifecycle events in durable order.
type KnowledgeBase ¶
type KnowledgeBase struct {
ID string `json:"id"`
KnowledgeBaseSpec
ActiveSnapshotID string `json:"activeSnapshotId,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ConfigRevision int64 `json:"-"`
}
func CreateKnowledgeBase ¶
func CreateKnowledgeBase(ctx context.Context, sessionDir string, spec KnowledgeBaseSpec) (KnowledgeBase, error)
func GetKnowledgeBase ¶
func GetKnowledgeBase(ctx context.Context, sessionDir, id string) (KnowledgeBase, error)
func ListKnowledgeBases ¶
func ListKnowledgeBases(ctx context.Context, sessionDir string) ([]KnowledgeBase, error)
func UpdateKnowledgeBase ¶
func UpdateKnowledgeBase(ctx context.Context, sessionDir, id string, spec KnowledgeBaseSpec) (KnowledgeBase, error)
type KnowledgeBaseSpec ¶
type KnowledgeBaseSpec struct {
Name string `json:"name"`
RootDir string `json:"rootDir"`
PreprocessProfile string `json:"preprocessProfile"`
Provider string `json:"provider"`
Model string `json:"model"`
Mode string `json:"mode"`
ThinkingLevel string `json:"thinkingLevel,omitempty"`
Schedule string `json:"schedule"`
Enabled bool `json:"enabled"`
IgnoreGlobs []string `json:"ignoreGlobs,omitempty"`
}
KnowledgeBaseSpec is the editable Desktop configuration. It deliberately stores provider/model/mode as references, not copied provider credentials.
type KnowledgeChunk ¶
type KnowledgeChunk struct {
ID string `json:"id"`
SnapshotID string `json:"snapshotId"`
FileID string `json:"fileId"`
RelativePath string `json:"relativePath,omitempty"`
Ordinal int `json:"ordinal"`
Text string `json:"text"`
StartLine int `json:"startLine"`
EndLine int `json:"endLine"`
ContentSHA256 string `json:"contentSha256"`
}
type KnowledgeDiffSummary ¶ added in v1.3.103
type KnowledgeDiffSummary struct {
Added int `json:"added"`
Modified int `json:"modified"`
Removed int `json:"removed"`
Unchanged int `json:"unchanged"`
AddedPaths []string `json:"addedPaths,omitempty"`
ModifiedPaths []string `json:"modifiedPaths,omitempty"`
RemovedPaths []string `json:"removedPaths,omitempty"`
}
func DiffKnowledgeManifest ¶ added in v1.3.103
func DiffKnowledgeManifest(ctx context.Context, sessionDir, baseID string, manifest []KnowledgeFile) (KnowledgeDiffSummary, error)
DiffKnowledgeManifest compares an indexable manifest against the files of the active snapshot. Path lists are bounded; the counts always cover the whole comparison. A base without an active snapshot reports every file as added.
type KnowledgeDiscoveryEntry ¶ added in v1.3.103
KnowledgeDiscoveryEntry is one relative path with the reason it was not indexed. It never carries file contents.
type KnowledgeDiscoverySummary ¶ added in v1.3.103
type KnowledgeDiscoverySummary struct {
Discovered int `json:"discovered"`
Ignored int `json:"ignored"`
Skipped int `json:"skipped"`
IgnoredEntries []KnowledgeDiscoveryEntry `json:"ignoredEntries,omitempty"`
SkippedEntries []KnowledgeDiscoveryEntry `json:"skippedEntries,omitempty"`
}
func (*KnowledgeDiscoverySummary) RecordIgnored ¶ added in v1.3.103
func (s *KnowledgeDiscoverySummary) RecordIgnored(path, reason string)
RecordIgnored counts one ignored path and keeps a bounded sample entry.
func (*KnowledgeDiscoverySummary) RecordSkipped ¶ added in v1.3.103
func (s *KnowledgeDiscoverySummary) RecordSkipped(path, reason string)
RecordSkipped counts one skipped path and keeps a bounded sample entry.
type KnowledgeEdge ¶
type KnowledgeEntityAlias ¶ added in v1.3.103
type KnowledgeEntityAlias struct {
ID string `json:"id"`
SnapshotID string `json:"snapshotId"`
NormalizedAlias string `json:"normalizedAlias"`
NodeID string `json:"nodeId"`
}
KnowledgeEntityAlias maps one normalized synonym label onto the entity node that owns it inside a snapshot. Merging requires evidence support.
type KnowledgeEvidence ¶
type KnowledgeEvidence struct {
ID string `json:"id"`
SnapshotID string `json:"snapshotId"`
NodeID string `json:"nodeId,omitempty"`
EdgeID string `json:"edgeId,omitempty"`
ChunkID string `json:"chunkId"`
StartLine int `json:"startLine"`
EndLine int `json:"endLine"`
Confidence float64 `json:"confidence"`
}
type KnowledgeFile ¶
type KnowledgeFile struct {
ID string `json:"id"`
SnapshotID string `json:"snapshotId"`
RelativePath string `json:"relativePath"`
ContentSHA256 string `json:"contentSha256"`
ByteSize int64 `json:"byteSize"`
MediaType string `json:"mediaType"`
Title string `json:"title,omitempty"`
Status string `json:"status"`
}
type KnowledgeFileGraph ¶
type KnowledgeFileGraph struct {
File KnowledgeFile
Chunks []KnowledgeChunk
Nodes []KnowledgeNode
Edges []KnowledgeEdge
Evidence []KnowledgeEvidence
}
KnowledgeFileGraph is the self-contained, evidence-backed subgraph owned by one source file. It is used to carry unchanged file work from an immutable snapshot into its successor without re-running extractors or an Indexer.
type KnowledgeGraphQuery ¶
type KnowledgeGraphQuery struct {
KnowledgeBase KnowledgeBase `json:"knowledgeBase"`
Snapshot KnowledgeSnapshot `json:"snapshot"`
Chunks []KnowledgeChunk `json:"chunks"`
Nodes []KnowledgeNode `json:"nodes"`
Edges []KnowledgeEdge `json:"edges"`
Evidence []KnowledgeEvidence `json:"evidence,omitempty"`
Uncertainties []KnowledgeUncertainty `json:"uncertainties,omitempty"`
Truncated bool `json:"truncated"`
}
func QueryKnowledgeGraph ¶
func QueryKnowledgeGraph(ctx context.Context, sessionDir, baseID, query string, limit int) (KnowledgeGraphQuery, error)
QueryKnowledgeGraph executes the local FTS seed lookup followed by a bounded graph projection. It never reads the source directory itself; the active completed snapshot is the sole query authority.
type KnowledgeGraphReusePlan ¶
type KnowledgeGraphReusePlan struct {
BaseConfigRevision int64
SourceSnapshotID string
Files map[string]KnowledgeFileGraph // key: normalized relative path
}
KnowledgeGraphReusePlan contains source-file subgraphs that still match the current directory manifest. The caller must clone them into a new snapshot; no row, node, chunk or edge identity is shared between snapshots.
func PrepareKnowledgeGraphReusePlan ¶
func PrepareKnowledgeGraphReusePlan(ctx context.Context, sessionDir, baseID string, manifest []KnowledgeFile) (KnowledgeGraphReusePlan, error)
PrepareKnowledgeGraphReusePlan loads unchanged per-file graph work from the active snapshot. It is deliberately all-or-nothing per file: an edge whose endpoint or evidence escapes the file is omitted rather than claiming an unverified cross-file relationship in the successor snapshot.
type KnowledgeGraphSnapshot ¶
type KnowledgeGraphSnapshot struct {
BaseConfigRevision int64
Snapshot KnowledgeSnapshot
Files []KnowledgeFile
Chunks []KnowledgeChunk
Nodes []KnowledgeNode
Edges []KnowledgeEdge
Evidence []KnowledgeEvidence
Aliases []KnowledgeEntityAlias
DiffSummary *KnowledgeDiffSummary
DiscoverySummary *KnowledgeDiscoverySummary
}
KnowledgeGraphSnapshot is the immutable payload committed by a successful indexer. The session package atomically stores it and switches the active snapshot only after all graph rows are durable.
type KnowledgeNode ¶
type KnowledgeNode struct {
ID string `json:"id"`
SnapshotID string `json:"snapshotId"`
Kind string `json:"kind"`
Label string `json:"label"`
NormalizedLabel string `json:"normalizedLabel"`
Summary string `json:"summary,omitempty"`
// Status is "fact" for deterministically derived nodes and "candidate" for
// model-asserted nodes that carry no locally verifiable evidence. Confidence
// is the Runtime-assigned reliability of the node.
Status string `json:"status,omitempty"`
Confidence float64 `json:"confidence,omitempty"`
}
type KnowledgeSnapshot ¶
type KnowledgeSnapshot struct {
ID string `json:"id"`
KnowledgeBaseID string `json:"knowledgeBaseId"`
RunID string `json:"runId,omitempty"`
Status string `json:"status"`
SchemaVersion int `json:"schemaVersion"`
FileCount int `json:"fileCount"`
ChunkCount int `json:"chunkCount"`
NodeCount int `json:"nodeCount"`
EdgeCount int `json:"edgeCount"`
StartedAt time.Time `json:"startedAt"`
FinishedAt time.Time `json:"finishedAt,omitempty"`
ErrorSummary string `json:"errorSummary,omitempty"`
DiffSummary *KnowledgeDiffSummary `json:"diffSummary,omitempty"`
DiscoverySummary *KnowledgeDiscoverySummary `json:"discoverySummary,omitempty"`
}
func GetKnowledgeSnapshot ¶
func GetKnowledgeSnapshot(ctx context.Context, sessionDir, id string) (KnowledgeSnapshot, error)
func ReuseKnowledgeSnapshotIfFilesMatch ¶
func ReuseKnowledgeSnapshotIfFilesMatch(ctx context.Context, sessionDir, baseID string, expectedRevision int64, files []KnowledgeFile) (KnowledgeSnapshot, bool, error)
ReuseKnowledgeSnapshotIfFilesMatch returns the active immutable snapshot when the deterministic scan produced the exact same indexable file set. It deliberately compares content hashes rather than timestamps so a caller cannot serve stale knowledge merely because a tool preserved mtimes.
func StoreKnowledgeGraphSnapshot ¶
func StoreKnowledgeGraphSnapshot(ctx context.Context, sessionDir string, graph KnowledgeGraphSnapshot) (KnowledgeSnapshot, error)
type KnowledgeSource ¶ added in v1.3.103
type KnowledgeSource struct {
RelativePath string `json:"relativePath"`
Title string `json:"title,omitempty"`
MediaType string `json:"mediaType,omitempty"`
Status string `json:"status"`
ByteSize int64 `json:"byteSize"`
ChunkCount int `json:"chunkCount"`
ContentSHA256 string `json:"contentSha256,omitempty"`
}
KnowledgeSource is the bounded file-level provenance projection for one active snapshot. It never carries file contents.
func ListKnowledgeSources ¶ added in v1.3.103
func ListKnowledgeSources(ctx context.Context, sessionDir, baseID string) ([]KnowledgeSource, error)
ListKnowledgeSources projects the active snapshot's file manifest. It reads no source directory and returns no file contents.
type KnowledgeUncertainty ¶ added in v1.3.103
type KnowledgeUncertainty struct {
Kind string `json:"kind"`
Description string `json:"description"`
NodeID string `json:"nodeId,omitempty"`
EdgeID string `json:"edgeId,omitempty"`
Path string `json:"path,omitempty"`
}
KnowledgeUncertainty is one bounded, structured signal that a query result may be incomplete or low-confidence. It never contains full document text.
type LabelEntry ¶
type LabelEntry struct {
EntryBase
TargetID string `json:"targetId"`
Label *string `json:"label,omitempty"`
}
LabelEntry records a user-defined label on an entry.
type LeaseHeartbeatHealth ¶ added in v1.3.103
type LeaseHeartbeatHealth struct {
DatabaseIdentity string `json:"databaseIdentity"`
LastAttemptAt time.Time `json:"lastAttemptAt,omitempty"`
LastSuccessAt time.Time `json:"lastSuccessAt,omitempty"`
ConsecutiveFailures int `json:"consecutiveFailures"`
Attempts uint64 `json:"attempts"`
Failures uint64 `json:"failures"`
FenceLosses uint64 `json:"fenceLosses"`
MaxRenewDuration time.Duration `json:"maxRenewDurationNs"`
}
LeaseHeartbeatHealth is a diagnostics-only view of this process's runtime lease heartbeat for one session database. It never authorizes anything: ownership is decided solely by the fenced owner/epoch/token CAS, so a stalled heartbeat (ConsecutiveFailures > 0 with a stale LastSuccessAt) is an availability problem to retry, not ownership loss. A non-zero FenceLosses means a renewal actually ran and the CAS no longer matched, i.e. another process took the session over. DatabaseIdentity is the session database's base name: the local /debug/vars surface does not expose absolute paths.
func LeaseHeartbeatHealthStats ¶ added in v1.3.103
func LeaseHeartbeatHealthStats() []LeaseHeartbeatHealth
LeaseHeartbeatHealthStats returns one health row per session database this process has heartbeated, sorted by database identity for stable output.
type LeftBehindEntry ¶
type LeftBehindEntry struct {
// Name is the entry name relative to the session directory.
Name string
// Directory reports whether the entry is a directory.
Directory bool
// Bytes is the entry size, summed recursively for directories. Symbolic
// links are not followed.
Bytes int64
}
LeftBehindEntry is one session-directory entry that outlives a reset.
type ListOption ¶
type ListOption func(*listOptions)
func WithDeferredEventStorePreview ¶ added in v1.3.105
func WithDeferredEventStorePreview() ListOption
WithDeferredEventStorePreview leaves EventStore preview/title projection to the caller's current page. Callers that sort and filter on cheap SQLite metadata first can use this to avoid replaying every EventStore transcript just to render the first page.
func WithLimit ¶
func WithLimit(limit int) ListOption
func WithMessagesOnly ¶
func WithMessagesOnly() ListOption
WithMessagesOnly limits session listings to sessions containing at least one persisted conversation message. This avoids loading transient empty sessions during history pagination.
func WithOffset ¶
func WithOffset(offset int) ListOption
func WithSearch ¶
func WithSearch(search string) ListOption
WithSearch filters sessions by ID, work directory, channel metadata, or persisted message/session-info content. It is intended for session listings.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages a single session's state and persistence.
func ContinueRecent ¶
ContinueRecent continues the session a person last used in a directory, or creates a new one. "Most recent" means last activity, not newest creation, so continuing an old but active session does not silently switch to an empty one created afterwards.
func CreateBound ¶
func NewSubAgent ¶
NewSubAgent creates a session manager whose records are stored separately from user-continuable sessions.
func OpenByID ¶
OpenByID opens the session for cwd whose session ID matches sessionID. Supports prefix matching — if sessionID matches multiple sessions, an error is returned.
func OpenByIDExact ¶
OpenByIDExact opens a session by exact session ID regardless of cwd.
func OpenByPathOrID ¶
OpenByPathOrID opens a session using either an explicit file path or a session ID for the supplied working directory.
func RotateBoundSession ¶
RotateBoundSession atomically creates a new bound session and clears the old one. The replacement inherits the old session's durable work directory; channel configuration is only used when an identity has no session yet.
func (*Manager) AppendAdditionalDirectories ¶
AppendAdditionalDirectories records a complete replacement of the session's additional directory roots.
func (*Manager) AppendCompaction ¶
func (m *Manager) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int) (string, error)
AppendCompaction records a context compaction.
func (*Manager) AppendContentOverride ¶
func (m *Manager) AppendContentOverride(targetEntryID string, msg provider.Message, reason, code string) (string, error)
AppendContentOverride records an append-only replacement of a persisted message entry's content. Replay substitutes msg for the target entry while the original entry stays in the log for audit. It is the durable half of the provider content-rejection recovery: when a provider permanently refuses an image, the Runtime strips it in memory and records the override so every later replay (this process or a reload) never re-sends the refused content.
func (*Manager) AppendEventStoreEntries ¶ added in v1.3.105
func (m *Manager) AppendEventStoreEntries(ctx context.Context, runID, turnID string, entries []interface{}) ([]string, error)
AppendEventStoreEntries appends a complete bounded batch to the canonical session EventStore. It is the Runtime-owned write entry point for sessions that have opted into the new content store; the legacy AppendMessage APIs intentionally remain SQLite-compatible until their callers migrate.
func (*Manager) AppendMessage ¶
AppendMessage adds a message entry.
func (*Manager) AppendMessages ¶
AppendMessages persists an ordered batch of conversation messages, folding one agent iteration's worth of tool results into a bounded number of write transactions (see maxEntriesPerTransaction) instead of one transaction per message. Entries are chained parent-to-child in order; the lease fence and the leaf-conflict check run once per transaction and provide the same guarantees AppendMessage provides per entry. On failure no entry of the failing transaction is persisted while messages committed by earlier chunk transactions stay durable — the same contract as a sequence of AppendMessage calls failing halfway through.
func (*Manager) AppendModeChange ¶
AppendModeChange records a session execution mode change.
func (*Manager) AppendModelChange ¶
AppendModelChange records a model change.
func (*Manager) AppendSessionInfo ¶
AppendSessionInfo records a session display name. It is retained for compatibility; new callers should use AppendSessionTitle with a source.
func (*Manager) AppendSessionTitle ¶
AppendSessionTitle records a session display name and its origin.
func (*Manager) AppendThinkingLevelChange ¶
AppendThinkingLevelChange records a thinking level change.
func (*Manager) ConvergeEventStore ¶ added in v1.3.105
ConvergeEventStore makes this Manager read the canonical EventStore. It is the single expression of "this session is now open": load() calls it for every Manager that observes the EventStore, and MigrateToEventStore calls it before deciding whether an export is needed.
Reading canonically is a property of the session, not of whichever entry point happens to call SessionRuntime.BindSession. serve/chat, the background coordinator, channels, ESM, and ACP all open Managers directly, so leaving the read to a bind side effect let those Managers replay the legacy SQLite duplicate of a transcript that the EventStore already owns.
The caller must not hold m.mu. Convergence takes neither a lease nor a reservation: both durable repairs it may run are recomputations of facts the committed event log already states, so they are idempotent and cannot destroy live data. The write fence for real content changes stays inside appendEventStoreEntriesLocked and the Runtime terminal transaction.
func (*Manager) EndConversationTurn ¶
EndConversationTurn closes the durable boundary used by Session fork resolution. It is safe for callers to report failed, cancelled and incomplete outcomes; all are terminal turn states.
func (*Manager) GetExpertID ¶
GetExpertID returns the bound expert bundle name ("" when unbound).
func (*Manager) GetLatestAdditionalDirectories ¶
func (m *Manager) GetLatestAdditionalDirectories() (AdditionalDirectoriesEntry, bool)
GetLatestAdditionalDirectories returns the latest complete directory-root binding persisted in this session.
func (*Manager) GetLatestCompaction ¶
func (m *Manager) GetLatestCompaction() (CompactionEntry, bool)
GetLatestCompaction returns the newest compaction entry in the current session.
func (*Manager) GetLatestModeChange ¶
func (m *Manager) GetLatestModeChange() (ModeChangeEntry, bool)
GetLatestModeChange returns the newest session mode in the session.
func (*Manager) GetLatestModelChange ¶
func (m *Manager) GetLatestModelChange() (ModelChangeEntry, bool)
GetLatestModelChange returns the newest model binding in the session.
func (*Manager) GetLatestSessionInfo ¶ added in v1.3.105
func (m *Manager) GetLatestSessionInfo() (SessionInfoEntry, bool)
GetLatestSessionInfo returns the newest session title entry.
func (*Manager) GetLatestThinkingLevelChange ¶
func (m *Manager) GetLatestThinkingLevelChange() (ThinkingLevelChangeEntry, bool)
GetLatestThinkingLevelChange returns the newest thinking level in the session.
func (*Manager) GetMessages ¶
GetMessages extracts all messages from the current branch.
func (*Manager) GetReplayState ¶
func (m *Manager) GetReplayState() ReplayState
GetReplayState returns the current branch after applying compaction entries.
func (*Manager) GetSessionDir ¶
GetSessionDir returns the root directory containing this manager's shared sessions database. Runtime extensions use it for auxiliary session tables.
func (*Manager) Init ¶
Init initializes a new session with an auto-generated session ID. Must be called before appending entries.
func (*Manager) InitWithBinding ¶
InitWithBinding initializes a new session with a channel binding.
func (*Manager) InitWithID ¶
InitWithID initializes a new session using the provided session ID. If id is empty, a new random ID is generated.
func (*Manager) InitWithIDAndBinding ¶
InitWithIDAndBinding initializes a session with a specific ID and channel binding.
func (*Manager) MigrateToEventStore ¶ added in v1.3.105
MigrateToEventStore is the single migration entry point for a session's persisted content store. Every Runtime attach path (SessionRuntime.BindSession, AttachSessionResources, and Builder.Build) calls exactly this method and does no migration logic of its own, so no entry point can diverge on whether an old session is migrated.
It exports the legacy SQLite transcript once, under a session content lease. The EventStore batch is committed and indexed before legacy payload rows are removed, so a failed export leaves the old source intact while a successful migration removes the duplicate payload copy.
Migration is opportunistic and must never contend with the Run a session serves: an attach is not an execution, and an adapter must be able to open a session whose run is owned elsewhere. The Runtime binds — and therefore migrates — a session while the durable Run that owns the session lease is still active, so this routine never reserves an idle session with AcquireMutation. It either adopts facts that are already committed (no lease at all) or fences the one irreversible step, the content store flip, against the lease identity this process already holds. When no lease exists the session is genuinely idle and the flip needs no fence beyond the atomic statement itself.
When another owner holds the session run — or this process loses its lease mid-export — there is no safe window to take the irreversible step, so the call returns nil having done nothing: the session keeps serving from its self-consistent legacy store and a later attach (or the owner's own bind) migrates it. Only a genuinely unsafe session fails closed: an unhealthy or corrupt EventStore, an entry type the store cannot replay, or a database error.
Convergence is idempotent, so bind does not fork it: `ConvergeEventStore` — which every open passes through — is called first and brings this Manager to the canonical event log together with the two durable repairs. When the session has not been flipped yet, only this entry is entitled to take the irreversible step, so `exportLegacyTranscript` follows.
func (*Manager) RecordUsage ¶
func (m *Manager) RecordUsage(provider, protocol, model string, inputTokens, outputTokens, totalTokens, durationMs int) error
RecordUsage records a single LLM request's token usage and timing.
func (*Manager) RecordUsageFromProviderUsage ¶
func (m *Manager) RecordUsageFromProviderUsage(provider, protocol, model string, usage *provider.Usage, durationMs int) error
RecordUsageFromProviderUsage records usage from a provider.Usage struct.
func (*Manager) Reload ¶
Reload refreshes a manager from the shared SQLite session database. Serve entry points may retain a Manager while another UI writes the same session; reload after acquiring the session runtime lock so the next append uses the current leaf instead of an old optimistic-lock parent.
func (*Manager) SetExpertBinding ¶
SetExpertBinding updates the session's expert binding (empty string unbinds). It patches the in-memory header and persists the sessions row so reloads restore the identity; callers rebuild the Agent afterwards (same lifecycle as capability toggles such as /delegate).
func (*Manager) SetSessionBinding ¶
SetSessionBinding updates a Manager's in-memory header after a binding change.
func (*Manager) SetWorkDir ¶
SetWorkDir changes the persisted working directory of an idle session. The caller is responsible for ensuring that the new directory is authorized and for rebuilding any Runtime resources that were assembled for the old one.
func (*Manager) StartConversationTurn ¶
StartConversationTurn opens the durable boundary used by Session fork resolution. It is intentionally optional on session.Store so transient and in-memory agents do not need a SQLite turn index.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is an in-memory implementation of Store for testing. It does not persist data to disk.
func NewMemoryStore ¶
func NewMemoryStore() *MemoryStore
NewMemoryStore creates a new in-memory session store.
func (*MemoryStore) AppendAdditionalDirectories ¶
func (m *MemoryStore) AppendAdditionalDirectories(directories []string) (string, error)
func (*MemoryStore) AppendCompaction ¶
func (m *MemoryStore) AppendCompaction(summary, firstKeptEntryID string, tokensBefore int) (string, error)
func (*MemoryStore) AppendMessage ¶
func (m *MemoryStore) AppendMessage(msg provider.Message) (string, error)
func (*MemoryStore) AppendModeChange ¶
func (m *MemoryStore) AppendModeChange(mode string) (string, error)
func (*MemoryStore) AppendModelChange ¶
func (m *MemoryStore) AppendModelChange(providerName, modelID string) (string, error)
func (*MemoryStore) AppendSessionInfo ¶
func (m *MemoryStore) AppendSessionInfo(name string) (string, error)
func (*MemoryStore) AppendThinkingLevelChange ¶
func (m *MemoryStore) AppendThinkingLevelChange(level string) (string, error)
func (*MemoryStore) GetFile ¶
func (m *MemoryStore) GetFile() string
func (*MemoryStore) GetHeader ¶
func (m *MemoryStore) GetHeader() *Header
func (*MemoryStore) GetLatestAdditionalDirectories ¶
func (m *MemoryStore) GetLatestAdditionalDirectories() (AdditionalDirectoriesEntry, bool)
func (*MemoryStore) GetLatestCompaction ¶
func (m *MemoryStore) GetLatestCompaction() (CompactionEntry, bool)
func (*MemoryStore) GetLatestModeChange ¶
func (m *MemoryStore) GetLatestModeChange() (ModeChangeEntry, bool)
func (*MemoryStore) GetLatestModelChange ¶
func (m *MemoryStore) GetLatestModelChange() (ModelChangeEntry, bool)
func (*MemoryStore) GetLatestThinkingLevelChange ¶
func (m *MemoryStore) GetLatestThinkingLevelChange() (ThinkingLevelChangeEntry, bool)
func (*MemoryStore) GetLeafID ¶
func (m *MemoryStore) GetLeafID() *string
func (*MemoryStore) GetMessages ¶
func (m *MemoryStore) GetMessages() []provider.Message
func (*MemoryStore) GetReplayState ¶
func (m *MemoryStore) GetReplayState() ReplayState
func (*MemoryStore) Init ¶
func (m *MemoryStore) Init() error
func (*MemoryStore) InitWithID ¶
func (m *MemoryStore) InitWithID(id string) error
type MessageEntry ¶
MessageEntry contains a conversation message.
type ModeChangeEntry ¶
ModeChangeEntry records a session execution mode change.
type ModelChangeEntry ¶
type ModelChangeEntry struct {
EntryBase
Provider string `json:"provider"`
ModelID string `json:"modelId"`
}
ModelChangeEntry records a model switch.
func LatestModelChangeByID ¶
func LatestModelChangeByID(sessionDir, sessionID string) (ModelChangeEntry, bool, error)
LatestModelChangeByID reads the replayed provider/model binding for a session without exposing SQLite details to protocol adapters.
type Project ¶
type Project struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
func CreateProject ¶
func ListProjects ¶
func RenameProject ¶
type ReplayState ¶
ReplayState is the reconstructed conversation state after applying compactions.
type ResetReport ¶
type ResetReport struct {
// DatabaseBackup is the renamed sessions.db. It is empty when no database
// file existed before the reset.
DatabaseBackup string
// Archived lists every file the reset moved aside, database first then each
// sidecar, so a caller can report what left the directory without deriving
// the archive naming itself.
Archived []ArchivedFile
// LeftBehind lists the session-directory entries a reset does not archive.
// Attachment, channel, and knowledge-base storage each derive their own
// paths elsewhere, so the reset reports everything beside sessions.db
// instead of restating those rules.
LeftBehind []LeftBehindEntry
}
ResetReport describes what one sessions database reset did, and what it deliberately did not do.
func ResetDatabase ¶
func ResetDatabase(sessionDir string) (ResetReport, error)
ResetDatabase moves the shared sessions database and session EventStore aside and creates a fresh, migrated database in their place. The previous database, sidecars, and event store are renamed (never deleted) next to the new file, so the old sessions remain recoverable. A sidecar that outlived its database - an interrupted reset, or a database deleted by hand - is archived under the same name as well: leaving it in place would let the fresh database inherit it and make SQLite's own handling of the leftover decide whether startup succeeds.
Callers must ensure no other process is running against the session directory: a database moved while another process still holds it open keeps being written there, and this process cannot detect that. ActiveRuntimeLeases reports the processes known to hold a run in the database being archived.
type ResponseItemArchive ¶
type ResponseItemArchive struct {
ID int64
SessionID string
LocalTurnID string
ResponseID string
ItemID string
OutputIndex int
ItemType string
ItemStatus string
ItemKey string
SanitizedJSON json.RawMessage
CreatedAt time.Time
}
ResponseItemArchive stores one sanitized normalized item. Raw provider request/response bodies must not be passed here.
func ListResponseItems ¶
func ListResponseItems(sessionDir, sessionID, localTurnID string) ([]ResponseItemArchive, error)
type ResponseReplayTurn ¶
type ResponseReplayTurn struct {
LocalTurnID string
Items []json.RawMessage
}
ResponseReplayTurn groups the native output items belonging to one local Responses turn. It lets callers place those items at the corresponding assistant position while rebuilding a complete local conversation.
func ListResponseReplayTurns ¶
func ListResponseReplayTurns(sessionDir, sessionID string, limit int) ([]ResponseReplayTurn, error)
ListResponseReplayTurns returns completed native output grouped by local turn, ordered by their original completion order.
type ResponseRun ¶
type ResponseRun struct {
ID int64 `json:"id"`
SessionID string `json:"sessionId"`
LocalRunID string `json:"localRunId"`
LocalTurnID string `json:"localTurnId,omitempty"`
MessageID *int64 `json:"messageId,omitempty"`
ResponseID string `json:"responseId,omitempty"`
Provider string `json:"provider"`
API string `json:"api"`
State string `json:"state"`
PollingURL string `json:"pollingUrl,omitempty"`
LastEventSequence *int64 `json:"lastEventSequence,omitempty"`
CancelRequested bool `json:"cancelRequested,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
ResponseRun is the durable state for a Responses background run.
func GetResponseRun ¶
func GetResponseRun(sessionDir, sessionID, localRunID string) (*ResponseRun, error)
func ListResponseRuns ¶
func ListResponseRuns(sessionDir, sessionID string, limit int) ([]ResponseRun, error)
type ResponseSessionState ¶
type ResponseSessionState struct {
SessionID string
StateMode string
PreviousResponseID string
ConversationID string
Provider string
API string
Model string
Version int64
UpdatedAt time.Time
}
ResponseSessionState is the compare-and-swap protected remote lineage for a single local session. Provider config supplies defaults; this record keeps concurrent sessions and concurrent turns from sharing mutable remote state.
func GetResponseSessionState ¶
func GetResponseSessionState(sessionDir, sessionID string) (*ResponseSessionState, error)
GetResponseSessionState returns the durable remote lineage for a local session. A missing record means the caller must use its configured default, normally replay mode.
type ResponseTurn ¶
type ResponseTurn struct {
ID int64
SessionID string
LocalTurnID string
MessageID *int64
RequestID string
ResponseID string
PreviousResponseID string
ConversationID string
Provider string
API string
Model string
StateMode string
Status string
IncompleteReason string
RequestSummary json.RawMessage
ResponseSummary json.RawMessage
CreatedAt time.Time
CompletedAt *time.Time
}
ResponseTurn is the durable lineage and lifecycle summary for one Responses API turn. It intentionally contains summaries, not a second transcript.
func GetResponseTurn ¶
func GetResponseTurn(sessionDir, sessionID, localTurnID string) (*ResponseTurn, error)
type RuntimeLeaseBinding ¶
type RuntimeLeaseBinding struct {
DatabaseIdentity string
SessionID string
RunID string
OwnerInstanceID string
TokenHash string
Epoch int64
Purpose RuntimeLeasePurpose
}
RuntimeLeaseBinding is the Runtime-owned identity of an acquired Session lease. It is safe to expose to trusted in-process code for diagnostics and matching, but must never be accepted from an adapter or client as authority.
func BindRuntimeLeaseToExistingRun ¶
func BindRuntimeLeaseToExistingRun(sessionDir, sessionID, runID string) (RuntimeLeaseBinding, error)
BindRuntimeLeaseToExistingRun promotes a recovery/legacy lease to execution only while the expected Run is still the Session's sole non-terminal Run. Reattach paths call this before registering an in-memory execution.
func CurrentRuntimeLeaseBinding ¶
func CurrentRuntimeLeaseBinding(sessionDir, sessionID string) (RuntimeLeaseBinding, bool)
CurrentRuntimeLeaseBinding returns the lease identity held by this process. It is intended for internal/agentruntime registration and diagnostics only; durable control operations must still revalidate the database row.
func HeldRuntimeLeaseBinding ¶ added in v1.3.105
func HeldRuntimeLeaseBinding(sessionDir, sessionID string) (RuntimeLeaseBinding, <-chan struct{}, bool)
HeldRuntimeLeaseBinding reports the lease identity this process holds for a session together with its loss signal. Callers that must write while the lease is held by an active durable Run need both: the identity to fence the write against the SQLite lease row, and the signal to stop before a takeover makes the fence stale. CurrentRuntimeLeaseBinding alone cannot express "no lease".
func RetainRuntimeLease ¶
func RetainRuntimeLease(sessionDir, sessionID, runID string) (RuntimeLeaseBinding, func(), bool, error)
RetainRuntimeLease adds a Runtime-owned reference to the current execution lease. The caller-owned RuntimeLeaseGuard may be released independently; the durable lease remains active until the returned release function is called. This is intentionally an in-process handoff primitive, never a client-facing authorization mechanism.
type RuntimeLeaseBusStats ¶ added in v1.3.103
type RuntimeLeaseBusStats struct {
// Published counts datagrams written to the loopback broadcast.
Published uint64
// SendFailures counts publishes that never reached the socket.
SendFailures uint64
// Received counts accepted ownership datagrams (after validity and self
// filtering).
Received uint64
// Invalid counts dropped datagrams that failed to parse or validate.
Invalid uint64
// SelfSkipped counts loopback copies of this process's own announcements.
SelfSkipped uint64
// Duplicates counts datagrams suppressed by the dedupe window.
Duplicates uint64
// Applied counts notifications that mutated the ownership cache.
Applied uint64
// Gaps counts detected per-origin sequence gaps (a lost datagram).
Gaps uint64
// Uncertain counts lookups that could not be answered from a fresh entry
// (miss, staleness, gap, or conflict) and therefore require a SQLite read.
Uncertain uint64
}
RuntimeLeaseBusStats is a snapshot of the advisory ownership bus and cache counters. They are diagnostics only: none of them authorizes anything.
func RuntimeLeaseBusMetrics ¶ added in v1.3.103
func RuntimeLeaseBusMetrics() RuntimeLeaseBusStats
RuntimeLeaseBusMetrics returns a snapshot of the ownership bus counters.
type RuntimeLeaseGroup ¶
type RuntimeLeaseGroup struct {
// contains filtered or unexported fields
}
RuntimeLeaseGroup owns an ordered set of Session leases acquired for one multi-Session mutation.
func AcquireMutations ¶
func AcquireMutations(sessionDir string, sessionIDs []string) (*RuntimeLeaseGroup, error)
AcquireMutations reserves multiple idle Sessions in stable order so a cross-Session mutation cannot deadlock another caller taking the same set.
func (*RuntimeLeaseGroup) Guard ¶
func (g *RuntimeLeaseGroup) Guard(sessionID string) *RuntimeLeaseGuard
Guard returns the mutation guard this group holds for sessionID. It is used by one shared multi-session operation to fence each per-session write inside its own transaction without attempting to reacquire the process-local lock.
func (*RuntimeLeaseGroup) Release ¶
func (g *RuntimeLeaseGroup) Release()
Release relinquishes grouped leases in reverse acquisition order.
type RuntimeLeaseGuard ¶
type RuntimeLeaseGuard struct {
// contains filtered or unexported fields
}
RuntimeLeaseGuard owns both the process-local mutex and the durable SQLite lease. Release is idempotent and must be called after every successful acquisition.
func AcquireContentWriteReservation ¶ added in v1.3.105
func AcquireContentWriteReservation(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
AcquireContentWriteReservation serializes one Session content write across every process without requiring the session to be idle.
This is the compatibility reservation for callers that reach the Session Manager directly instead of going through a Runtime-bound execution lease. Such a caller has no Run binding to fence against and must stay behaviourally identical to the legacy SQLite transcript writer, which checked the lease passively and relied on the leaf CAS. `AcquireMutation` cannot serve here: it refuses any session with an active durable Run, so a background/API turn that legitimately appends while its own Run is still open would fail closed.
The reservation therefore borrows the legacy acquisition mode (no active-Run gate) and stays a *reservation*, not an execution grant: purpose `legacy` is a short reservation, it carries no Run ID, it cannot be bound to a Run, and it is excluded from every execution/admission/recovery allowlist. Single writer per session is preserved because acquisition still bumps the epoch and cross-process contention still fails with ErrRuntimeLeaseBusy.
Migration bridge. Owner: internal/agentruntime EventStore convergence. Removal condition: every entry point appends canonical content only through a Runtime-bound execution lease (TUI, CLI, serve/openaiapi background runs, channels and ACP all bind before writing), at which point this function and its call site in eventStoreWriteBinding are deleted.
func AcquireExecutionAdmission ¶
func AcquireExecutionAdmission(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
AcquireExecutionAdmission reserves an existing idle Session for a new Run. The durable admission transaction must subsequently bind the new run ID and transition this same lease to purpose=execution.
func AcquireFork ¶
func AcquireFork(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
AcquireFork reserves an idle source Session while a child snapshot is made.
func AcquireMutation ¶
func AcquireMutation(sessionDir, sessionID string) (*RuntimeLeaseGuard, error)
AcquireMutation reserves an idle Session for a short non-execution change.
func AcquireRecovery ¶
func AcquireRecovery(sessionDir, sessionID, expectedRunID string) (*RuntimeLeaseGuard, error)
AcquireRecovery claims an unowned or expired active Run for fenced recovery.
func AcquireRecoveryContext ¶
func AcquireRecoveryContext(ctx context.Context, sessionDir, sessionID, expectedRunID string) (*RuntimeLeaseGuard, error)
AcquireRecoveryContext bounds the lease acquisition transaction by the recovery attempt deadline.
func (*RuntimeLeaseGuard) Binding ¶
func (g *RuntimeLeaseGuard) Binding() RuntimeLeaseBinding
Binding returns the exact identity acquired by this process.
func (*RuntimeLeaseGuard) Lost ¶
func (g *RuntimeLeaseGuard) Lost() <-chan struct{}
Lost reports when the durable lease can no longer be renewed.
func (*RuntimeLeaseGuard) Release ¶
func (g *RuntimeLeaseGuard) Release()
Release relinquishes the durable lease and then the process-local mutex.
type RuntimeLeaseNotification ¶
type RuntimeLeaseNotification struct {
Version int `json:"version"`
MessageID string `json:"messageId"`
Type string `json:"type"`
SessionID string `json:"sessionId,omitempty"`
// DatabaseIdentity names the canonical session database this notification is
// scoped to (see RuntimeDatabaseIdentity). Global-scope ownership
// synchronization keys its in-memory view by (DatabaseIdentity, SessionID),
// so producers that know the session directory must stamp it. Notifications
// published without one are still valid; receivers then fall back to SQLite.
DatabaseIdentity string `json:"databaseIdentity,omitempty"`
// Path names the database file for the database_rebuilt wake-up; lease
// notifications leave it empty because they are session-scoped.
Path string `json:"path,omitempty"`
Origin string `json:"origin,omitempty"`
OriginInstanceID string `json:"originInstanceId"`
OwnerInstanceID string `json:"ownerInstanceId,omitempty"`
OwnerPID int `json:"ownerPid,omitempty"`
RunID string `json:"runId,omitempty"`
Epoch int64 `json:"epoch,omitempty"`
ExpiresAt int64 `json:"expiresAt,omitempty"`
// Seq is a per-OriginInstanceID monotonic sequence. Receivers use it to drop
// out-of-order duplicates and to detect a gap (a jump means a lost datagram),
// which schedules a coalesced SQLite re-read. It never authorizes anything.
Seq uint64 `json:"seq,omitempty"`
// RunStatus and Phase are optional projection hints carried by state_changed
// events; receivers still re-read the durable Run before projecting it.
RunStatus string `json:"runStatus,omitempty"`
Phase string `json:"phase,omitempty"`
}
RuntimeLeaseNotification is a local-process wake-up signal and an ownership synchronization hint. SQLite leases and durable Run rows remain the sole authority for admission, cancellation, and ownership: receivers re-read the database whenever the synchronized in-memory view is missing, stale, or uncertain, and never authorize, cancel, or terminalize from a notification.
Threat model: the UDP bus is unauthenticated. Any process on the same host can send spoofed notifications (only the loopback source address is checked). This is acceptable because a notification can at most refresh or clear a process-local ownership hint and schedule a database re-read; it can never grant ownership, cancel a run, or change content. A forged database_rebuilt notice can retire a cached connection this process actually holds for the named file and log a warning; notices for databases it never opened are ignored. The bus is deliberately host-only: a directed broadcast on the loopback network, so it never reaches another machine.
type RuntimeLeasePurpose ¶
type RuntimeLeasePurpose string
RuntimeLeasePurpose describes why a process owns the Session-wide lease. Legacy rows use RuntimeLeasePurposeLegacyRun until all callers have migrated to an explicit purpose.
const ( RuntimeLeasePurposeLegacyRun RuntimeLeasePurpose = "run" RuntimeLeasePurposeAdmission RuntimeLeasePurpose = "admission" RuntimeLeasePurposeExecution RuntimeLeasePurpose = "execution" RuntimeLeasePurposeRecovery RuntimeLeasePurpose = "recovery" RuntimeLeasePurposeMutation RuntimeLeasePurpose = "mutation" RuntimeLeasePurposeFork RuntimeLeasePurpose = "fork" // RuntimeLeasePurposeLegacy is the compatibility reservation taken by calls // that reach the Session Manager without a Runtime execution lease. It is a // short reservation like mutation/fork: it never binds a Run and never // grants execution authority. See AcquireContentWriteReservation. RuntimeLeasePurposeLegacy RuntimeLeasePurpose = "legacy" )
type RuntimeLeaseSnapshot ¶
type RuntimeLeaseSnapshot struct {
SessionID string
OwnerInstanceID string
OwnerPID int
OwnerKind string
TokenHash string
Epoch int64
RunID string
Purpose RuntimeLeasePurpose
State string
AcquiredAt time.Time
HeartbeatAt time.Time
ExpiresAt time.Time
UpdatedAt time.Time
Valid bool
}
RuntimeLeaseSnapshot is an immutable database view of one Session lease. TokenHash is an internal identity component used only for matching a Runtime-owned binding; callers must never accept it back as authorization.
type RuntimeOwnershipEntry ¶ added in v1.3.103
type RuntimeOwnershipEntry struct {
DatabaseIdentity string
SessionID string
OwnerInstanceID string
OwnerPID int
Epoch int64
Purpose string
RunID string
State string
RunStatus string
Phase string
ExpiresAt time.Time
Seq uint64
OriginInstanceID string
AppliedAt time.Time
// FromDatabase marks an entry primed by a local SQLite read rather than a
// peer announcement. Both are hints; this is for diagnostics only.
FromDatabase bool
}
RuntimeOwnershipEntry is one process's synchronized view of who holds a Session-wide lease. It is a projection hint derived from a SQLite lease row (either read locally or announced by the owner over the advisory bus); it never authorizes a write.
type RuntimeOwnershipLookup ¶ added in v1.3.103
type RuntimeOwnershipLookup struct {
Entry RuntimeOwnershipEntry
Present bool
Fresh bool
Uncertain bool
}
RuntimeOwnershipLookup is the result of a cache query. Exactly one of the following holds:
- Present && Fresh: use the entry to project ownership without a DB read;
- Uncertain: the entry is stale, conflict-marked, or gap-marked; re-read SQLite;
- zero value: the session is unknown to the cache; re-read SQLite (absence never means "idle").
func LookupRuntimeOwnership ¶ added in v1.3.103
func LookupRuntimeOwnership(databaseIdentity, sessionID string) RuntimeOwnershipLookup
LookupRuntimeOwnership returns the synchronized ownership view for one session. An empty/zero result means "unknown, re-read SQLite".
type RuntimeSubmission ¶
type RuntimeSubmission struct {
ID string
SessionID string
Scope string
KeyHash string
RequestFingerprint string
IntentID string
RunID string
CreatedAt time.Time
}
RuntimeSubmission is the durable admission identity for one original or retry submission. Only a digest of the transport key is persisted.
func GetRuntimeSubmission ¶
func GetRuntimeSubmission(ctx context.Context, sessionDir, sessionID, scope, keyHash string) (*RuntimeSubmission, error)
type RuntimeSubmissionError ¶
type RuntimeSubmissionError struct {
Existing RuntimeSubmission
Conflict bool
}
RuntimeSubmissionError carries the canonical Run identity selected by a competing or replayed admission.
func (*RuntimeSubmissionError) Error ¶
func (e *RuntimeSubmissionError) Error() string
func (*RuntimeSubmissionError) Unwrap ¶
func (e *RuntimeSubmissionError) Unwrap() error
type SequencedMessage ¶
SequencedMessage is a persisted conversation message with its entries.seq cursor.
func ListSessionMessagesAfter ¶
func ListSessionMessagesAfter(sessionDir, sessionID string, afterSeq int64, limit int) ([]SequencedMessage, error)
ListSessionMessagesAfter returns persisted message rows after entries.seq.
func ListSessionMessagesBefore ¶
func ListSessionMessagesBefore(sessionDir, sessionID string, beforeSeq int64, limit int) ([]SequencedMessage, error)
ListSessionMessagesBefore returns messages with seq < beforeSeq, newest first limited to `limit`.
func ListSessionMessagesLatest ¶
func ListSessionMessagesLatest(sessionDir, sessionID string, limit int) ([]SequencedMessage, error)
ListSessionMessagesLatest returns the latest N message entries (highest seq first).
func ListSessionMessagesWithSeq ¶
func ListSessionMessagesWithSeq(sessionDir, sessionID string) ([]SequencedMessage, error)
ListSessionMessagesWithSeq returns the visible replay messages for a session, preserving each message row's entries.seq cursor.
type SequencedSessionCapabilityEvent ¶
type SequencedSessionCapabilityEvent struct {
Seq int64
Event SessionCapabilityEvent
}
SequencedSessionCapabilityEvent is a capability event with its table cursor.
func ListSessionCapabilityEventsAfter ¶
func ListSessionCapabilityEventsAfter(sessionDir, sessionID string, afterSeq int64, limit int) ([]SequencedSessionCapabilityEvent, error)
ListSessionCapabilityEventsAfter returns capability events after session_capability_events.seq.
func ListSessionCapabilityEventsWithSeq ¶
func ListSessionCapabilityEventsWithSeq(sessionDir, sessionID string) ([]SequencedSessionCapabilityEvent, error)
ListSessionCapabilityEventsWithSeq returns capability events with their seq cursor.
type SequencedSessionRunEvent ¶
type SequencedSessionRunEvent struct {
Seq int64
Event SessionRunEvent
}
SequencedSessionRunEvent is a run lifecycle event with its table cursor.
func ListSessionRunEventsAfter ¶
func ListSessionRunEventsAfter(sessionDir, sessionID string, afterSeq int64, limit int) ([]SequencedSessionRunEvent, error)
ListSessionRunEventsAfter returns run events after session_run_events.seq.
func ListSessionRunEventsWithSeq ¶
func ListSessionRunEventsWithSeq(sessionDir, sessionID string) ([]SequencedSessionRunEvent, error)
ListSessionRunEventsWithSeq returns run events with their session_run_events.seq cursor.
type SessionBindings ¶ added in v1.3.105
type SessionBindings struct {
ModelChange ModelChangeEntry
HasModelChange bool
ModeChange ModeChangeEntry
HasModeChange bool
ThinkingLevelChange ThinkingLevelChangeEntry
HasThinkingLevelChange bool
AdditionalDirectories AdditionalDirectoriesEntry
HasAdditionalDirectories bool
}
SessionBindings is the latest persisted front-end-neutral binding state of a session: provider/model, execution mode, thinking level, and additional directory roots. List projections use it instead of replaying a whole transcript just to recover a handful of metadata entries.
type SessionCapabilities ¶
type SessionCapabilities struct {
SessionID string
Mode string
DisplayMode string
DelegateMode bool
MultiAgent bool
Workflows bool
WebSearch bool
Browser bool
A2AMaster bool
UpdatedAt time.Time
}
SessionCapabilities stores persisted per-session runtime capability state.
func LoadSessionCapabilities ¶
func LoadSessionCapabilities(sessionDir, sessionID string) (*SessionCapabilities, bool, error)
LoadSessionCapabilities loads persisted capabilities for a session.
type SessionCapabilityEvent ¶
type SessionCapabilityEvent struct {
ID string
SessionID string
RunID string
EventType string
Source string
Actor string
Capability string
OldValue string
NewValue string
Timestamp time.Time
Data json.RawMessage
}
SessionCapabilityEvent records one capability state transition.
func ListSessionCapabilityEvents ¶
func ListSessionCapabilityEvents(sessionDir, sessionID string) ([]SessionCapabilityEvent, error)
ListSessionCapabilityEvents returns capability events for a session, ordered by insertion.
type SessionDetail ¶
type SessionDetail struct {
SessionInfo
ID string
MessageCount int
Preview string // first user message (truncated)
}
SessionDetail contains detailed metadata about a session for display.
func ListAllDetailed ¶
func ListAllDetailed(sessionDir string, opts ...ListOption) ([]SessionDetail, error)
ListAllDetailed lists sessions with details across all working directories.
func ListForDirDetailed ¶
func ListForDirDetailed(cwd, sessionDir string) ([]SessionDetail, error)
ListForDirDetailed lists sessions with details (ID, message count, preview).
type SessionExecutionFacts ¶
type SessionExecutionFacts struct {
DatabaseIdentity string
SessionID string
SessionExists bool
DatabaseNow time.Time
ActiveRuns []SessionRun
Lease *RuntimeLeaseSnapshot
Recovery *SessionRunRecovery
RemoteRun *ResponseRun
}
SessionExecutionFacts contains the durable Run and lease rows observed from one SQLite read transaction and one SQLite clock sample. ActiveRuns normally contains at most one row; retaining the slice lets Runtime surface corrupted or legacy databases with multiple active rows as inconsistent.
func ReadSessionExecutionFacts ¶
func ReadSessionExecutionFacts(sessionDir, sessionID string) (SessionExecutionFacts, error)
ReadSessionExecutionFacts reads the durable execution facts for one Session from a single transaction. It deliberately does not consult process-local runtime state; internal/agentruntime combines this immutable view with its own registered execution bindings.
func ReadSessionExecutionFactsContext ¶
func ReadSessionExecutionFactsContext(ctx context.Context, sessionDir, sessionID string) (SessionExecutionFacts, error)
ReadSessionExecutionFactsContext is the cancellable form used by bounded recovery attempts. The transaction and every query in the snapshot share the caller's deadline.
type SessionInfo ¶
type SessionInfo struct {
Path string
// ModTime is when the session was last used (its newest persisted entry),
// which is what every listing orders and displays. CreatedAt keeps the
// creation timestamp separately; it names the session handle and never
// stands in for activity.
ModTime time.Time
CreatedAt time.Time
Name string
Cwd string
ChannelType string
ChannelID string
ParentSession string
ForkBoundarySeq int64
SeedLength int64
ForkKind string
ExpertID string
}
SessionInfo contains metadata about a session file.
func ListAll ¶
func ListAll(sessionDir string, opts ...ListOption) ([]SessionInfo, error)
ListAll lists session files across all working directories.
func ListForDir ¶
func ListForDir(cwd, sessionDir string) ([]SessionInfo, error)
ListForDir lists session files for a given working directory. The returned sessions carry their last activity time, not just their creation time, so a caller that continues "the most recent session" continues the one a person actually last worked in.
type SessionInfoEntry ¶
type SessionInfoEntry struct {
EntryBase
Name string `json:"name"`
Source string `json:"source,omitempty"` // "manual" or "auto"
}
SessionInfoEntry stores session metadata.
type SessionMetadata ¶
type SessionMetadata struct {
ProjectID string `json:"projectId,omitempty"`
Pinned bool `json:"pinned"`
// UpdatedAt is the persisted revision time of the metadata row. It is
// read-only output; SetSessionMetadata always stamps the write time itself.
UpdatedAt time.Time `json:"updatedAt,omitempty"`
}
func GetSessionMetadata ¶
func GetSessionMetadata(sessionDir, sessionID string) (SessionMetadata, error)
type SessionRun ¶
type SessionRun struct {
ID string
SessionID string
IntentID string
RetryOf string
Attempt int
WorkDir string
Source string
Model string
Mode string
Status string
StartedAt time.Time
UpdatedAt time.Time
FinishedAt *time.Time
Error string
ErrorInfo json.RawMessage
Progress json.RawMessage
Usage json.RawMessage
ContextUsage json.RawMessage
// InputResourceIDs are Runtime-prepared resources admitted with this Run.
// They are bound by the same transaction as the intent/run/start event.
InputResourceIDs []string
// Submission fields are admission-only digests. They are reserved in the
// same transaction as the intent, Run, turn, resources, and start event.
SubmissionKeyHash string
SubmissionScope string
SubmissionFingerprint string
// UserMessage is the canonical user entry admitted with a conversation
// Run. It is admission-only; transcript replay remains the source of truth.
UserEntryID string
UserMessage *provider.Message
// AssistantMessage is the final assistant entry held by the Runtime until
// terminalization. It is intentionally transient and is committed together
// with the terminal Run/turn and delivery plan.
AssistantEntryID string
AssistantMessage *provider.Message
// DeliveryPlan is terminal-only. The terminal transaction creates its
// outbox rows together with the Run, turn, and terminal event transition.
DeliveryPlan *DeliveryPlan
}
SessionRun is the durable lifecycle record for one agent execution.
func GetActiveSessionRun ¶
func GetActiveSessionRun(sessionDir, sessionID string) (*SessionRun, error)
func GetActiveSessionRunContext ¶
func GetActiveSessionRunContext(ctx context.Context, sessionDir, sessionID string) (*SessionRun, error)
func GetSessionRun ¶
func GetSessionRun(sessionDir, runID string) (*SessionRun, error)
func GetSessionRunContext ¶
func GetSessionRunContext(ctx context.Context, sessionDir, runID string) (*SessionRun, error)
func LatestSessionRunForIntent ¶
func LatestSessionRunForIntent(sessionDir, sessionID, intentID string) (*SessionRun, error)
LatestSessionRunForIntent returns the highest-attempt Run in an immutable intent chain. Retry admission uses it to prevent two callers from retrying an older terminal attempt after a newer attempt already exists.
func ListOrphanedSessionRuns ¶
func ListOrphanedSessionRuns(sessionDir string) ([]SessionRun, error)
ListOrphanedSessionRuns returns all runs that are in a non-terminal state. This is used during server startup to recover runs that were active when the previous server instance stopped.
func ListOrphanedSessionRunsContext ¶
func ListOrphanedSessionRunsContext(ctx context.Context, sessionDir string) ([]SessionRun, error)
func ListSessionRuns ¶
func ListSessionRuns(sessionDir, sessionID string, limit int) ([]SessionRun, error)
type SessionRunEvent ¶
type SessionRunEvent struct {
ID string
SessionID string
RunID string
EventType string
Source string
Status string
Model string
Mode string
Timestamp time.Time
Data json.RawMessage
}
SessionRunEvent records one lifecycle event for a single chat/run execution.
func ListSessionRunEvents ¶
func ListSessionRunEvents(sessionDir, sessionID string) ([]SessionRunEvent, error)
ListSessionRunEvents returns run events for a session, ordered by insertion.
func ListSessionRunEventsContext ¶
func ListSessionRunEventsContext(ctx context.Context, sessionDir, sessionID string) ([]SessionRunEvent, error)
ListSessionRunEventsContext is the cancellable event replay query used by bounded recovery and reconnect paths.
type SessionRunRecovery ¶
type SessionRunRecovery struct {
RunID string
SessionID string
State SessionRunRecoveryState
TriggerSource string
ReasonCode string
Attempt int
PreviousLeaseEpoch int64
LastError string
NextRetryAt *time.Time
StartedAt time.Time
UpdatedAt time.Time
CompletedAt *time.Time
}
SessionRunRecovery is the durable diagnostic and retry state for orphan reconciliation. It never grants ownership; the recovery lease remains the sole authority for changing a Run.
func BeginSessionRunRecovery ¶
func BeginSessionRunRecovery(sessionDir, sessionID, runID, triggerSource, reasonCode string, previousLeaseEpoch int64) (*SessionRunRecovery, error)
BeginSessionRunRecovery records an attempt while verifying the exact purpose=recovery lease and target Run in the same transaction.
func BeginSessionRunRecoveryContext ¶
func BeginSessionRunRecoveryContext(ctx context.Context, sessionDir, sessionID, runID, triggerSource, reasonCode string, previousLeaseEpoch int64) (*SessionRunRecovery, error)
BeginSessionRunRecoveryContext is the cancellable form used by the bounded Runtime recovery coordinator.
func GetSessionRunRecovery ¶
func GetSessionRunRecovery(sessionDir, runID string) (*SessionRunRecovery, error)
GetSessionRunRecovery returns the last durable recovery disposition for a Run. A missing row is represented by (nil, nil).
type SessionRunRecoveryState ¶
type SessionRunRecoveryState string
const ( SessionRunRecoveryRunning SessionRunRecoveryState = "recovering" SessionRunRecoveryFailed SessionRunRecoveryState = "failed" SessionRunRecoveryComplete SessionRunRecoveryState = "completed" SessionRunRecoveryDetached SessionRunRecoveryState = "detached_remote" )
type SessionWakeCoalescer ¶ added in v1.3.103
type SessionWakeCoalescer struct {
// contains filtered or unexported fields
}
SessionWakeCoalescer collapses bursts of advisory wake-ups for one session into a single in-flight handler invocation plus at most one trailing re-run. It bounds the receive side of the unauthenticated UDP lease bus: a spoofed or chatty flood for one session can never spawn more than one handler goroutine at a time, and the trailing re-run guarantees the handler re-reads the durable state after the last wake in a burst, so projections still converge.
The handler must be idempotent and re-read authoritative state itself (the bus never carries state). Wakes for distinct session IDs remain independent; the residual amplification for a flood of unique random IDs is one cheap durable read per ID, which the loopback-only trust boundary accepts.
func NewSessionWakeCoalescer ¶ added in v1.3.103
func NewSessionWakeCoalescer(handler func(sessionID string)) *SessionWakeCoalescer
NewSessionWakeCoalescer creates a coalescer for one handler. A nil handler makes every wake a no-op.
func (*SessionWakeCoalescer) Wake ¶ added in v1.3.103
func (c *SessionWakeCoalescer) Wake(sessionID string)
Wake schedules the handler for sessionID unless it is already in flight, in which case exactly one trailing re-run is remembered. It never blocks.
type Store ¶
type Store interface {
// Init initializes the session store, creating the underlying
// database or storage if needed.
Init() error
// InitWithID initializes the session with a specific ID.
// An empty id generates a new one.
InitWithID(id string) error
// AppendMessage persists a conversation message and returns its entry ID.
AppendMessage(msg provider.Message) (string, error)
// AppendCompaction records a context compaction event.
AppendCompaction(summary, firstKeptEntryID string, tokensBefore int) (string, error)
// AppendModelChange records a model switch.
AppendModelChange(providerName, modelID string) (string, error)
// AppendModeChange records a session execution mode change.
AppendModeChange(mode string) (string, error)
// AppendThinkingLevelChange records a thinking level change.
AppendThinkingLevelChange(level string) (string, error)
AppendAdditionalDirectories(directories []string) (string, error)
// AppendSessionInfo records session metadata.
AppendSessionInfo(name string) (string, error)
// GetMessages returns all messages in the current branch,
// with compaction summaries applied.
GetMessages() []provider.Message
// GetReplayState returns the full replay state including
// messages and their entry IDs.
GetReplayState() ReplayState
// GetLeafID returns the current leaf entry ID, or nil if empty.
GetLeafID() *string
// GetLatestCompaction returns the most recent compaction entry,
// or (zero, false) if none exists.
GetLatestCompaction() (CompactionEntry, bool)
// GetLatestModelChange returns the most recent persisted model binding.
GetLatestModelChange() (ModelChangeEntry, bool)
// GetLatestModeChange returns the most recent persisted session mode.
GetLatestModeChange() (ModeChangeEntry, bool)
// GetLatestThinkingLevelChange returns the most recent persisted thinking level.
GetLatestThinkingLevelChange() (ThinkingLevelChangeEntry, bool)
GetLatestAdditionalDirectories() (AdditionalDirectoriesEntry, bool)
// GetFile returns the session file path (handle file for SQLite).
GetFile() string
// GetHeader returns the session header with metadata.
GetHeader() *Header
}
Store is the interface for session persistence backends. Manager implements this interface using SQLite. Alternative backends (in-memory for testing, cloud storage, etc.) can implement Store to swap the persistence layer without changing agent or UI code.
type ThinkingLevelChangeEntry ¶
ThinkingLevelChangeEntry records a thinking level change.
type ToolExecutionRecord ¶
type ToolExecutionRecord struct {
ID int64
SessionID string
LocalTurnID string
ExecutionKey string
Provider string
API string
ResponseID string
ProviderCallID string
ToolKind string
ToolName string
ArgsHash string
ExecutionState string
ResultSummary json.RawMessage
ProviderMetadata json.RawMessage
SideEffecting bool
CreatedAt time.Time
CompletedAt *time.Time
}
ToolExecutionRecord is the cross-protocol idempotency record for a tool invocation. ExecutionKey is local and remains the deduplication authority.
func ClaimToolExecutionRecord ¶
func ClaimToolExecutionRecord(sessionDir string, record ToolExecutionRecord) (*ToolExecutionRecord, bool, error)
ClaimToolExecutionRecord atomically claims an execution key. A false created result means another request already owns the key and its record must be consulted before executing a side effect.
func RequestToolExecutionRecoveryRecords ¶
func RequestToolExecutionRecoveryRecords(sessionDir, sessionID, localTurnID string, providerCallIDs []string) ([]ToolExecutionRecord, int64, error)
RequestToolExecutionRecoveryRecords records explicit user confirmation and returns only matching interrupted calls. The records are retained as audit evidence while recovery starts as a fresh execution; terminal Runs are never reactivated to consume these records.
type TurnEndEntry ¶
type TurnEndEntry struct {
EntryBase
TurnID string `json:"turnId"`
IntentID string `json:"intentId,omitempty"`
RunID string `json:"runId,omitempty"`
Status string `json:"status"`
StopReason string `json:"stopReason,omitempty"`
}
TurnEndEntry marks the durable terminal boundary of a logical conversation turn. It is persisted for fork resolution and recovery, not model replay.
type TurnStartEntry ¶
type TurnStartEntry struct {
EntryBase
TurnID string `json:"turnId"`
IntentID string `json:"intentId,omitempty"`
RunID string `json:"runId,omitempty"`
Attempt int `json:"attempt,omitempty"`
}
TurnStartEntry marks the durable beginning of a logical conversation turn. It is persisted for boundary recovery but is excluded from provider replay.
type Worktree ¶ added in v1.3.103
type Worktree struct {
ID string `json:"id"`
Name string `json:"name"`
Branch string `json:"branch,omitempty"`
Directory string `json:"directory"`
RepositoryRoot string `json:"repositoryRoot"`
ProjectID string `json:"projectId,omitempty"`
StartCommand string `json:"startCommand,omitempty"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
// External marks a git worktree that exists in the repository but is not
// registered (for example one created by hand). It is read-only.
External bool `json:"external,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Worktree is the session-domain projection of one Runtime-owned worktree registry row. Git remains the content authority (existence, branch, cleanliness); this record is the identity/ownership/authorization authority.
func CreateWorktreeRecord ¶ added in v1.3.103
CreateWorktreeRecord inserts a new registry row. It is the only writer of a worktree's identity; callers must supply a stable id and the canonical directory. Git materialization is a separate, Runtime-owned step.
func GetWorktreeByDirectory ¶ added in v1.3.103
GetWorktreeByDirectory returns the registered worktree for a canonical directory, or a zero Worktree when it does not exist.
func GetWorktreeByID ¶ added in v1.3.103
GetWorktreeByID returns the registered worktree, or a zero Worktree when it does not exist.
func ListWorktrees ¶ added in v1.3.103
ListWorktrees returns registry rows, optionally filtered by repository root and/or project id.
Source Files
¶
- artifacts.go
- bindings.go
- conversation_turn.go
- database.go
- database_recovery_notice.go
- database_reset.go
- decision_events.go
- delivery_store.go
- entry.go
- esm_guidance.go
- event_entry.go
- event_intents.go
- event_store.go
- event_store_append.go
- event_store_display.go
- event_turn.go
- execution_facts.go
- execution_intent.go
- fork.go
- fork_event_store.go
- identity_lock.go
- input_resources.go
- knowledge_bases.go
- knowledge_database.go
- lock_registry.go
- memory_store.go
- message_normalize.go
- migrations.go
- projects.go
- response_store.go
- run_recovery.go
- run_store.go
- run_user_message.go
- runtime_lease_bus.go
- runtime_lease_bus_socket_unix.go
- runtime_lease_health.go
- runtime_lease_metrics.go
- runtime_lease_status.go
- runtime_lock.go
- runtime_ownership_cache.go
- runtime_submission.go
- runtime_wake_coalescer.go
- schema.go
- session.go
- store.go
- workdir.go
- worktrees.go