session

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Overview

Package session owns Peen's durable transport-neutral session transcript.

Index

Constants

View Source
const (
	ExecutionUserStopReason   = "user requested stop"
	ExecutionUserCancelReason = "user cancelled child agent"
	AgentMessageSenderAgent   = "agent"

	ExecutionTerminalHooksActivityName = "terminalHooksV1"

	EventTypeUserMessageCreated   = "userMessage.created"
	EventTypeUserMessageQueued    = "userMessage.queued"
	EventTypeUserMessageDelivered = "userMessage.delivered"
	EventTypeSkillInjected        = "skill.injected"
	EventTypeAgentRunCompleted    = "agent.run.completed"
	EventTypeAgentRunFailed       = "agent.run.failed"
	EventTypeAgentRunCancelled    = "agent.run.cancelled"
	EventTypeTurnFailed           = "turn.failed"
	EventTypeTurnCancelled        = "turn.cancelled"

	// TurnFailureAgentRun and TurnFailureCancelled are the reasons a turn's
	// terminal frame carries, the only values the WebSocket contract allows.
	TurnFailureAgentRun  = "agentRun"
	TurnFailureCancelled = "cancelled"

	// TurnEndNoticeSource is the source of the turn.failed and turn.cancelled
	// notices Peen records when a turn ends without completing.
	TurnEndNoticeSource = "session.turn"
)
View Source
const (
	ExecutionFinishActivityName = "finishExecutionV1"
	ExecutionFinishStepID       = "finish"
)
View Source
const (
	// MaximumFeedLimit bounds one ListFeed page across events, agent run
	// events, and notices combined.
	MaximumFeedLimit = 200

	// FeedEventTypeNoticeCreated is the live frame type a notice feed item
	// carries. A notice has no event_type column of its own, unlike the
	// event and agent run event tables it shares the feed sequence with.
	FeedEventTypeNoticeCreated = "notice.created"
)
View Source
const (
	// DefaultPageLimit is the API default for transcript pagination.
	DefaultPageLimit = 50
	// MaximumPageLimit bounds one transcript page at the storage boundary.
	MaximumPageLimit = 200
)
View Source
const ExecutionCrashPauseReason = "paused after a crash"

ExecutionCrashPauseReason is recorded on work paused because the process that ran it died.

View Source
const ExecutionEventTypeCompletionSealed = ExecutionEventType(
	"execution.completionSealed",
)
View Source
const ExecutionEventTypeInboxResumed = ExecutionEventType("inbox.resumed")
View Source
const ExecutionEventTypeTurnRestored = ExecutionEventType(
	"execution.turnRestored",
)

Variables

View Source
var (
	// ErrExecutionInboxPending requires continuation before successful finish.
	// Storage and transport return it joined with commerr.ErrConflict.
	ErrExecutionInboxPending = errors.New("execution inbox has pending work")
	// ErrSessionBusy reports a concurrent turn attempt for one session.
	ErrSessionBusy = commerr.ErrLockHeld
	// ErrInvalidPage reports invalid transcript pagination arguments.
	ErrInvalidPage = commerr.ErrValidationFailed

	// ErrRunningTurnSettingsChange reports a message sent while a turn runs
	// that asks for another model, reasoning level, or system prompt. A
	// queued message joins the running turn, so it cannot change how that
	// turn runs. It is always joined with commerr.ErrValidationFailed, and
	// its text is written for the person who sent the message.
	ErrRunningTurnSettingsChange = errors.New(
		"a message sent during a running turn cannot change its model, reasoning, or system prompt",
	)

	// ErrAgentRunFinished reports a message sent to a child agent that is no
	// longer running, so nothing would ever read it, or a non-terminal event
	// recorded after the run ended. It is always joined with
	// commerr.ErrConflict.
	ErrAgentRunFinished = errors.New("agent has finished")
	// ErrAgentRunNotFound reports a message sent to an agent run the session
	// never had. It is always joined with commerr.ErrNotFound.
	ErrAgentRunNotFound = errors.New("agent run not found")
)

Functions

func IsAgentRunTerminalEventType added in v0.32.0

func IsAgentRunTerminalEventType(eventType string) bool

IsAgentRunTerminalEventType reports whether an event type ends a child run's event stream. It is the only kind a run accepts after it has ended.

func ValidateStopRevision added in v0.25.0

func ValidateStopRevision(expected *int64, current int64) error

ValidateStopRevision refuses requests accepted before a later stop. Nil adopts the current revision for callers making a fresh admission.

func WithAgentRunOwner added in v0.24.0

func WithAgentRunOwner(
	ctx context.Context,
	generationID uuid.UUID,
) context.Context

WithAgentRunOwner fences child writes against a replaced worker. Apply it only to worker mutations; historical reads remain available to new workers.

Types

type AcceptExecutionMessageInput added in v0.25.0

type AcceptExecutionMessageInput struct {
	ExpectedStopRevision *int64 `json:"expectedStopRevision,omitempty"`

	RequestID        uuid.UUID            `json:"requestId"`
	SourceEventID    uuid.UUID            `json:"sourceEventId,omitempty"`
	WorkingDirectory string               `json:"workingDirectory"`
	Message          string               `json:"message"`
	Parts            []ExecutionInboxPart `json:"parts"`
	Capacity         int                  `json:"capacity"`
	// ResumeNotice is what a paused child reads ahead of this message: why
	// it was paused. A message to a paused child resumes it, so the notice is
	// queued only then, and ignored for a running child.
	ResumeNotice string `json:"resumeNotice,omitempty"`
}

type ActivityClaim added in v0.25.0

type ActivityClaim struct {
	Activity *models.ExecutionActivity `json:"activity"`
	Lease    ActivityLease             `json:"lease"`
	Decision ActivityDecision          `json:"decision"`
}

type ActivityDecision added in v0.25.0

type ActivityDecision string
const (
	ActivityDecisionExecute   ActivityDecision = "execute"
	ActivityDecisionReuse     ActivityDecision = "reuse"
	ActivityDecisionPaused    ActivityDecision = "paused"
	ActivityDecisionReconcile ActivityDecision = "reconcile"
)

type ActivityLease added in v0.25.0

type ActivityLease struct {
	ID           uuid.UUID `json:"id"`
	GenerationID uuid.UUID `json:"generationId"`
	Attempt      int64     `json:"attempt"`
}

type ActivityResolution added in v0.25.0

type ActivityResolution string
const (
	ActivityResolutionRetry  ActivityResolution = "retry"
	ActivityResolutionAccept ActivityResolution = "accept"
)

type AdmissionGate added in v0.17.0

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

AdmissionGate admits messages to each session one at a time, in the order their places were reserved.

Admitting a message means deciding whether it starts a turn or joins the running turn's queue, and making that decision take effect. Two messages for one session admitted at once can both see an idle session and race for its lease, so the loser is refused as busy even though it only had to queue, and the one sent second can start the turn. Holding the gate across the decision and its effect removes both races.

Sessions do not share a line, so a slow admission in one never delays another. A session's line exists only while a ticket is in it.

func NewAdmissionGate added in v0.17.0

func NewAdmissionGate() *AdmissionGate

NewAdmissionGate builds a gate with every session's line empty.

func (*AdmissionGate) Acquire added in v0.17.0

func (g *AdmissionGate) Acquire(
	ctx context.Context,
	sessionID uuid.UUID,
) (func(), error)

Acquire reserves a place and waits for it. It returns the ticket's release function, which is safe to call more than once, so a caller can release as soon as its message is admitted and still defer the call for every failure path.

func (*AdmissionGate) CancelPending added in v0.25.0

func (g *AdmissionGate) CancelPending(sessionID uuid.UUID) int

CancelPending invalidates current admissions, preserving future tickets. It cancels bound preparation contexts and leaves other sessions untouched.

func (*AdmissionGate) Reserve added in v0.17.0

func (g *AdmissionGate) Reserve(sessionID uuid.UUID) *AdmissionTicket

Reserve takes the next place in the session's line without waiting.

A caller that hands the message to another goroutine reserves before doing so, which fixes the admission order to the order the messages were received rather than the order those goroutines happen to run in. The ticket must be released on every path, admitted or not.

type AdmissionTicket added in v0.17.0

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

AdmissionTicket is one message's place in its session's admission line.

func (*AdmissionTicket) BindContext added in v0.25.0

func (t *AdmissionTicket) BindContext(
	ctx context.Context,
) (context.Context, context.CancelFunc)

BindContext keeps preparation cancellable until this ticket leaves admission. Releasing admission preserves the context until the caller cancels it.

func (*AdmissionTicket) Release added in v0.17.0

func (t *AdmissionTicket) Release()

Release leaves the line. When the ticket was at the front, the next one is admitted. Releasing again does nothing.

func (*AdmissionTicket) SessionID added in v0.17.0

func (t *AdmissionTicket) SessionID() uuid.UUID

SessionID is the session whose line the ticket is in.

func (*AdmissionTicket) Wait added in v0.17.0

func (t *AdmissionTicket) Wait(ctx context.Context) error

Wait blocks until every ticket reserved before this one is released. A caller that stops waiting cancels ctx, which returns the context error; the ticket still holds its place until it is released.

type AgentRunCompactionInput added in v0.11.0

type AgentRunCompactionInput struct {
	ID                     uuid.UUID
	FromMessageID          uuid.UUID
	ToMessageID            uuid.UUID
	FromSequence           int64
	ToSequence             int64
	DirectFromSequence     int64
	DirectToSequence       int64
	Summary                string
	SourceMessageCount     int64
	InputTokenCount        int64
	SummaryTokenCount      int64
	ModelID                string
	PromptHash             string
	SupersedesCompactionID *uuid.UUID
}

AgentRunCompactionInput stores one immutable child replacement summary.

type AgentRunCompactionPage added in v0.11.0

type AgentRunCompactionPage struct {
	Items   []*models.AgentRunCompaction
	Limit   int
	Offset  int
	HasMore bool
}

AgentRunCompactionPage is one complete child compaction page, newest first.

type AgentRunEventInput added in v0.4.0

type AgentRunEventInput struct {
	ID          uuid.UUID `json:"id"`
	EventType   string    `json:"eventType"`
	PayloadJSON string    `json:"payloadJson"`
	CreatedAt   time.Time `json:"createdAt"`
}

AgentRunEventInput is one immutable child-agent event.

type AgentRunEventPage added in v0.4.0

type AgentRunEventPage struct {
	Run        *models.AgentRun
	Items      []*models.AgentRunEvent
	NextCursor int64
	HasMore    bool
}

AgentRunEventPage is one complete ordered child-event window.

type AgentRunHistoryResult added in v0.11.0

type AgentRunHistoryResult struct {
	Compaction *models.AgentRunCompaction
	Messages   []*models.AgentRunMessage
}

AgentRunHistoryResult is a child's current summary plus the raw tail after it, which is what rebuilds the child conversation from SQLite.

type AgentRunMessageInput added in v0.11.0

type AgentRunMessageInput struct {
	ID            uuid.UUID          `json:"id"`
	Role          models.MessageRole `json:"role"`
	Content       string             `json:"content"`
	ModelID       string             `json:"modelId"`
	Thinking      string             `json:"thinking"`
	ToolCallsJSON string             `json:"toolCallsJson"`
	ToolCallID    string             `json:"toolCallId"`
	IsError       bool               `json:"isError"`
	Incomplete    bool               `json:"incomplete"`
	Directory     string             `json:"directory,omitempty"`
	SystemPrompt  string             `json:"systemPrompt,omitempty"`
}

AgentRunMessageInput is one prompt-visible record in a child agent's own transcript. A successful directory result also checkpoints the run's current workspace and system prompt in the same transaction.

type AgentRunMessagePage added in v0.11.0

type AgentRunMessagePage struct {
	Items   []*models.AgentRunMessage
	Limit   int
	Offset  int
	HasMore bool
}

AgentRunMessagePage is one complete child transcript page, oldest first.

type AgentRunPage added in v0.4.0

type AgentRunPage struct {
	Items   []*models.AgentRun
	Limit   int
	Offset  int
	HasMore bool
}

AgentRunPage is one complete child-run page.

type AgentSpaceDecisionPage added in v0.19.0

type AgentSpaceDecisionPage struct {
	Items   []*models.SessionAgentSpaceDecision
	Limit   int
	Offset  int
	HasMore bool
}

AgentSpaceDecisionPage is one complete page of agent space decisions.

type AppendJobOutputInput added in v0.4.0

type AppendJobOutputInput struct {
	ID        uuid.UUID
	Stream    models.JobOutputStream
	Content   string
	CreatedAt time.Time
}

AppendJobOutputInput is one immutable line in the combined process stream.

type ChildExecutionInboxStorage added in v0.25.0

type ChildExecutionInboxStorage interface {
	AcceptChildExecutionMessage(context.Context, uuid.UUID, uuid.UUID,
		AcceptExecutionMessageInput) (*ExecutionInboxAcceptance, error)
	DeliverChildExecutionMessages(context.Context, uuid.UUID, ActivityLease,
		[]uuid.UUID) (*ExecutionInboxDelivery, error)
}

type ClaimAgentRunInput added in v0.24.0

type ClaimAgentRunInput struct {
	GenerationID         uuid.UUID            `json:"generationId"`
	PreviousGenerationID string               `json:"previousGenerationId"`
	PreviousState        models.AgentRunState `json:"previousState"`
}

type CompactionInput

type CompactionInput struct {
	ID                     uuid.UUID  `json:"id"`
	FromMessageID          uuid.UUID  `json:"fromMessageId"`
	ToMessageID            uuid.UUID  `json:"toMessageId"`
	FromSequence           int64      `json:"fromSequence"`
	ToSequence             int64      `json:"toSequence"`
	DirectFromSequence     int64      `json:"directFromSequence"`
	DirectToSequence       int64      `json:"directToSequence"`
	Summary                string     `json:"summary"`
	SourceMessageCount     int64      `json:"sourceMessageCount"`
	InputTokenCount        int64      `json:"inputTokenCount"`
	SummaryTokenCount      int64      `json:"summaryTokenCount"`
	ModelID                string     `json:"modelId"`
	PromptHash             string     `json:"promptHash"`
	SupersedesCompactionID *uuid.UUID `json:"supersedesCompactionId"`
}

CompactionInput stores one immutable replacement summary.

type CompactionPage added in v0.4.0

type CompactionPage struct {
	Items   []*models.Compaction
	Limit   int
	Offset  int
	HasMore bool
}

CompactionPage is one complete session-local compaction page.

type CompleteActivityInput added in v0.25.0

type CompleteActivityInput struct {
	Output          json.RawMessage           `json:"output"`
	Context         json.RawMessage           `json:"context"`
	Finish          *FinishExecutionInput     `json:"finish,omitempty"`
	Compaction      *CompactionInput          `json:"compaction,omitempty"`
	RootProjection  *ExecutionRootProjection  `json:"rootProjection,omitempty"`
	ChildProjection *ExecutionChildProjection `json:"childProjection,omitempty"`
}

type CreateExecutionInput added in v0.25.0

type CreateExecutionInput struct {
	DeferredInboxID     *uuid.UUID      `json:"deferredInboxId,omitempty"`
	ID                  uuid.UUID       `json:"id"`
	RootTurnID          uuid.UUID       `json:"rootTurnId"`
	ParentExecutionID   *uuid.UUID      `json:"parentExecutionId,omitempty"`
	AgentRunID          *uuid.UUID      `json:"agentRunId,omitempty"`
	WorkflowVersion     string          `json:"workflowVersion"`
	WorkflowExecutionID string          `json:"workflowExecutionId,omitempty"`
	Task                string          `json:"task"`
	WorkingDirectory    string          `json:"workingDirectory"`
	Context             json.RawMessage `json:"context"`
}

type CreateJobInput added in v0.4.0

type CreateJobInput struct {
	ID                 uuid.UUID
	TurnID             uuid.UUID
	AgentRunID         *uuid.UUID
	WorkerGenerationID string
	ToolCallID         string
	PID                int64
	Purpose            string
	Command            string
	Directory          string
	StartedAt          time.Time
}

CreateJobInput records a supervised process before its output is observed.

type CreateModelCallInput added in v0.4.0

type CreateModelCallInput struct {
	ID                  uuid.UUID
	Round               int64
	RequestMessagesJSON string
	RequestToolsJSON    string
	StartedAt           time.Time
}

CreateModelCallInput describes one outbound provider round before bytes leave Peen.

type CreateModelRunInput added in v0.4.0

type CreateModelRunInput struct {
	ID                  uuid.UUID
	TurnID              uuid.UUID
	AgentRunID          *uuid.UUID
	Stage               models.ModelRunStage
	ModelReference      string
	ConnectionName      string
	RequestedModelID    string
	RequestSettingsJSON string
	StartedAt           time.Time
}

CreateModelRunInput describes one logical provider invocation before its first outbound round starts.

type CreateSessionNoticeInput added in v0.4.0

type CreateSessionNoticeInput struct {
	ID        uuid.UUID
	Type      string
	Source    string
	Summary   string
	DataJSON  string
	Delivery  models.NoticeDelivery
	CreatedAt time.Time
}

CreateSessionNoticeInput describes an external or worker report before it is delivered to a model.

type CreateWorkerGenerationInput added in v0.8.0

type CreateWorkerGenerationInput struct {
	ID                 uuid.UUID
	Kind               string
	AgentSpace         string
	AgentSpaceRevision int64
	State              string
	Workspace          string
	SocketPath         string

	// CredentialHash verifies the worker's launch credential. The raw
	// credential is never stored.
	CredentialHash string
}

CreateWorkerGenerationInput records one worker before it launches, so a controller that dies mid-launch still leaves a row an operator can reconcile.

type DeferredTurnAdmission added in v0.25.0

type DeferredTurnAdmission struct {
	Lease   Lease                   `json:"lease"`
	Events  []EventInput            `json:"events"`
	Created bool                    `json:"created"`
	Notices []*models.SessionNotice `json:"notices,omitempty"`
}

type DeliverExecutionMessagesInput added in v0.25.0

type DeliverExecutionMessagesInput struct {
	TurnLease  Lease         `json:"turnLease"`
	ModelLease ActivityLease `json:"modelLease"`
	RequestIDs []uuid.UUID   `json:"requestIds"`
}

type DirectoryState added in v0.24.0

type DirectoryState struct {
	Directory string `json:"directory"`
	Sequence  int64  `json:"sequence"`
}

DirectoryState identifies the last accepted root directory change. An empty directory means the session still uses its startup directory.

type EventInput

type EventInput struct {
	ID                 uuid.UUID `json:"id"`
	RequestID          uuid.UUID `json:"requestId"`
	WorkerGenerationID string    `json:"workerGenerationId"`
	EventType          string    `json:"eventType"`
	PayloadJSON        string    `json:"payloadJson"`
	ParentToolCallID   string    `json:"parentToolCallId"`
}

EventInput describes one exact internal or protocol event.

type EventPage added in v0.4.0

type EventPage struct {
	Items   []*models.Event
	Limit   int
	Offset  int
	HasMore bool
}

EventPage is one complete session-local protocol event page.

type ExecutionActivities added in v0.25.0

type ExecutionActivities interface {
	BeginExecutionActivity(
		context.Context, uuid.UUID, uuid.UUID, uuid.UUID, ScheduleActivityInput,
	) (*ActivityClaim, error)
	CompleteExecutionActivity(
		context.Context, uuid.UUID, ActivityLease, CompleteActivityInput,
	) (*models.ExecutionActivity, error)
	InterruptExecutionActivity(context.Context, uuid.UUID, ActivityLease) error
	ResolveExecutionActivity(
		context.Context, uuid.UUID, uuid.UUID, ResolveActivityInput,
	) (*models.ExecutionActivity, error)
	GetExecutionActivity(context.Context, uuid.UUID, uuid.UUID) (
		*models.ExecutionActivity, error)
	ListExecutionActivities(
		context.Context, uuid.UUID, uuid.UUID, ListEventsOptions,
	) (*ExecutionActivityPage, error)
}

type ExecutionActivityCompletion added in v0.25.0

type ExecutionActivityCompletion struct {
	Activity *models.ExecutionActivity `json:"activity"`
	Events   []EventInput              `json:"events"`
}

type ExecutionActivityPage added in v0.25.0

type ExecutionActivityPage struct {
	Items   []*models.ExecutionActivity `json:"items"`
	Limit   int                         `json:"limit"`
	Offset  int                         `json:"offset"`
	HasMore bool                        `json:"hasMore"`
}

type ExecutionAgentControls added in v0.25.0

type ExecutionAgentControls interface {
	ResumeExecutionFromActivity(context.Context, uuid.UUID, uuid.UUID,
		ResumeExecutionInput) ([]uuid.UUID, error)
	ResolveExecutionActivityFromActivity(context.Context, uuid.UUID, uuid.UUID,
		ResolveExecutionControlInput) (*models.ExecutionActivity, error)
}

type ExecutionChildProjection added in v0.25.0

type ExecutionChildProjection struct {
	ControlRevision int64                   `json:"controlRevision"`
	Messages        []AgentRunMessageInput  `json:"messages"`
	Events          []AgentRunEventInput    `json:"events"`
	Question        *ExecutionChildQuestion `json:"question,omitempty"`
}

type ExecutionChildQuestion added in v0.25.0

type ExecutionChildQuestion struct {
	EventID       uuid.UUID `json:"eventId"`
	Question      string    `json:"question"`
	ParentMessage string    `json:"parentMessage"`
}

type ExecutionCompletionSeal added in v0.25.0

type ExecutionCompletionSeal struct {
	ActivityID      uuid.UUID `json:"activityId"`
	InputHash       string    `json:"inputHash"`
	InboxSequence   int64     `json:"inboxSequence"`
	ControlRevision int64     `json:"controlRevision"`
}

type ExecutionCompletionStorage added in v0.25.0

type ExecutionCompletionStorage interface {
	ReserveExecutionCompletion(context.Context, uuid.UUID, ActivityLease) (
		*ExecutionCompletionSeal, error)
}

type ExecutionEventPage added in v0.25.0

type ExecutionEventPage struct {
	Items   []*models.ExecutionEvent `json:"items"`
	Limit   int                      `json:"limit"`
	Offset  int                      `json:"offset"`
	HasMore bool                     `json:"hasMore"`
}

type ExecutionEventType added in v0.25.0

type ExecutionEventType string
const (
	ExecutionEventTypeCreated        ExecutionEventType = "execution.created"
	ExecutionEventTypePaused         ExecutionEventType = "execution.paused"
	ExecutionEventTypeResumed        ExecutionEventType = "execution.resumed"
	ExecutionEventTypeStarted        ExecutionEventType = "execution.started"
	ExecutionEventTypeCheckpoint     ExecutionEventType = "execution.checkpoint"
	ExecutionEventTypeCompleted      ExecutionEventType = "execution.completed"
	ExecutionEventTypeFailed         ExecutionEventType = "execution.failed"
	ExecutionEventTypeCancelled      ExecutionEventType = "execution.cancelled"
	ExecutionEventTypeStepCancelled  ExecutionEventType = "activity.cancelled"
	ExecutionEventTypeStepScheduled  ExecutionEventType = "activity.scheduled"
	ExecutionEventTypeStepStarted    ExecutionEventType = "activity.started"
	ExecutionEventTypeStepCompleted  ExecutionEventType = "activity.completed"
	ExecutionEventTypeStepFailed     ExecutionEventType = "activity.failed"
	ExecutionEventTypeStepPaused     ExecutionEventType = "activity.paused"
	ExecutionEventTypeStepUncertain  ExecutionEventType = "activity.uncertain"
	ExecutionEventTypeStepResolved   ExecutionEventType = "activity.resolved"
	ExecutionEventTypeInboxQueued    ExecutionEventType = "inbox.queued"
	ExecutionEventTypeInboxDelivered ExecutionEventType = "inbox.delivered"
	ExecutionEventTypeInboxForwarded ExecutionEventType = "inbox.forwarded"
)

type ExecutionFinishChild added in v0.25.0

type ExecutionFinishChild struct {
	State                 models.AgentRunState `json:"state"`
	ResponseText          string               `json:"responseText"`
	ResponseThinking      string               `json:"responseThinking"`
	ResponseMessagesJSON  string               `json:"responseMessagesJson"`
	FinishReason          string               `json:"finishReason"`
	PromptTokenCount      int64                `json:"promptTokenCount"`
	CompletionTokenCount  int64                `json:"completionTokenCount"`
	FailureClassification string               `json:"failureClassification"`
	FailureDetail         string               `json:"failureDetail"`
}

type ExecutionFinishHolder added in v0.25.0

type ExecutionFinishHolder struct {
	LeaseID         uuid.UUID `json:"leaseId"`
	ControlRevision int64     `json:"controlRevision"`
}

type ExecutionInboxAcceptance added in v0.25.0

type ExecutionInboxAcceptance struct {
	Message *models.ExecutionInboxMessage `json:"message"`
	Events  []EventInput                  `json:"events"`
	// Resumed lists the paused executions the message resumed, so the caller
	// can start their workflows again.
	Resumed []uuid.UUID `json:"resumed,omitempty"`
}

type ExecutionInboxDelivery added in v0.25.0

type ExecutionInboxDelivery struct {
	Messages []MessageInput `json:"messages"`
	Events   []EventInput   `json:"events"`
}

type ExecutionInboxPage added in v0.25.0

type ExecutionInboxPage struct {
	Items   []*models.ExecutionInboxMessage `json:"items"`
	Limit   int                             `json:"limit"`
	Offset  int                             `json:"offset"`
	HasMore bool                            `json:"hasMore"`
}

type ExecutionInboxPart added in v0.25.0

type ExecutionInboxPart struct {
	Content     string `json:"content"`
	SkillName   string `json:"skillName"`
	SkillIsNote bool   `json:"skillIsNote"`
}

type ExecutionPage added in v0.25.0

type ExecutionPage struct {
	Items   []*models.Execution `json:"items"`
	Limit   int                 `json:"limit"`
	Offset  int                 `json:"offset"`
	HasMore bool                `json:"hasMore"`
}

type ExecutionRecords added in v0.25.0

type ExecutionRecords interface {
	CreateExecution(context.Context, uuid.UUID, CreateExecutionInput) (
		*models.Execution, error)
	GetExecution(context.Context, uuid.UUID, uuid.UUID) (
		*models.Execution, error)
	SearchExecutions(context.Context, uuid.UUID, SearchExecutionsOptions) (
		*ExecutionPage, error)
	PauseExecution(context.Context, uuid.UUID, uuid.UUID, string) (
		[]uuid.UUID, error)
	ResumeExecution(context.Context, uuid.UUID, uuid.UUID) ([]uuid.UUID, error)
	ListExecutionEvents(
		context.Context, uuid.UUID, uuid.UUID, ListEventsOptions,
	) (*ExecutionEventPage, error)
}

type ExecutionRootProjection added in v0.25.0

type ExecutionRootProjection struct {
	Holder   ExecutionFinishHolder `json:"holder"`
	Messages []MessageInput        `json:"messages"`
	Events   []EventInput          `json:"events"`
}

type ExecutionStorage added in v0.25.0

ExecutionStorage is the workflow checkpoint and control boundary. Workers reach the same operations over their authenticated session socket.

type ExecutionTurnLeases added in v0.25.0

type ExecutionTurnLeases interface {
	AcquireDeferredExecutionTurn(context.Context, uuid.UUID, uuid.UUID,
		StartTurnInput) (*DeferredTurnAdmission, error)
	GetExecutionRootTurn(context.Context, uuid.UUID, uuid.UUID) (
		*models.Turn, error)
	RestoreExecutionTurn(context.Context, uuid.UUID, uuid.UUID,
		RestoreExecutionTurnInput) (Lease, error)
	GetExecutionTurnLease(context.Context, uuid.UUID, uuid.UUID) (
		*models.ExecutionTurnLease, error)
}

type FeedItem added in v0.26.0

type FeedItem struct {
	SessionID uuid.UUID
	Sequence  int64
	ID        uuid.UUID
	Kind      FeedKind
	EventType string

	// RequestID is set for an event item and Nil otherwise.
	RequestID uuid.UUID
	// TurnID is set for an event item.
	TurnID uuid.UUID

	// AgentRunID, ParentTurnID, and ParentAgentRunID are set for an agent
	// run event item. ParentAgentRunID is nil for a top-level child.
	AgentRunID       uuid.UUID
	ParentTurnID     uuid.UUID
	ParentAgentRunID *uuid.UUID

	PayloadJSON string

	// Notice is set for a notice item.
	Notice *models.SessionNotice

	CreatedAt time.Time
}

FeedItem is one row of a session's contiguous feed sequence, merged across events, agent_run_events, and session_notices.

type FeedKind added in v0.26.0

type FeedKind string

FeedKind identifies which durable table a FeedItem came from.

const (
	FeedKindEvent         FeedKind = "event"
	FeedKindAgentRunEvent FeedKind = "agentRunEvent"
	FeedKindNotice        FeedKind = "notice"
)

type FeedPage added in v0.26.0

type FeedPage struct {
	Items      []FeedItem
	NextCursor int64
	HasMore    bool
	Head       int64
}

FeedPage is one page of a session's merged feed, oldest first.

type FeedSignalFunc added in v0.26.0

type FeedSignalFunc func(sessionID uuid.UUID, first int64)

FeedSignalFunc notifies that sessionID's feed gained rows starting at first. Store calls it at most once per (session, commit), strictly after the writing transaction returned nil, never on rollback.

type FinalizeAgentRunInput added in v0.4.0

type FinalizeAgentRunInput struct {
	State                 models.AgentRunState
	ResponseText          string
	ResponseThinking      string
	ResponseMessagesJSON  string
	FinishReason          string
	PromptTokenCount      int64
	CompletionTokenCount  int64
	FailureClassification string
	FailureDetail         string
}

FinalizeAgentRunInput describes the durable terminal outcome of a child.

type FinalizeJobInput added in v0.4.0

type FinalizeJobInput struct {
	State         models.JobState
	ExitCode      int64
	FailureDetail string
}

FinalizeJobInput stores a job's terminal outcome exactly once.

type FinalizeModelCallInput added in v0.4.0

type FinalizeModelCallInput struct {
	State                   models.ModelCallState
	ResponseMessageJSON     string
	ResponseUsageJSON       string
	RetryAttemptsJSON       string
	RetryAttemptCount       int64
	PromptTokens            int64
	CompletionTokens        int64
	TotalTokens             int64
	ReasoningTokens         int64
	CacheReadTokens         int64
	CacheWriteTokens        int64
	CacheWriteLongTTLTokens int64
	WastedPromptTokens      int64
	WastedCompletionTokens  int64
	WastedTotalTokens       int64
	TotalAttempts           int64
	ResponseModelID         string
	FinishReason            string
	ResponseCostAmount      string
	RetryCostAmount         string
	BilledCostAmount        string
	CostKnown               bool
	FailureClassification   string
	FailureDetail           string
}

FinalizeModelCallInput records the complete result of one provider round.

type FinalizeModelRunInput added in v0.4.0

type FinalizeModelRunInput struct {
	State                  models.ModelRunState
	ResponseModelID        string
	ResponseText           string
	ResponseThinking       string
	ResponseMessagesJSON   string
	ResponseInjectionsJSON string
	ResponseUsageJSON      string
	ResponseCostAmount     string
	RetryCostAmount        string
	BilledCostAmount       string
	CostKnown              bool
	FinishReason           string
	FailureClassification  string
	FailureDetail          string
}

FinalizeModelRunInput stores every non-secret result of one logical model invocation, including aggregate usage across its provider rounds.

type FinalizeTurnInput

type FinalizeTurnInput struct {
	State                 models.TurnState `json:"state"`
	FailureClassification string           `json:"failureClassification"`
	// FailureDetail is the error a turn that did not complete ended with, as
	// its notice carries it.
	FailureDetail       string         `json:"failureDetail,omitempty"`
	ContextSnapshotHash *string        `json:"contextSnapshotHash"`
	PromptSnapshotHash  *string        `json:"promptSnapshotHash"`
	Messages            []MessageInput `json:"messages"`
	Events              []EventInput   `json:"events"`
}

FinalizeTurnInput describes terminal turn state and durable references.

type FinishExecutionInput added in v0.25.0

type FinishExecutionInput struct {
	State            models.ExecutionState  `json:"state"`
	WorkingDirectory string                 `json:"workingDirectory,omitempty"`
	FailureDetail    string                 `json:"failureDetail,omitempty"`
	PendingOutput    json.RawMessage        `json:"pendingOutput,omitempty"`
	RootHolder       *ExecutionFinishHolder `json:"rootHolder,omitempty"`
	Turn             *FinalizeTurnInput     `json:"turn,omitempty"`
	Child            *ExecutionFinishChild  `json:"child,omitempty"`
	ChildReport      string                 `json:"childReport,omitempty"`
}

type History

type History struct {
	Compaction *models.Compaction
	Messages   []*models.Message
}

History is the active compaction followed by its uncovered completed tail.

type IdleCallbackFunc added in v0.26.2

type IdleCallbackFunc func(sessionID uuid.UUID, state models.TurnState)

IdleCallbackFunc notifies that sessionID's turn ended in state and the session now holds no active turn in this store. Store calls it once a normal turn end has released the lease, never while holding activeMu, so the callback can read IsActive and start a new turn without deadlocking the store that just finished writing.

type IdleNotifier added in v0.26.2

type IdleNotifier interface {
	SetIdleCallback(IdleCallbackFunc)
}

IdleNotifier is the optional seam a runtime uses to re-check a session's pending notices once its turn ends on its own. A notice published while that turn was still running degrades to a queued delivery because the session reports busy; nothing else revisits it once the turn is gone.

Not every Storage a caller supplies needs one: a worker's protocol store mirrors a lease for cancellation only, and the controller's store it forwards to is the one that owns this decision.

type JobOutputPage added in v0.4.0

type JobOutputPage struct {
	Job        *models.Job
	Items      []*models.JobOutputLine
	NextCursor int64
	HasMore    bool
}

JobOutputPage is one complete ordered output replay page.

type JobPage added in v0.4.0

type JobPage struct {
	Items   []*models.Job
	Limit   int
	Offset  int
	HasMore bool
}

JobPage is one complete process-job page.

type JobSignalRequestPage added in v0.4.0

type JobSignalRequestPage struct {
	Job     *models.Job
	Items   []*models.JobSignalRequest
	Limit   int
	Offset  int
	HasMore bool
}

JobSignalRequestPage is one complete signal-request history page.

type Lease

type Lease struct {
	ID        uuid.UUID `json:"id"`
	SessionID uuid.UUID `json:"sessionId"`
	TurnID    uuid.UUID `json:"turnId"`
}

Lease identifies one holder even when the original turn ID is reused.

type ListAgentRunCompactionsOptions added in v0.11.0

type ListAgentRunCompactionsOptions struct {
	Limit  int
	Offset int
}

ListAgentRunCompactionsOptions bounds one child compaction page.

type ListAgentRunEventsOptions added in v0.4.0

type ListAgentRunEventsOptions struct {
	Cursor int64
	Limit  int
}

ListAgentRunEventsOptions controls one replay window. Cursor is the next sequence number the caller has not seen yet, beginning at zero.

type ListAgentRunMessagesOptions added in v0.11.0

type ListAgentRunMessagesOptions struct {
	Limit  int
	Offset int
}

ListAgentRunMessagesOptions bounds one child transcript page.

type ListAgentRunsOptions added in v0.4.0

type ListAgentRunsOptions struct {
	Limit  int
	Offset int
	State  *models.AgentRunState

	// IsWaiting keeps only running runs with a question nobody answered yet.
	IsWaiting bool
	// ParentAgentRunID keeps only the direct children of one run.
	ParentAgentRunID *uuid.UUID
	// IsTopLevel keeps only the children the root conversation launched.
	IsTopLevel bool
}

ListAgentRunsOptions controls a bounded child-run page.

type ListAgentSpaceDecisionsOptions added in v0.19.0

type ListAgentSpaceDecisionsOptions struct {
	Limit  int
	Offset int
}

ListAgentSpaceDecisionsOptions controls a bounded page of one session's agent space decisions.

type ListCompactionsOptions added in v0.4.0

type ListCompactionsOptions struct {
	Limit  int
	Offset int
}

ListCompactionsOptions controls a bounded page of compaction records.

type ListEventsOptions added in v0.4.0

type ListEventsOptions struct {
	Limit      int
	Offset     int
	Order      PageOrder
	TurnID     uuid.UUID `json:"turnId,omitempty"`
	EventTypes []string  `json:"eventTypes,omitempty"`
}

ListEventsOptions controls a bounded page of durable protocol events.

type ListExecutionInboxOptions added in v0.25.0

type ListExecutionInboxOptions struct {
	State  models.InboxMessageState `json:"state,omitempty"`
	Limit  int                      `json:"limit"`
	Offset int                      `json:"offset"`
}

type ListJobOutputOptions added in v0.4.0

type ListJobOutputOptions struct {
	Cursor int64
	Limit  int
	Stream *models.JobOutputStream
}

ListJobOutputOptions controls one ordered process-output replay window.

type ListJobSignalRequestsOptions added in v0.4.0

type ListJobSignalRequestsOptions struct {
	Limit  int
	Offset int
}

ListJobSignalRequestsOptions controls a bounded signal-request history page.

type ListJobsOptions added in v0.4.0

type ListJobsOptions struct {
	Limit  int
	Offset int
	State  *models.JobState
}

ListJobsOptions controls a bounded session-local process-job page.

type ListMessagesOptions

type ListMessagesOptions struct {
	Limit  int
	Offset int
	Order  PageOrder
}

ListMessagesOptions controls a bounded session-local message page.

type ListModelCallsOptions added in v0.4.0

type ListModelCallsOptions struct {
	Limit  int
	Offset int
}

ListModelCallsOptions controls one ordered provider-round page.

type ListModelRunsOptions added in v0.4.0

type ListModelRunsOptions struct {
	Limit  int
	Offset int
	Stage  *models.ModelRunStage
	State  *models.ModelRunState
}

ListModelRunsOptions controls a bounded session-local model-run page.

type ListSessionNoticesOptions added in v0.4.0

type ListSessionNoticesOptions struct {
	ValidateWakeSource bool `json:"validateWakeSource,omitempty"`
	Limit              int
	Offset             int
	ID                 *uuid.UUID         `json:"id,omitempty"`
	State              models.NoticeState `json:"state,omitempty"`
}

ListSessionNoticesOptions controls a bounded page of notice history.

type ListSessionsOptions added in v0.8.0

type ListSessionsOptions struct {
	Limit  int
	Offset int
}

ListSessionsOptions controls a bounded page of the control surface's durable sessions.

type ListTurnsOptions added in v0.4.0

type ListTurnsOptions struct {
	Limit  int
	Offset int
}

ListTurnsOptions controls a bounded page of durable session turns.

type ListWorkerGenerationsOptions added in v0.8.0

type ListWorkerGenerationsOptions struct {
	Limit  int
	Offset int
}

ListWorkerGenerationsOptions controls a bounded page of one session's worker generations.

type MessageInput

type MessageInput struct {
	ID        uuid.UUID          `json:"id"`
	Workspace string             `json:"workspace"`
	Role      models.MessageRole `json:"role"`
	Content   string             `json:"content"`
	ModelID   string             `json:"modelId"`
	Thinking  string             `json:"thinking"`
	// ProviderReasoningJSON is the provider's reasoning envelope, kept so a
	// later turn can replay it to the same model.
	ProviderReasoningJSON string              `json:"providerReasoningJson"`
	ToolCallsJSON         string              `json:"toolCallsJson"`
	ToolCallID            string              `json:"toolCallId"`
	IsError               bool                `json:"isError"`
	Incomplete            bool                `json:"incomplete"`
	Injected              bool                `json:"injected"`
	InjectedKind          models.InjectedKind `json:"injectedKind"`
}

MessageInput describes a durable transcript record.

type MessagePage

type MessagePage struct {
	Items   []*models.Message
	Limit   int
	Offset  int
	HasMore bool
}

MessagePage is one complete limit-offset transcript page.

type ModelCallPage added in v0.4.0

type ModelCallPage struct {
	Run     *models.ModelRun
	Items   []*models.ModelCall
	Limit   int
	Offset  int
	HasMore bool
}

ModelCallPage is one complete provider-round page for a model run.

type ModelRunPage added in v0.4.0

type ModelRunPage struct {
	Items   []*models.ModelRun
	Limit   int
	Offset  int
	HasMore bool
}

ModelRunPage is one complete model-run page.

type NoticePage added in v0.5.0

type NoticePage struct {
	Items   []*models.SessionNotice
	Limit   int
	Offset  int
	HasMore bool
}

NoticePage is one complete session-local notice page.

type OpenSessionOptions

type OpenSessionOptions struct {
	RootAgent string
	ModelID   string

	// AgentSpace is the agent space a newly created session runs in. Opening
	// an existing session never changes its agent space, so this only applies
	// to creation.
	AgentSpace string
}

OpenSessionOptions supplies immutable session attribution on creation.

type OpenSessionResult

type OpenSessionResult struct {
	Session *models.Session
	Created bool
}

OpenSessionResult is a resolved session and whether this call created it.

type Options

type Options struct {
	Clock func() time.Time
	NewID func() uuid.UUID

	// MaxStoredMessageBytes bounds one message row of any role. An assistant
	// or tool message has no caller-facing size limit, so without this a
	// single tool result could grow the transcript without bound. Zero takes
	// the package default.
	MaxStoredMessageBytes int
}

Options supplies deterministic seams for the transport-neutral store.

type PageOrder

type PageOrder string

PageOrder controls transcript pagination direction.

const (
	PageOrderAscending  PageOrder = "asc"
	PageOrderDescending PageOrder = "desc"
)

type RecordJobSignalInput added in v0.4.0

type RecordJobSignalInput struct {
	ID          uuid.UUID
	Signal      models.JobSignal
	Accepted    bool
	RequestedAt time.Time
}

RecordJobSignalInput records one accepted or no-op request to stop a job.

type RecordModelCallRetriesInput added in v0.4.0

type RecordModelCallRetriesInput struct {
	RetryAttemptsJSON string
	RetryAttemptCount int64
}

RecordModelCallRetriesInput persists every retry that Elelem reports while a provider round remains active.

type ResolveActivityInput added in v0.25.0

type ResolveActivityInput struct {
	Attempt    int64              `json:"attempt"`
	Resolution ActivityResolution `json:"resolution"`
	Evidence   string             `json:"evidence"`
	Output     json.RawMessage    `json:"output,omitempty"`
	Context    json.RawMessage    `json:"context,omitempty"`
}

type ResolveExecutionControlInput added in v0.25.0

type ResolveExecutionControlInput struct {
	SourceLease     ActivityLease `json:"sourceLease"`
	ControlRevision int64         `json:"controlRevision"`
	ResolveActivityInput
}

type RestoreExecutionTurnInput added in v0.25.0

type RestoreExecutionTurnInput struct {
	ControlRevision    int64     `json:"controlRevision"`
	OwnerGenerationID  uuid.UUID `json:"ownerGenerationId"`
	WorkerGenerationID uuid.UUID `json:"workerGenerationId,omitempty"`
	PreviousLeaseID    uuid.UUID `json:"previousLeaseId,omitempty"`
}

type ResumeExecutionInput added in v0.25.0

type ResumeExecutionInput struct {
	SourceLease          ActivityLease `json:"sourceLease"`
	ControlRevision      int64         `json:"controlRevision"`
	DeferredRequestID    *uuid.UUID    `json:"deferredRequestId,omitempty"`
	DeferredStopRevision *int64        `json:"deferredStopRevision,omitempty"`
}

type ScheduleActivityInput added in v0.25.0

type ScheduleActivityInput struct {
	StepID       string                      `json:"stepId"`
	Kind         models.ActivityKind         `json:"kind"`
	ReplayPolicy models.ActivityReplayPolicy `json:"replayPolicy"`
	Name         string                      `json:"name"`
	Input        json.RawMessage             `json:"input"`
}

type SearchExecutionsOptions added in v0.25.0

type SearchExecutionsOptions struct {
	ID       uuid.UUID             `json:"id,omitempty"`
	ParentID uuid.UUID             `json:"parentId,omitempty"`
	RootID   uuid.UUID             `json:"rootId,omitempty"`
	State    models.ExecutionState `json:"state,omitempty"`
	Text     string                `json:"text,omitempty"`
	FromTime *time.Time            `json:"fromTime,omitempty"`
	ToTime   *time.Time            `json:"toTime,omitempty"`
	Limit    int                   `json:"limit"`
	Offset   int                   `json:"offset"`
}

type StartAgentRunInput added in v0.4.0

type StartAgentRunInput struct {
	ID                 uuid.UUID
	ParentTurnID       uuid.UUID
	WorkerGenerationID string
	ParentAgentRunID   *uuid.UUID
	ParentToolCallID   string
	RequestID          uuid.UUID
	Name               string
	Definition         models.AgentRunDefinition
	Depth              int64
	Workspace          string
	ModelReference     string
	ModelID            string
	Task               string
	Instructions       string
	AllowedToolsJSON   string
	SystemPrompt       string
	StartedAt          time.Time
}

StartAgentRunInput describes the immutable child-agent launch record.

type StartTurnInput

type StartTurnInput struct {
	RequestID            uuid.UUID
	Workspace            string
	Messages             []MessageInput
	Events               []EventInput
	NoticeIDs            []uuid.UUID `json:"noticeIds,omitempty"`
	ExpectedStopRevision *int64      `json:"expectedStopRevision,omitempty"`
	// WakeNoticeID binds automatic admission to its retained opening notice.
	WakeNoticeID       *uuid.UUID `json:"wakeNoticeId,omitempty"`
	WorkerGenerationID string     `json:"workerGenerationId,omitempty"`
}

StartTurnInput describes the durable beginning of an agent turn.

type Storage added in v0.8.0

type Storage interface {
	// contains filtered or unexported methods
}

Storage is the durable surface one session's runtime needs.

It exists because the same runtime runs in two places. Inside the control plane it is backed by *Store, which owns SQLite. Inside a worker it is backed by the private worker protocol, which forwards each operation to the controller. A worker therefore gets the same transcript semantics without ever opening the controller's database.

The interface is deliberately the whole set rather than a convenient subset. A worker-side implementation must answer every method, and refusing one it has no business performing is a decision that shows up in the code rather than a method that silently does not exist.

type Store

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

Store persists sessions and protects each active session turn in-process.

func NewStore

func NewStore(handle *db.Handle, options Options) (*Store, error)

NewStore builds a store over an already-open migrated database handle.

func (*Store) AcceptChildExecutionMessage added in v0.25.0

func (s *Store) AcceptChildExecutionMessage(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
	input AcceptExecutionMessageInput,
) (*ExecutionInboxAcceptance, error)

func (*Store) AcceptExecutionMessage added in v0.25.0

func (s *Store) AcceptExecutionMessage(
	ctx context.Context,
	executionID uuid.UUID,
	lease Lease,
	input AcceptExecutionMessageInput,
) (*ExecutionInboxAcceptance, error)

AcceptExecutionMessage retains the accepted text and skill content by ID.

func (*Store) AcquireDeferredExecutionTurn added in v0.25.0

func (s *Store) AcquireDeferredExecutionTurn(
	ctx context.Context,
	sessionID, inboxID uuid.UUID,
	input StartTurnInput,
) (*DeferredTurnAdmission, error)

AcquireDeferredExecutionTurn admits accepted input once across restarts. Retries retain the turn and transcript; cancelled work remains stopped.

func (*Store) AcquireTurn

func (s *Store) AcquireTurn(
	ctx context.Context,
	sessionID uuid.UUID,
	input StartTurnInput,
) (Lease, error)

AcquireTurn starts one durable turn and records its initial transcript data.

func (*Store) AgentRunHistory added in v0.11.0

func (s *Store) AgentRunHistory(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
) (*AgentRunHistoryResult, error)

AgentRunHistory returns the child's current summary and the raw tail that follows it, which is what rebuilds a child conversation after a restart.

func (*Store) AppendAgentRunEvent added in v0.4.0

func (s *Store) AppendAgentRunEvent(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	input AgentRunEventInput,
) (*models.AgentRunEvent, error)

AppendAgentRunEvent records a child event before it reaches a live client.

Once the run has ended it accepts only a terminal event, and refuses any other with ErrAgentRunFinished joined with commerr.ErrConflict. A stream still delivering deltas after a cancellation would otherwise land after the terminal event, which restore requires to close the run's events.

func (*Store) AppendAgentRunMessages added in v0.11.0

func (s *Store) AppendAgentRunMessages(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	inputs []AgentRunMessageInput,
) ([]*models.AgentRunMessage, error)

AppendAgentRunMessages stores prompt-visible child records in one transaction, so a child loop never continues past a message the durable transcript does not hold.

Sequences are allocated per agent run, independent of the session transcript. A child agent is a separate model context, so its messages never enter the session transcript and a parent-session compaction can never absorb them.

func (*Store) AppendCheckpoint

func (s *Store) AppendCheckpoint(
	ctx context.Context,
	lease Lease,
	messages []MessageInput,
	events []EventInput,
) error

AppendCheckpoint records visible messages and events without ending a turn.

func (*Store) AppendJobOutput added in v0.4.0

func (s *Store) AppendJobOutput(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	inputs []AppendJobOutputInput,
) ([]*models.JobOutputLine, error)

AppendJobOutput stores process lines in order, in one transaction, before any live reader can see them. stdout and stderr share the same sequence so replay preserves observed ordering across both streams. Either every line is stored or none is.

func (*Store) BeginExecutionActivity added in v0.25.0

func (s *Store) BeginExecutionActivity(
	ctx context.Context,
	sessionID, executionID, generationID uuid.UUID,
	input ScheduleActivityInput,
) (*ActivityClaim, error)

BeginExecutionActivity saves the input before external work begins. Completed results are reused; a replaced writer cannot overwrite a new claim.

func (*Store) Cancel

func (s *Store) Cancel(ctx context.Context, sessionID uuid.UUID) (bool, error)

Cancel records a stop revision even when the session has no active turn. Its result reports whether a turn or execution was stopped.

func (*Store) ClaimAgentRun added in v0.24.0

func (s *Store) ClaimAgentRun(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	input ClaimAgentRunInput,
) (*models.AgentRun, error)

ClaimAgentRun resumes an interrupted child or transfers a stale worker's running child. A current owner, cancelled child or terminal child cannot be claimed. The conditional update prevents two owners claiming one run.

func (*Store) CompleteExecutionActivity added in v0.25.0

func (s *Store) CompleteExecutionActivity(
	ctx context.Context,
	sessionID uuid.UUID,
	lease ActivityLease,
	input CompleteActivityInput,
) (*models.ExecutionActivity, error)

CompleteExecutionActivity commits the result before the workflow ack. An identical repeat is harmless. A stale generation or attempt is refused.

func (*Store) CompleteExecutionActivityReceipt added in v0.25.0

func (s *Store) CompleteExecutionActivityReceipt(
	ctx context.Context,
	sessionID uuid.UUID,
	lease ActivityLease,
	input CompleteActivityInput,
) (*ExecutionActivityCompletion, error)

CompleteExecutionActivityReceipt returns only events committed by this call. Repeated completions return the saved activity without new events.

func (*Store) CompletedHistory

func (s *Store) CompletedHistory(
	ctx context.Context,
	sessionID uuid.UUID,
) (*History, error)

CompletedHistory returns the current summary and the raw completed tail.

func (*Store) CreateAgentRun added in v0.4.0

func (s *Store) CreateAgentRun(
	ctx context.Context,
	sessionID uuid.UUID,
	input StartAgentRunInput,
) (*models.AgentRun, error)

CreateAgentRun records a child before any provider work or visible stream event can begin.

func (*Store) CreateAgentRunCompaction added in v0.11.0

func (s *Store) CreateAgentRunCompaction(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	input AgentRunCompactionInput,
) (*models.AgentRunCompaction, error)

CreateAgentRunCompaction stores one immutable child summary and assigns the direct messages it covered.

Only rows this compaction covered itself are assigned, so an earlier child compaction keeps the direct membership it already recorded.

func (*Store) CreateCompaction

func (s *Store) CreateCompaction(
	ctx context.Context,
	sessionID uuid.UUID,
	input CompactionInput,
) (*models.Compaction, error)

CreateCompaction stores an immutable completed-history replacement summary.

func (*Store) CreateExecution added in v0.25.0

func (s *Store) CreateExecution(
	ctx context.Context,
	sessionID uuid.UUID,
	input CreateExecutionInput,
) (*models.Execution, error)

CreateExecution records an immutable identity before scheduling a workflow. Duplicate creation returns the saved execution and never wakes paused work.

func (*Store) CreateJob added in v0.4.0

func (s *Store) CreateJob(
	ctx context.Context,
	sessionID uuid.UUID,
	input CreateJobInput,
) (*models.Job, error)

CreateJob records a supervised process before its output reaches memory or any connected client.

func (*Store) CreateModelCall added in v0.4.0

func (s *Store) CreateModelCall(
	ctx context.Context,
	sessionID uuid.UUID,
	modelRunID uuid.UUID,
	input CreateModelCallInput,
) (*models.ModelCall, error)

CreateModelCall writes one exact outbound provider request before Elelem gives its driver permission to execute it.

func (*Store) CreateModelRun added in v0.4.0

func (s *Store) CreateModelRun(
	ctx context.Context,
	sessionID uuid.UUID,
	input CreateModelRunInput,
) (*models.ModelRun, error)

CreateModelRun records a logical model invocation before any provider work begins. No live event is permitted to outrun this row.

func (*Store) CreateOrResume

func (s *Store) CreateOrResume(
	ctx context.Context,
	requestedSessionID *uuid.UUID,
	options OpenSessionOptions,
) (*OpenSessionResult, error)

CreateOrResume creates a session or resumes its requested durable ID.

func (*Store) CreateSessionNotice added in v0.4.0

func (s *Store) CreateSessionNotice(
	ctx context.Context,
	sessionID uuid.UUID,
	input CreateSessionNoticeInput,
) (*models.SessionNotice, error)

CreateSessionNotice writes a notice before it reaches an in-process bus or a model. It is the durable source of the session's outside event history.

func (*Store) CreateWorkerGeneration added in v0.8.0

func (s *Store) CreateWorkerGeneration(
	ctx context.Context,
	sessionID uuid.UUID,
	input CreateWorkerGenerationInput,
) (*models.WorkerGeneration, error)

CreateWorkerGeneration stores a new generation for one existing session.

func (*Store) CurrentWorkerGeneration added in v0.8.0

func (s *Store) CurrentWorkerGeneration(
	ctx context.Context,
	sessionID uuid.UUID,
) (*models.WorkerGeneration, error)

CurrentWorkerGeneration returns the session's newest generation.

func (*Store) DeferExecutionMessage added in v0.25.0

func (s *Store) DeferExecutionMessage(
	ctx context.Context,
	executionID uuid.UUID,
	lease Lease,
	input AcceptExecutionMessageInput,
) (*ExecutionInboxAcceptance, error)

DeferExecutionMessage retains late input for a separate root execution. It requires a reserved completion and never delivers into the old model loop.

func (*Store) DeliverChildExecutionMessages added in v0.25.0

func (s *Store) DeliverChildExecutionMessages(
	ctx context.Context,
	sessionID uuid.UUID,
	lease ActivityLease,
	requestIDs []uuid.UUID,
) (*ExecutionInboxDelivery, error)

func (*Store) DeliverExecutionMessages added in v0.25.0

func (s *Store) DeliverExecutionMessages(
	ctx context.Context,
	sessionID uuid.UUID,
	input DeliverExecutionMessagesInput,
) (*ExecutionInboxDelivery, error)

DeliverExecutionMessages commits the accepted IDs and transcript together.

func (*Store) DrainSessionNotices added in v0.4.0

func (s *Store) DrainSessionNotices(
	ctx context.Context,
	sessionID uuid.UUID,
) ([]*models.SessionNotice, error)

DrainSessionNotices marks every pending notice delivered and returns the exact immutable records for the next model context.

func (*Store) EndRunningTurn added in v0.30.0

func (s *Store) EndRunningTurn(
	ctx context.Context,
	sessionID, turnID uuid.UUID,
	end TurnEnd,
) (bool, error)

EndRunningTurn ends a turn that is still running without holding its lease, and stores its terminal frame and notice in the same feed transaction, so a client reading the feed sees the turn end and the next turn learns why. It reports false and changes nothing when the turn has already ended.

func (*Store) FeedHead added in v0.26.0

func (s *Store) FeedHead(
	ctx context.Context,
	sessionID uuid.UUID,
) (int64, error)

FeedHead returns the current head of a session's feed sequence.

func (*Store) FinalizeAgentRun added in v0.4.0

func (s *Store) FinalizeAgentRun(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	input FinalizeAgentRunInput,
) (*models.AgentRun, error)

FinalizeAgentRun writes the terminal response or failure exactly once.

func (*Store) FinalizeJob added in v0.4.0

func (s *Store) FinalizeJob(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	input FinalizeJobInput,
) (*models.Job, error)

FinalizeJob records a terminal process result exactly once.

func (*Store) FinalizeModelCall added in v0.4.0

func (s *Store) FinalizeModelCall(
	ctx context.Context,
	sessionID uuid.UUID,
	modelRunID uuid.UUID,
	modelCallID uuid.UUID,
	input FinalizeModelCallInput,
) (*models.ModelCall, error)

FinalizeModelCall writes one provider round's output and accounting exactly once. The request snapshot is immutable from CreateModelCall.

func (*Store) FinalizeModelRun added in v0.4.0

func (s *Store) FinalizeModelRun(
	ctx context.Context,
	sessionID uuid.UUID,
	modelRunID uuid.UUID,
	input FinalizeModelRunInput,
) (*models.ModelRun, error)

FinalizeModelRun writes the logical invocation outcome after every round has either finished or been marked terminal.

func (*Store) FinalizeTurn

func (s *Store) FinalizeTurn(
	ctx context.Context,
	lease Lease,
	input FinalizeTurnInput,
) error

FinalizeTurn atomically writes terminal transcript data and state. Once the write commits and the lease is released, it notifies the installed idle callback with the turn's terminal state, so a notice that missed every tool boundary in this turn can still be re-checked.

func (*Store) Get

func (s *Store) Get(
	ctx context.Context,
	sessionID uuid.UUID,
) (*models.Session, error)

Get returns durable metadata for one existing session.

func (*Store) GetAgentRun added in v0.4.0

func (s *Store) GetAgentRun(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
) (*models.AgentRun, error)

GetAgentRun returns one session-scoped durable child run.

func (*Store) GetAgentRunCompaction added in v0.11.0

func (s *Store) GetAgentRunCompaction(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	compactionID uuid.UUID,
) (*models.AgentRunCompaction, error)

GetAgentRunCompaction returns one immutable child compaction owned by both the session and the agent run.

func (*Store) GetCompaction added in v0.4.0

func (s *Store) GetCompaction(
	ctx context.Context,
	sessionID uuid.UUID,
	compactionID uuid.UUID,
) (*models.Compaction, error)

GetCompaction returns one immutable compaction record owned by a session.

func (*Store) GetContentBlobs added in v0.26.3

func (s *Store) GetContentBlobs(
	ctx context.Context,
	hashes []string,
) (map[string][]byte, error)

GetContentBlobs reads stored blobs by hash.

func (*Store) GetContextSnapshot added in v0.4.0

func (s *Store) GetContextSnapshot(
	ctx context.Context,
	sessionID uuid.UUID,
	hash string,
) (*models.ContextSnapshot, error)

GetContextSnapshot returns a snapshot only when this session references it.

func (*Store) GetDirectoryState added in v0.24.0

func (s *Store) GetDirectoryState(
	ctx context.Context,
	sessionID uuid.UUID,
) (*DirectoryState, error)

GetDirectoryState returns paired tool metadata without transferring history.

func (*Store) GetExecution added in v0.25.0

func (s *Store) GetExecution(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
) (*models.Execution, error)

func (*Store) GetExecutionActivity added in v0.25.0

func (s *Store) GetExecutionActivity(
	ctx context.Context,
	sessionID, activityID uuid.UUID,
) (*models.ExecutionActivity, error)

func (*Store) GetExecutionMessageByRequest added in v0.25.0

func (s *Store) GetExecutionMessageByRequest(
	ctx context.Context,
	sessionID, executionID, requestID uuid.UUID,
) (*models.ExecutionInboxMessage, error)

GetExecutionMessageByRequest reads frozen acceptance without waking work.

func (*Store) GetExecutionRootTurn added in v0.25.0

func (s *Store) GetExecutionRootTurn(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
) (*models.Turn, error)

GetExecutionRootTurn reads the original turn without claiming or resuming it.

func (*Store) GetExecutionTurnLease added in v0.25.0

func (s *Store) GetExecutionTurnLease(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
) (*models.ExecutionTurnLease, error)

func (*Store) GetJob added in v0.4.0

func (s *Store) GetJob(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
) (*models.Job, error)

GetJob reads a single durable process job scoped to its session.

func (*Store) GetModelRun added in v0.4.0

func (s *Store) GetModelRun(
	ctx context.Context,
	sessionID uuid.UUID,
	modelRunID uuid.UUID,
) (*models.ModelRun, error)

GetModelRun returns one session-scoped logical model invocation.

func (*Store) GetPromptSnapshot added in v0.4.0

func (s *Store) GetPromptSnapshot(
	ctx context.Context,
	sessionID uuid.UUID,
	hash string,
) (*models.PromptSnapshot, error)

GetPromptSnapshot returns a snapshot only when this session references it.

func (*Store) GetWorkerGeneration added in v0.8.0

func (s *Store) GetWorkerGeneration(
	ctx context.Context,
	sessionID uuid.UUID,
	generationID uuid.UUID,
) (*models.WorkerGeneration, error)

GetWorkerGeneration reads one generation by ID, scoped to its session so a caller cannot read another session's worker record by guessing an ID.

func (*Store) InterruptExecutionActivity added in v0.25.0

func (s *Store) InterruptExecutionActivity(
	ctx context.Context,
	sessionID uuid.UUID,
	lease ActivityLease,
) error

InterruptExecutionActivity retains uncertainty instead of replaying effects. Model and declared retryable activities can be claimed after interruption.

func (*Store) IsActive

func (s *Store) IsActive(sessionID uuid.UUID) bool

IsActive reports whether the process currently owns a running turn.

func (*Store) LatestAgentRunCompaction added in v0.11.0

func (s *Store) LatestAgentRunCompaction(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
) (*models.AgentRunCompaction, error)

LatestAgentRunCompaction returns the child's current chain head, never a superseded row.

func (*Store) LatestCompaction

func (s *Store) LatestCompaction(
	ctx context.Context,
	sessionID uuid.UUID,
) (*models.Compaction, error)

LatestCompaction returns the current chain head, not a superseded row.

func (*Store) ListAgentRunCompactions added in v0.11.0

func (s *Store) ListAgentRunCompactions(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	options ListAgentRunCompactionsOptions,
) (*AgentRunCompactionPage, error)

ListAgentRunCompactions returns one bounded page of a child's compaction lineage, newest first, scoped to the owning session.

func (*Store) ListAgentRunEvents added in v0.4.0

func (s *Store) ListAgentRunEvents(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	options ListAgentRunEventsOptions,
) (*AgentRunEventPage, error)

ListAgentRunEvents returns ordered durable replay data for one child run.

func (*Store) ListAgentRunMessages added in v0.11.0

func (s *Store) ListAgentRunMessages(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	options ListAgentRunMessagesOptions,
) (*AgentRunMessagePage, error)

ListAgentRunMessages returns one bounded page of a child's own transcript, oldest first, scoped to the owning session.

func (*Store) ListAgentRuns added in v0.4.0

func (s *Store) ListAgentRuns(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListAgentRunsOptions,
) (*AgentRunPage, error)

ListAgentRuns returns a stable newest-first session-scoped child-run page.

func (*Store) ListCompactions added in v0.4.0

func (s *Store) ListCompactions(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListCompactionsOptions,
) (*CompactionPage, error)

ListCompactions returns a stable newest-first page of durable summaries.

func (*Store) ListDeferredExecutionMessages added in v0.25.0

func (s *Store) ListDeferredExecutionMessages(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListEventsOptions,
) (*ExecutionInboxPage, error)

ListDeferredExecutionMessages reads pending input from completed roots. Reading never claims input, resumes a source or starts a turn.

func (*Store) ListEvents added in v0.4.0

func (s *Store) ListEvents(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListEventsOptions,
) (*EventPage, error)

ListEvents returns a stable bounded page of durable protocol events.

func (*Store) ListExecutionActivities added in v0.25.0

func (s *Store) ListExecutionActivities(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
	options ListEventsOptions,
) (*ExecutionActivityPage, error)

func (*Store) ListExecutionEvents added in v0.25.0

func (s *Store) ListExecutionEvents(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
	options ListEventsOptions,
) (*ExecutionEventPage, error)

func (*Store) ListExecutionMessages added in v0.25.0

func (s *Store) ListExecutionMessages(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
	options ListExecutionInboxOptions,
) (*ExecutionInboxPage, error)

ListExecutionMessages reads retained inbox state without resuming work.

func (*Store) ListFeed added in v0.26.0

func (s *Store) ListFeed(
	ctx context.Context,
	sessionID uuid.UUID,
	cursor int64,
	limit int,
) (*FeedPage, error)

ListFeed returns a page of a session's merged feed sequence, strictly after cursor, oldest first. A cursor at or past the head returns an empty page with NextCursor equal to cursor.

func (*Store) ListJobOutput added in v0.4.0

func (s *Store) ListJobOutput(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	options ListJobOutputOptions,
) (*JobOutputPage, error)

ListJobOutput replays the one persisted combined process stream.

func (*Store) ListJobSignalRequests added in v0.4.0

func (s *Store) ListJobSignalRequests(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	options ListJobSignalRequestsOptions,
) (*JobSignalRequestPage, error)

ListJobSignalRequests returns every durable request to signal one job.

func (*Store) ListJobs added in v0.4.0

func (s *Store) ListJobs(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListJobsOptions,
) (*JobPage, error)

ListJobs returns a stable newest-first session-local process-job page.

func (*Store) ListLiveWorkerGenerations added in v0.8.0

func (s *Store) ListLiveWorkerGenerations(
	ctx context.Context,
) ([]*models.WorkerGeneration, error)

ListLiveWorkerGenerations returns every generation a restarted controller may still own, newest first.

A controller reconnects to these before replacing anything, so a worker that outlived its controller is adopted rather than abandoned.

func (*Store) ListMessages

func (s *Store) ListMessages(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListMessagesOptions,
) (*MessagePage, error)

ListMessages returns a stable bounded page of one session's transcript.

func (*Store) ListModelCalls added in v0.4.0

func (s *Store) ListModelCalls(
	ctx context.Context,
	sessionID uuid.UUID,
	modelRunID uuid.UUID,
	options ListModelCallsOptions,
) (*ModelCallPage, error)

ListModelCalls returns the ordered provider rounds for one durable model invocation, including each exact request and retry trail.

func (*Store) ListModelRuns added in v0.4.0

func (s *Store) ListModelRuns(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListModelRunsOptions,
) (*ModelRunPage, error)

ListModelRuns returns a stable newest-first session-local model run page.

func (*Store) ListSessionAgentSpaceDecisions added in v0.19.0

func (s *Store) ListSessionAgentSpaceDecisions(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListAgentSpaceDecisionsOptions,
) (*AgentSpaceDecisionPage, error)

ListSessionAgentSpaceDecisions returns one session's agent space decision history, newest first.

func (*Store) ListSessionNotices added in v0.4.0

func (s *Store) ListSessionNotices(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListSessionNoticesOptions,
) (*NoticePage, error)

ListSessionNotices returns owned notice history in durable sequence order. ID and state filters narrow the history without marking notices delivered.

func (*Store) ListSessions added in v0.8.0

func (s *Store) ListSessions(
	ctx context.Context,
	options ListSessionsOptions,
) (*WorkspaceSessionPage, error)

ListSessions returns a stable bounded page of every durable session.

Unlike the other durable reads it takes no session ID, because it is how a client discovers which sessions exist. Ordering is newest-updated first so a client that pages sees the sessions it is most likely to want first.

func (*Store) ListTurns added in v0.4.0

func (s *Store) ListTurns(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListTurnsOptions,
) (*TurnPage, error)

ListTurns returns a stable newest-first page of durable session turns.

func (*Store) ListWorkerGenerations added in v0.8.0

func (s *Store) ListWorkerGenerations(
	ctx context.Context,
	sessionID uuid.UUID,
	options ListWorkerGenerationsOptions,
) (*WorkerGenerationPage, error)

ListWorkerGenerations returns a stable newest-first page of one session's worker generations.

func (*Store) OpenAgentRunQuestions added in v0.21.0

func (s *Store) OpenAgentRunQuestions(
	ctx context.Context,
	sessionID uuid.UUID,
) (map[uuid.UUID]string, error)

OpenAgentRunQuestions returns the question each running child of the session is waiting on, keyed by run. A run is waiting while its latest agent.run.question event has no later agent.run.answer.

func (*Store) OpenWorkspace added in v0.7.0

func (s *Store) OpenWorkspace(
	ctx context.Context,
	workspace string,
	options OpenSessionOptions,
) (*OpenSessionResult, error)

OpenWorkspace returns the one durable session belonging to workspace.

func (*Store) OpenWorkspaceIdentity added in v0.22.0

func (s *Store) OpenWorkspaceIdentity(
	ctx context.Context,
	canonicalWorkspace string,
	options OpenSessionOptions,
) (*OpenSessionResult, error)

OpenWorkspaceIdentity binds a caller-owned virtual identity without reading the host filesystem. Host callers must use OpenWorkspace for canonical paths.

func (*Store) PauseExecution added in v0.25.0

func (s *Store) PauseExecution(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
	reason string,
) ([]uuid.UUID, error)

PauseExecution commits the complete subtree's pause before work is stopped. Completed and failed descendants retain their terminal state.

func (*Store) PauseUnfinishedExecutions added in v0.30.0

func (s *Store) PauseUnfinishedExecutions(
	ctx context.Context,
	sessionID uuid.UUID,
) (int, error)

PauseUnfinishedExecutions pauses, with their subtrees, the executions a dead process left running or reconciling, so nothing continues until something resumes it explicitly. Queued executions have not started and stay queued. sessionID limits it to one session; uuid.Nil means every session. It returns how many executions it paused.

func (*Store) PrepareAgentRunRecovery added in v0.24.0

func (s *Store) PrepareAgentRunRecovery(
	ctx context.Context,
	sessionID, generationID uuid.UUID,
) (int, error)

PrepareAgentRunRecovery settles stale children of this session alone. Embedded runtimes use controller startup recovery and pass no generation.

func (*Store) PutContentBlobs added in v0.26.3

func (s *Store) PutContentBlobs(
	ctx context.Context,
	blobs []contentblob.Blob,
) error

PutContentBlobs stores the blobs of a compacted workflow payload.

func (*Store) ReconfigureAgentSpace added in v0.19.0

func (s *Store) ReconfigureAgentSpace(
	ctx context.Context,
	sessionID uuid.UUID,
	toAgentSpace string,
	reason string,
) (*models.SessionAgentSpaceDecision, error)

ReconfigureAgentSpace moves one idle session to a different agent space and records why.

It refuses a session with a turn in flight, because changing the environment under running work would leave that turn's tool calls attributed to an agent space that did not run them. The caller stops the session's worker afterwards so the next turn starts a new generation in the new agent space.

func (*Store) RecordJobSignal added in v0.4.0

func (s *Store) RecordJobSignal(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	input RecordJobSignalInput,
) (*models.JobSignalRequest, error)

RecordJobSignal stores every accepted and no-op signal request.

func (*Store) RecordModelCallRetries added in v0.4.0

func (s *Store) RecordModelCallRetries(
	ctx context.Context,
	sessionID uuid.UUID,
	modelRunID uuid.UUID,
	modelCallID uuid.UUID,
	input RecordModelCallRetriesInput,
) error

RecordModelCallRetries checkpoints failed attempts while the provider round remains in progress, preserving them even if the process exits mid-backoff.

func (*Store) RecordTurnWorkerGeneration added in v0.8.0

func (s *Store) RecordTurnWorkerGeneration(
	ctx context.Context,
	lease Lease,
	generationID uuid.UUID,
) error

RecordTurnWorkerGeneration names the worker that ran one turn. It updates only the lease's own turn, so a concurrent turn cannot be relabelled.

func (*Store) RecordWorkerContainer added in v0.8.0

func (s *Store) RecordWorkerContainer(
	ctx context.Context,
	generationID uuid.UUID,
	containerID string,
	imageDigest string,
) error

RecordWorkerContainer stores the container a Docker worker created. It is separate from the state transition because a container ID only exists once the daemon has accepted the create call.

func (*Store) RecordWorkerExit added in v0.8.0

func (s *Store) RecordWorkerExit(
	ctx context.Context,
	generationID uuid.UUID,
	exitCode int,
) error

RecordWorkerExit stores how a worker ended.

func (*Store) RecordWorkerProcess added in v0.8.0

func (s *Store) RecordWorkerProcess(
	ctx context.Context,
	generationID uuid.UUID,
	processID int,
) error

RecordWorkerProcess stores the operating system identity of a control worker.

func (*Store) RecoverInterrupted

func (s *Store) RecoverInterrupted(ctx context.Context) (int, error)

RecoverInterrupted marks active turns and their messages incomplete.

func (*Store) RecoverInterruptedAgentRuns added in v0.4.0

func (s *Store) RecoverInterruptedAgentRuns(ctx context.Context) (int, error)

RecoverInterruptedAgentRuns marks stale child runs terminal during startup.

func (*Store) RecoverInterruptedJobs added in v0.4.0

func (s *Store) RecoverInterruptedJobs(ctx context.Context) (int, error)

RecoverInterruptedJobs marks process rows left running by a prior process terminal. The original child process cannot be safely reattached.

func (*Store) RecoverInterruptedModelRuns added in v0.4.0

func (s *Store) RecoverInterruptedModelRuns(ctx context.Context) (int, error)

RecoverInterruptedModelRuns marks durable work left running by a prior Peen process terminal. No provider connection can be safely resumed in place.

func (*Store) RecoverWorkerTurns added in v0.24.0

func (s *Store) RecoverWorkerTurns(
	ctx context.Context,
	sessionID, generationID uuid.UUID,
) (int, error)

RecoverWorkerTurns releases only turns owned by the worker that ended. Their checkpoints remain available for audit; they are not model history.

func (*Store) RegisterCancellation

func (s *Store) RegisterCancellation(lease Lease, cancel context.CancelFunc)

RegisterCancellation associates cancellation with one exact active lease.

func (*Store) ReleaseTurn

func (s *Store) ReleaseTurn(lease Lease)

ReleaseTurn removes a lease only when it is still the registered turn.

func (*Store) RequestAgentRunCancellation added in v0.4.0

func (s *Store) RequestAgentRunCancellation(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
) (*models.AgentRun, bool, error)

RequestAgentRunCancellation records cancellation before signalling an active in-process child. It is idempotent for terminal and already-requested rows.

func (*Store) ReserveExecutionCompletion added in v0.25.0

func (s *Store) ReserveExecutionCompletion(
	ctx context.Context,
	sessionID uuid.UUID,
	lease ActivityLease,
) (*ExecutionCompletionSeal, error)

ReserveExecutionCompletion retains a terminal hook's empty-inbox boundary. A nil result requires continuation. Repeats retain the saved marker.

func (*Store) ResolveExecutionActivity added in v0.25.0

func (s *Store) ResolveExecutionActivity(
	ctx context.Context,
	sessionID, activityID uuid.UUID,
	input ResolveActivityInput,
) (*models.ExecutionActivity, error)

ResolveExecutionActivity records inspection of an unknown effect. Resolving a step never resumes a paused execution.

func (*Store) ResolveExecutionActivityFromActivity added in v0.25.0

func (s *Store) ResolveExecutionActivityFromActivity(
	ctx context.Context,
	sessionID, activityID uuid.UUID,
	input ResolveExecutionControlInput,
) (*models.ExecutionActivity, error)

ResolveExecutionActivityFromActivity records an inspected outcome while fencing the caller and target. It leaves a paused execution paused.

func (*Store) RestoreExecutionTurn added in v0.25.0

func (s *Store) RestoreExecutionTurn(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
	input RestoreExecutionTurnInput,
) (Lease, error)

RestoreExecutionTurn retains the original turn and never resumes a pause.

func (*Store) ResumeExecution added in v0.25.0

func (s *Store) ResumeExecution(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
) ([]uuid.UUID, error)

ResumeExecution changes only paused descendants of the explicit target. A read, worker replacement, or unrelated task never calls this method.

func (*Store) ResumeExecutionFromActivity added in v0.25.0

func (s *Store) ResumeExecutionFromActivity(
	ctx context.Context,
	sessionID, executionID uuid.UUID,
	input ResumeExecutionInput,
) ([]uuid.UUID, error)

ResumeExecutionFromActivity fences both the caller and the inspected target. A Stop that commits first prevents the caller from resuming retained work.

func (*Store) SaveContextSnapshot

func (s *Store) SaveContextSnapshot(
	ctx context.Context,
	snapshot *models.ContextSnapshot,
) error

SaveContextSnapshot stores an immutable resolved harness context.

func (*Store) SavePromptSnapshot

func (s *Store) SavePromptSnapshot(
	ctx context.Context,
	snapshot *models.PromptSnapshot,
) error

SavePromptSnapshot stores an immutable effective prompt.

func (*Store) SearchExecutions added in v0.25.0

func (s *Store) SearchExecutions(
	ctx context.Context,
	sessionID uuid.UUID,
	options SearchExecutionsOptions,
) (*ExecutionPage, error)

SearchExecutions reads every retained state without waking any execution. Times form a half-open interval; text is a literal substring, not SQL syntax.

func (*Store) SetFeedSignal added in v0.26.0

func (s *Store) SetFeedSignal(signal FeedSignalFunc)

SetFeedSignal installs the post-commit feed notifier, safe for concurrent use. A nil signal disables notification. Embedded runtimes never set one.

func (*Store) SetIdleCallback added in v0.26.2

func (s *Store) SetIdleCallback(callback IdleCallbackFunc)

SetIdleCallback installs the post-finalize idle notifier, safe for concurrent use. A nil callback disables notification.

func (*Store) TurnFeedStart added in v0.26.0

func (s *Store) TurnFeedStart(
	ctx context.Context,
	sessionID uuid.UUID,
	turnID uuid.UUID,
) (int64, bool, error)

TurnFeedStart returns the first feed sequence an event of turnID holds. The second return is false when the turn has no events yet.

func (*Store) UpdateWorkerGenerationState added in v0.8.0

func (s *Store) UpdateWorkerGenerationState(
	ctx context.Context,
	generationID uuid.UUID,
	state string,
	failureDetail string,
) error

UpdateWorkerGenerationState advances one generation's lifecycle.

Reaching ready stamps the start time and reaching a terminal state stamps the end time, so a durable record carries how long a worker actually ran.

type TurnEnd added in v0.30.0

type TurnEnd struct {
	State          models.TurnState `json:"state"`
	Classification string           `json:"classification"`
	EventType      string           `json:"eventType"`
	Detail         string           `json:"detail,omitempty"`
}

TurnEnd is how a running turn ended when no process finalizes it through its lease: Stop, a failed workflow, or a process that died. Detail is the error that ended it, as a client and the model may read it.

func CancelledTurnEnd added in v0.30.0

func CancelledTurnEnd() TurnEnd

CancelledTurnEnd is a turn Stop ended.

func FailedTurnEnd added in v0.30.0

func FailedTurnEnd(detail string) TurnEnd

FailedTurnEnd is a turn whose workflow failed with detail.

func (TurnEnd) Kind added in v0.31.0

func (e TurnEnd) Kind() TurnEnd

Kind is the end without its detail, which is what tells two ends apart.

type TurnEndNotice added in v0.32.0

type TurnEndNotice struct {
	TurnID              uuid.UUID         `json:"turnId"`
	State               models.TurnState  `json:"state"`
	Reason              string            `json:"reason"`
	Error               string            `json:"error,omitempty"`
	Message             string            `json:"message,omitempty"`
	UndeliveredMessages []string          `json:"undeliveredMessages,omitempty"`
	ToolCalls           []TurnEndToolCall `json:"toolCalls,omitempty"`
	ToolCallsOmitted    int               `json:"toolCallsOmitted,omitempty"`
}

TurnEndNotice is the data of a turn.failed or turn.cancelled notice. Message is the turn's opening user message, UndeliveredMessages the messages queued for the turn that never reached the model, and ToolCalls the calls the turn made, so the next turn knows what was asked and which effects already happened even though the ended turn's messages are left out of its history.

type TurnEndToolCall added in v0.32.0

type TurnEndToolCall struct {
	Name      string             `json:"name"`
	Arguments string             `json:"arguments"`
	Outcome   turnEndToolOutcome `json:"outcome"`
}

TurnEndToolCall is one tool call an ended turn made, with its arguments cut to turnEndToolArgumentBytes.

type TurnPage added in v0.4.0

type TurnPage struct {
	Items   []*models.Turn
	Limit   int
	Offset  int
	HasMore bool
}

TurnPage is one complete session-local turn page.

type WorkerGenerationPage added in v0.8.0

type WorkerGenerationPage struct {
	Items   []*models.WorkerGeneration
	Limit   int
	Offset  int
	HasMore bool
}

WorkerGenerationPage is one complete page of worker generations.

type WorkspaceSessionPage added in v0.8.0

type WorkspaceSessionPage struct {
	Items   []*models.Session
	Limit   int
	Offset  int
	HasMore bool
}

WorkspaceSessionPage is one complete page of durable sessions. Every session is bound to a canonical workspace, so the name says which sessions it holds without stuttering as session.SessionPage.

Source Files

Jump to

Keyboard shortcuts

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