sessions

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sessions owns the Session vocabulary: Sessions, Turns and their statuses, inputs, Environments and their provisioning failures, function calls, Item and Artifact reads, executor credentials, and the errors Session operations return. It also decides what Session writes publish: the public changes that report Turn and Session transitions, what a Turn that ends settles, measured Turn usage and the Session activity each change reports. The Session writes that several operations share are procedures here, over the transaction interfaces declared beside them: cancelling work, failing and terminating an Environment, tracking input activity, the admission gates, admitting a function result, reading a Turn's required actions, appending to a Turn's execution journal and projecting its observations and admitted inputs into Items, Turn usage and Subagents. Service runs the pooled Session use cases, such as staging a Turn's Artifacts, over Storage, and Reader declares the Session reads. ExecutionOperations runs the Session writes only the execution owner makes, such as recording function calls and their application receipts and journaling a Turn's observations, over the lease-bound ExecutionStorage.

Index

Constants

View Source
const (
	EnvironmentInputPending   = "pending"
	EnvironmentInputAdmitted  = "admitted"
	EnvironmentInputExpired   = "expired"
	EnvironmentInputCancelled = "cancelled"
	EnvironmentInputFailed    = "failed"
)
View Source
const (
	ProvisioningSetupCommand   = "setup"
	ProvisioningPythonPackages = "python"
	ProvisioningNPMPackages    = "npm"
	ProvisioningInitialFile    = "file"
	ProvisioningSkill          = "skill"
	ProvisioningHarness        = "harness"
)

Provisioning step kinds for ProvisioningFailure.Step.

View Source
const (
	RetainedChanges     = 256
	RetainedChangeBytes = 64 << 20
)

A Session keeps at most RetainedChanges public changes and RetainedChangeBytes of their payloads for live readers after each transaction, and always keeps its newest change even when it is larger.

View Source
const (
	TurnQueued     = "queued"
	TurnInProgress = "in_progress"
	TurnWaiting    = "waiting"
	TurnCompleted  = "completed"
	TurnFailed     = "failed"
	TurnCancelled  = "cancelled"
)
View Source
const ProvisioningFailureReason = "Failed to provision environment: initialization did not complete"

ProvisioningFailureReason is the safe reason for an Environment that failed without a confirmed failed step: timeouts, unknown effects, missing or old receipts, bootstrap rejection and Core restart during initialization.

Variables

View Source
var (
	ErrInvalidInput           = errors.New("invalid session input")
	ErrEnvironmentUnavailable = errors.New("environment is no longer available")
	ErrNotFound               = errors.New("session not found")
	ErrIdempotencyConflict    = errors.New("idempotency key was already used with different input")
)
View Source
var (
	// ErrUnknownFunctionCall rejects a result whose call_id names no function
	// call in the Session.
	ErrUnknownFunctionCall = errors.New("unknown pending tool call")
	// ErrFunctionCallTurnMismatch rejects a result whose call exists in the
	// Session but not in the named Turn, including a malformed or unknown Turn.
	ErrFunctionCallTurnMismatch = errors.New("tool call belongs to a different turn")
)

Result targets are resolved only inside a tenant-owned Session, after its lookup, so a missing or foreign Session still returns ErrNotFound (EVT-11).

View Source
var (
	// Session Items, Subagent Items and Subagent Turn Items.
	ErrItemCursor = &CursorError{Message: "Invalid session item ID in `after`"}
	// Subagents and Subagent Turns.
	ErrResourceCursor = &CursorError{Message: "Invalid resource ID in `after`"}
	// Session Artifacts.
	ErrArtifactCursor = &CursorError{Message: "after is not a valid artifact ID"}
)

Official messages for lists that reject an unresolved cursor with 400.

View Source
var ErrDeviceBindingConflict = errors.New("session is already bound to a different device")
View Source
var ErrEventLimit = errors.New("execution event storage limit exceeded")
View Source
var ErrExecutorCredentialExists = errors.New("executor key ID already exists; rotate explicitly")
View Source
var ErrFunctionResultConflict = errors.New("tool call already has a different result")

ErrFunctionResultConflict rejects a result that differs from the one already saved for its call, including after the Turn ended (EVT-12).

View Source
var ErrHostedEnvironmentFailed = fmt.Errorf("%w: the hosted environment failed to provision", ErrEnvironmentUnavailable)

ErrHostedEnvironmentFailed rejects new input on a Session whose hosted Environment failed to provision. It remains ErrEnvironmentUnavailable for internal callers; an expired Environment keeps that plain error.

View Source
var ErrInputPending = fmt.Errorf("%w: session input is still pending", ErrTurnConflict)

ErrInputPending rejects a new input batch while earlier Session input still waits for admission. It remains a Turn conflict for internal callers.

View Source
var ErrInstallationAuthorization = errors.New("installation authorization is invalid or expired; obtain a new command from the Session")
View Source
var ErrNotIdle = errors.New("session must be durably idle or failed without required actions before deletion")

ErrNotIdle rejects deletion of a Session that still has work or input pending. Callers cancel first and delete after the Session settles.

View Source
var ErrStreamGap = errors.New("live event buffer exceeded; recover through Session and Items reads")
View Source
var ErrTurnConflict = errors.New("turn state changed or cancellation was requested")
View Source
var ErrUnappliedInputs = errors.New("turn has messages without an executor receipt")

Functions

func AppendTurnEvent

func AppendTurnEvent(ctx context.Context, tx TurnEventTx, turn string, last int32, event ExecutionEvent) error

AppendTurnEvent records event in the Turn's journal after its last entry, last, which the caller read under the Session lock, and projects it. It records the terminal outcome, which the journal limits reserve an entry for.

func AppendTurnEvents

func AppendTurnEvents(ctx context.Context, tx TurnJournalTx, batch JournalBatch) error

AppendTurnEvents records batch in its Turn's journal and projects the new entries. A batch the journal already holds from the same position is an idempotent replay and changes nothing; a different batch there is ErrIdempotencyConflict. A new batch is recorded only as JournalBatch admits it, and a missing Turn is ErrNotFound.

func CancelTurn

func CancelTurn(ctx context.Context, tx TurnCancellationTx, turn Turn) error

CancelTurn requests the cancellation of turn, the Session's active Turn read under the Session lock, and publishes what the request settles: a queued Turn ends cancelled, and a waiting Turn reports its Session activity. Both read the Turn again after the request, which set its timestamps.

func CancelWork

func CancelWork(ctx context.Context, tx CancellationTx) error

CancelWork cancels the Session's active work: it requests the cancellation of the active Turn, then cancels the pending Environment input. Cancellation requests do not prove that native work has stopped.

func CheckComputeAdmission

func CheckComputeAdmission(ctx context.Context, tx ComputeAdmissionTx) error

CheckComputeAdmission admits a new execution owner, such as a Turn that starts or a file write, only while the Session's managed compute is running or has no suspension; otherwise it is ErrTurnConflict. Existing receipts stay readable in every phase.

func CheckFileWriteGate

func CheckFileWriteGate(ctx context.Context, tx FileWriteGateTx) error

CheckFileWriteGate holds new work while a file write to the Session's Environment is pending: it is ErrTurnConflict.

func CheckInputStart

func CheckInputStart(ctx context.Context, tx InputStartTx) error

CheckInputStart lets reserved Environment input, or a file write, start only on an idle Session: a pending file write, checked first, and an active Turn are both ErrTurnConflict.

func CreateEnvironmentDevice

func CreateEnvironmentDevice(ctx context.Context, tx EnvironmentDeviceTx, device ExecutionDevice, credentialHash string) error

CreateEnvironmentDevice creates the dedicated Runtime device of the Session's hosted Environment and binds it to the Session. A Session that is already bound to a device is ErrDeviceBindingConflict, so an existing credential is never widened.

func CreatesEnvironment

func CreatesEnvironment(configuration json.RawMessage) (bool, error)

CreatesEnvironment reports whether a Session created with the configuration snapshot has an Environment: a self_hosted or openai_hosted one does, and none or no Environment does not. Any other snapshot is ErrInvalidInput.

func EnvironmentType

func EnvironmentType(configuration json.RawMessage) (string, error)

EnvironmentType returns the type an Environment configuration snapshot names: self_hosted or openai_hosted.

func FailEnvironment

func FailEnvironment(ctx context.Context, tx EnvironmentFailureTx, environment Environment, reason string, detail *ProvisioningFailureDetail) error

FailEnvironment records the failure of the Session's live environment and ends the Session failed, in the observed official order: agent.session.environment.failed, the changes of cancelling the Session's work, an error event with the safe reason, then one agent.session.failed snapshot. Pending input settles as failed first, so the snapshot reports the settled input activity.

func LoadRequiredActions

func LoadRequiredActions(ctx context.Context, tx PendingFunctionCallsTx, turn Turn) ([]v1.FunctionCallAction, error)

LoadRequiredActions returns the function calls a Turn requires the caller to answer as public required actions: its pending calls while it accepts results, and none otherwise.

func MeasuredUsage

func MeasuredUsage(kind string, raw json.RawMessage) *v1.TokenUsage

MeasuredUsage interprets the token measurement an execution observation of kind carries: a usage report, a done payload, a terminal execution outcome or an applied cancellation receipt. It returns nil unless the breakdown is complete and consistent: every counter present and non-negative, cached tokens within input, reasoning tokens within output and the total the sum of input and output. An explicit zero is a measurement.

func ProjectInput

func ProjectInput(ctx context.Context, tx InputProjectionTx, sequence int64) error

ProjectInput projects the Session's admitted input at sequence: a message becomes its Session Items, and other inputs project nothing.

func ProjectSource

func ProjectSource(ctx context.Context, tx ProjectionTx, source Source) error

ProjectSource projects one observation under the Session lock. Subagent observations update the Session's Subagents, their Turns and Items and the root coordination Items. Any other observation replaces its root Turn's usage with the measurement it carries, then updates the Session Items it projects and journals their changes.

func TerminalStatus

func TerminalStatus(status string) bool

TerminalStatus reports whether a Turn status has ended the Turn. A terminal Turn is never reopened and its outcome is never overwritten.

func TerminateEnvironment

func TerminateEnvironment(ctx context.Context, tx EnvironmentTerminationTx, computeExpired bool, reason string, detail *ProvisioningFailureDetail) error

TerminateEnvironment settles the Session's Environment when its managed compute ends. A live Environment whose compute did not expire fails with the reason and detail, as FailEnvironment reports it. Otherwise the Environment expires if it is still live, its pending input fails and its work is cancelled, and the input activity this changes is reported.

func TrackInputActivity

func TrackInputActivity(ctx context.Context, tx InputActivityTx, apply func(context.Context) error) error

TrackInputActivity runs apply, the caller's writes in the same transaction, and reports the input activity they change. It reads the activity before and after apply, and only when it changed reads the Session's usage and journals the snapshot. When apply fails, it returns at once and the caller's transaction rolls back.

func ValidEngine

func ValidEngine(engine string) bool

func ValidTransition

func ValidTransition(from, to string) bool

ValidTransition reports whether a Turn may move from one status to another: a queued Turn starts, fails or is cancelled, and an in-progress or waiting Turn moves between the two or ends. An ended Turn never moves.

func ValidateInputKey

func ValidateInputKey(key string) error

ValidateInputKey enforces the shared request identity limit, including no-op requests.

Types

type ActiveTurnTx

type ActiveTurnTx interface {
	// LoadActiveTurn reads the Session's queued, in-progress or waiting Turn and
	// reports whether it has one.
	LoadActiveTurn(ctx context.Context) (Turn, bool, error)
}

ActiveTurnTx reads the Session's active Turn.

type Artifact

type Artifact struct {
	ID            string
	SessionID     string
	TurnID        string
	EnvironmentID string
	Path          string
	SizeBytes     int64
	CreatedAt     time.Time
}

Artifact is a file a completed Turn published from its Environment's outputs directory, immutable once published.

type ArtifactPage

type ArtifactPage struct {
	Artifacts  []Artifact
	NextCursor string
}

ArtifactPage is one page of a Session's published Artifacts. NextCursor is empty on the last page.

type ArtifactReader

type ArtifactReader interface {
	// GetSessionArtifact returns a published Artifact of the visible Session,
	// or ErrNotFound.
	GetSessionArtifact(ctx context.Context, tenantID, sessionID, artifactID string) (Artifact, error)
	// ListSessionArtifacts returns one page of the visible Session's published
	// Artifacts in publication-time and ID order. A non-empty environmentID
	// keeps the Artifacts that Environment produced; a malformed one matches
	// nothing. A limit outside 1..100 is ErrInvalidInput. A cursor that is not
	// a published Artifact of the Session, including a malformed one, is
	// ErrArtifactCursor.
	ListSessionArtifacts(ctx context.Context, tenantID, sessionID, environmentID, cursor string, limit int, ascending bool) (ArtifactPage, error)
	// ReadSessionArtifact passes consume a published Artifact and its content
	// from one snapshot, so a concurrent deletion never truncates a read it
	// admitted. It returns consume's error unchanged.
	ReadSessionArtifact(ctx context.Context, tenantID, sessionID, artifactID string, consume func(Artifact, io.Reader) error) error
}

ArtifactReader reads a Session's published Artifacts, independently of its Environment's availability.

type ArtifactSettlement

type ArtifactSettlement string

ArtifactSettlement is what a Turn that ended does with the Artifacts it staged.

const (
	// PublishArtifacts publishes the staged Artifacts at the Turn's completion
	// time. A path whose newest remaining Artifact has the same bytes keeps that
	// Artifact instead; new paths, changed bytes and paths whose newest Artifact
	// was deleted publish.
	PublishArtifacts ArtifactSettlement = "publish"
	// DiscardArtifacts deletes the staged Artifacts.
	DiscardArtifacts ArtifactSettlement = "discard"
)

type ArtifactStagingKey

type ArtifactStagingKey struct {
	TenantID      string
	SessionID     string
	TurnID        string
	EnvironmentID string
}

ArtifactStagingKey names the Turn whose export is staged and the Environment that produced it.

type ArtifactStagingTx

type ArtifactStagingTx interface {
	// LoadEnvironment reads the visible Session's Environment without a lock.
	LoadEnvironment(ctx context.Context) (Environment, error)
	// PutArtifactContent stores size bytes of content for path. The content
	// stays private until StageArtifacts records it.
	PutArtifactContent(ctx context.Context, path string, size int64, content io.Reader) error
	// LockSession locks the Session, including a publicly deleted one.
	LockSession(ctx context.Context) (LockedSession, error)
	// LoadTurn reads the key's Turn under the Session lock.
	LoadTurn(ctx context.Context) (Turn, error)
	// StageArtifacts records every content put in this transaction as a
	// private Artifact of the key's Turn and Environment.
	StageArtifacts(ctx context.Context) error
}

ArtifactStagingTx is the transaction StageTurnArtifacts runs in. It takes the Session lock only when LockSession is called.

type ArtifactStorage

type ArtifactStorage interface {
	// WithArtifactStaging runs stage in one transaction that commits only when
	// stage returns nil, so a failed staging leaves no content and no
	// Artifact. A malformed identifier in key is ErrInvalidInput.
	WithArtifactStaging(ctx context.Context, key ArtifactStagingKey, stage func(context.Context, ArtifactStagingTx) error) error
	// DeleteSessionArtifact removes a published Artifact of the visible
	// Session and its content under the Session lock, and records the write
	// audit, or returns ErrNotFound.
	DeleteSessionArtifact(ctx context.Context, tenantID, sessionID, artifactID string) error
}

ArtifactStorage persists a Session's Artifacts.

type CancellationTx

type CancellationTx interface {
	TurnCancellationTx
	ActiveTurnTx
	// CancelPendingInput settles the Session's pending Environment input
	// reservation as cancelled.
	CancelPendingInput(ctx context.Context) error
}

CancellationTx is the Session transaction CancelWork runs in.

type ChildItem

type ChildItem struct {
	ID, Subagent, Turn string
	Position           int32
	Payload            json.RawMessage
	Output             bool
}

ChildItem is a Subagent Item to store at its Turn position. Output Items take the Turn's next output index when they are first stored.

type ChildTurn

type ChildTurn struct {
	ID, Subagent, NativeID, Status string
	CreatedAtMS                    int64
	StartedAtMS, CompletedAtMS     *int64
	Usage                          json.RawMessage
}

ChildTurn is a Subagent's Turn. Its timestamps are native milliseconds and Usage is its measured usage, nil when unknown.

type ComputeAdmissionTx

type ComputeAdmissionTx interface {
	// LoadComputeSuspension reports whether the Session's managed compute is in
	// its suspension cycle: quiescing, suspending, suspended, restoring or
	// waking.
	LoadComputeSuspension(ctx context.Context) (bool, error)
}

ComputeAdmissionTx reads the Session's managed compute for CheckComputeAdmission.

type ConnectionTx

type ConnectionTx interface {
	InputActivityTx
	// LoadEnvironment reads the Session's Environment.
	LoadEnvironment(ctx context.Context) (Environment, error)
	// LoadConnection reads the Environment's connection generation and
	// reports whether it has one.
	LoadConnection(ctx context.Context, environment string) (EnvironmentConnection, bool, error)
	// ReplaceConnection starts the Environment's connection generation at
	// revision zero, replacing any earlier one.
	ReplaceConnection(ctx context.Context, environment, generation string) error
	// AdvanceConnection records the revision the current generation
	// committed.
	AdvanceConnection(ctx context.Context, environment string, revision int64) error
	// DeleteConnection discards the Environment's connection generation.
	DeleteConnection(ctx context.Context, environment string) error
	// SetConnectionStatus sets the Environment's connection status.
	SetConnectionStatus(ctx context.Context, environment, status string) error
}

ConnectionTx is the Session transaction the Environment connection operations run in.

type CreateSession

type CreateSession struct {
	// DeploymentProviderRevision is private creation metadata, never retry identity.
	DeploymentProviderRevision uuid.UUID `json:"-"`
	ExecutionConfiguration     *v1.SessionExecutionConfiguration
	ModelProvider              *v1.ModelProviderInput
	ModelProviderSource        string // session, agent or deployment; empty allows only openai_hosted
	Initialization             environmentconfig.Setup
	InitialFiles               []environmentconfig.InitialFile
	Creator                    identity.Subject
	CreationRequest            json.RawMessage
	Engine                     string
	Metadata                   map[string]string
	IdempotencyKey             string
	Configuration              json.RawMessage
	InitialInputs              []Input
}

type Creation

type Creation struct {
	Session Session
	Created bool
	Cursor  int64
}

Creation starts observation at the Session upsert. For a new creation, CreateSessionStream returns the committed Session projection that CreateSession returns, read after the creation commits; Cursor still precedes the initial inputs, so their events remain observable exactly once. Retries and FindSessionCreation return only the resource row and its cursor. Only a new creation emits a created snapshot and streams from Cursor; a stream retry of an existing creation sends no events.

type CursorError

type CursorError struct{ Message string }

CursorError reports a list `after` cursor that does not name a resource of that list once its parents have resolved. Message is the list family's observed official message; the API layer selects the family's code and param. Missing, malformed, other-type, other-parent and foreign cursors all produce the same error, so a cursor never reveals another tenant's resources.

func (*CursorError) Error

func (e *CursorError) Error() string

type DeleteSessionArtifactCommand

type DeleteSessionArtifactCommand struct {
	TenantID   string
	SessionID  string
	ArtifactID string
}

DeleteSessionArtifactCommand deletes one published Artifact.

type DeviceBindingTx

type DeviceBindingTx interface {
	// LoadDevice reports whether device is a device of the Session's tenant
	// that was not revoked.
	LoadDevice(ctx context.Context, device string) (bool, error)
	// BindDevice binds the device to the Session. A Session bound to another
	// device, or a device dedicated to another Session's Environment, is
	// ErrDeviceBindingConflict.
	BindDevice(ctx context.Context, device string) error
}

DeviceBindingTx is the Session transaction BindSessionDevice runs in.

type DeviceReader

type DeviceReader interface {
	// GetSessionDevice reads the Runtime device bound to the Session once its
	// Environment preparation completed; before that, and without a bound
	// device, it is ErrNotFound.
	GetSessionDevice(ctx context.Context, tenant, session string) (ExecutionDevice, error)
	// GetSessionRuntimeDevice reads the Runtime device bound to the Session,
	// or ErrNotFound. It reports an authorized connection binding and does not
	// admit native execution or file access before preparation completes.
	GetSessionRuntimeDevice(ctx context.Context, tenant, session string) (ExecutionDevice, error)
	// GetDeviceCredential reads the credential the Runtime gateway
	// authenticates a device with, and reports whether the device still has
	// authority.
	GetDeviceCredential(ctx context.Context, device string) (runtimedevice.Credential, bool, error)
	// ListEnrolledRuntimeBindings lists the enrolled user-managed Runtimes of
	// live Environments.
	ListEnrolledRuntimeBindings(ctx context.Context) ([]EnrolledRuntimeBinding, error)
}

DeviceReader reads Runtime devices and their Session bindings.

type DeviceRegistration

type DeviceRegistration struct {
	Name           string
	CredentialHash string
}

DeviceRegistration is a Runtime device's name and the SHA-256 digest of its credential, as NewDeviceRegistration validates them.

func NewDeviceRegistration

func NewDeviceRegistration(name, credentialHash string) (DeviceRegistration, error)

NewDeviceRegistration validates a device registration: a name of 1 to 256 bytes once trimmed, and a SHA-256 credential digest in hex, which it normalizes to lowercase. Anything else is ErrInvalidInput.

type DeviceStorage

type DeviceStorage interface {
	// CreateDevice stores a new device of the tenant and returns it.
	CreateDevice(ctx context.Context, tenant string, registration DeviceRegistration) (ExecutionDevice, error)
	// RevokeDevice revokes the tenant's device; an unknown device is
	// ErrNotFound.
	RevokeDevice(ctx context.Context, tenant, device string) error
	// TouchDevice records that the device was seen and reports whether it
	// still has authority.
	TouchDevice(ctx context.Context, device string) (bool, error)
	// TouchAuthenticatedDevice records that the device was seen with the
	// credential and reports whether that credential still has authority.
	TouchAuthenticatedDevice(ctx context.Context, device, credentialHash string) (bool, error)
	// WithEnrollment authenticates the executor credential for the
	// Environment, then runs apply in the transaction of the Environment's
	// Session, with the Environment and what the Session lock shows. A
	// credential that does not authenticate is ErrNotFound.
	WithEnrollment(ctx context.Context, environment, credentialHash string, apply func(context.Context, EnrollmentTx, Environment, LockedSession) error) error
}

DeviceStorage stores Runtime devices.

type Ending

type Ending struct {
	// Unfinished are the Turn's Items still in progress, in any order.
	Unfinished []UnfinishedItem
	// Usage is the Session's public usage with the Turn ended.
	Usage json.RawMessage
}

Ending holds the facts a Turn that ended is settled with, read under the Session lock in the transaction that ends it.

type EnrolledRuntimeBinding

type EnrolledRuntimeBinding struct {
	DeviceID, TenantID, EnvironmentID, SessionID string
}

EnrolledRuntimeBinding identifies user-managed compute, without an allocation or any promise of live authorization. The Worker rechecks the socket's key.

type EnrollmentAuthority

type EnrollmentAuthority struct {
	KeyID              string
	WorkspaceDirectory string
}

EnrollmentAuthority is what an executor credential authorizes when it enrolls a Runtime: the key and the Environment's workspace directory.

type EnrollmentTx

type EnrollmentTx interface {
	// AuthorizeEnrollment rechecks, under the Session lock, that the
	// credential still authorizes enrolling a Runtime for the live self_hosted
	// Environment, and holds the key's lock until the transaction ends, so
	// revocation cannot race enrollment. Without that authority it is
	// ErrNotFound.
	AuthorizeEnrollment(ctx context.Context) (EnrollmentAuthority, error)
	// EnrollDevice creates the Environment's user-managed Runtime device for
	// the key, or returns the device the same key already enrolled. A device
	// of another key, or a revoked one, is ErrDeviceBindingConflict.
	EnrollDevice(ctx context.Context, key string) (string, error)
	// BindDevice binds the device to the Session. A Session bound to another
	// device is ErrDeviceBindingConflict.
	BindDevice(ctx context.Context, device string) error
}

EnrollmentTx is the Session transaction EnrollRuntime runs in.

type Environment

type Environment struct {
	Initialization string
	ID             string
	SessionID      string
	TenantID       string
	Status         string
	CreatedAt      time.Time
	Configuration  json.RawMessage
}

Environment retains execution ownership; its configuration is an internal snapshot, not a public response.

type EnvironmentConnection

type EnvironmentConnection struct {
	Generation string
	Revision   int64
}

EnvironmentConnection is the connection generation that observes an Environment and the last revision it committed.

type EnvironmentDeviceTx

type EnvironmentDeviceTx interface {
	// LoadBoundDevice reports whether the Session is bound to a Runtime device
	// that still has authority.
	LoadBoundDevice(ctx context.Context) (bool, error)
	// InsertEnvironmentDevice inserts device, with the credential hash, as the
	// dedicated Runtime device of the Session's hosted Environment and binds
	// it to the Session. An Environment that already has a device or cannot
	// take one is ErrDeviceBindingConflict.
	InsertEnvironmentDevice(ctx context.Context, device ExecutionDevice, credentialHash string) error
}

EnvironmentDeviceTx is the Session transaction CreateEnvironmentDevice runs in.

type EnvironmentExecution

type EnvironmentExecution interface {
	// WithInitialization runs apply in the transaction of the tenant's
	// Session, with what the Session lock shows. A malformed Session ID is a
	// missing Session.
	WithInitialization(ctx context.Context, tenant, session string, apply func(context.Context, InitializationTx, LockedSession) error) error
	// WithConnection runs apply in the transaction of the Session that owns
	// the tenant's Environment, with what the Session lock shows. An
	// Environment of a publicly deleted Session, or a missing one, is
	// ErrNotFound.
	WithConnection(ctx context.Context, tenant, environment string, apply func(context.Context, ConnectionTx, LockedSession) error) error
	// WithDeviceBinding runs apply in the transaction of the tenant's Session,
	// with what the Session lock shows.
	WithDeviceBinding(ctx context.Context, tenant, session string, apply func(context.Context, DeviceBindingTx, LockedSession) error) error
	// WithFileWriteReservation reads the tenant's Environment, then runs apply
	// in the transaction of its Session, with the Environment and what the
	// Session lock shows. An Environment of a publicly deleted Session, or a
	// missing one, is ErrNotFound.
	WithFileWriteReservation(ctx context.Context, tenant, environment string, apply func(context.Context, FileWriteReservationTx, Environment, LockedSession) error) error
	// WithFileWriteSettlement reads the file write to the tenant's
	// Environment, including one whose Session was publicly deleted, then runs
	// apply in the transaction of its Session. A malformed ID is
	// ErrInvalidInput and an unknown write ErrNotFound.
	WithFileWriteSettlement(ctx context.Context, tenant, environment, write string, apply func(context.Context, FileWriteSettlementTx) error) error
	// ListEnvironmentConnections lists, in Environment order after the given
	// Environment, or from the first one when after is empty, a page of the
	// Environments of Sessions that were not publicly deleted and that are
	// connected or have a connection generation.
	ListEnvironmentConnections(ctx context.Context, after string) ([]EnvironmentKey, error)
}

EnvironmentExecution is the lease-bound storage of the Environment execution operations.

type EnvironmentExecutorCredentialTx

type EnvironmentExecutorCredentialTx interface {
	ExecutorCredentialTx
	// LoadSessionCreator reads who created the Session and reports whether
	// the Session recorded a creator.
	LoadSessionCreator(ctx context.Context) (identity.Subject, bool, error)
}

EnvironmentExecutorCredentialTx is the transaction of the Session whose Environment a credential is restricted to.

type EnvironmentFailure

type EnvironmentFailure struct {
	Reason   string                     `json:"reason"`
	FailedAt time.Time                  `json:"failed_at"`
	Detail   *ProvisioningFailureDetail `json:"-"`
}

EnvironmentFailure is an Environment's recorded provisioning failure. It makes the Session failed with this reason and last activity time.

type EnvironmentFailureTx

type EnvironmentFailureTx interface {
	CancellationTx
	InputActivityTx
	// RecordEnvironmentFailure marks the Session's live Environment failed
	// with the reason and the private detail, and returns the failure time the
	// database clock recorded.
	RecordEnvironmentFailure(ctx context.Context, environment, reason string, detail *ProvisioningFailureDetail) (time.Time, error)
	// FailPendingInput settles the Session's pending Environment input
	// reservation as failed.
	FailPendingInput(ctx context.Context) error
}

EnvironmentFailureTx is the Session transaction FailEnvironment runs in.

type EnvironmentFileWrite

type EnvironmentFileWrite struct {
	Identity                 FileWriteIdentity
	EnvironmentID, SessionID string
	State                    string
	CreatedAt                time.Time
	SettledAt                *time.Time
	Replayed                 bool
}

type EnvironmentInitialization

type EnvironmentInitialization struct {
	EnvironmentID, SessionID, TenantID, DeviceID, State, Engine string
}

EnvironmentInitialization owns preparation independently of compute ownership. A running record without its process-local owner is unknown, never replayable.

type EnvironmentInputActivity

type EnvironmentInputActivity struct {
	Status        string    `json:"status"`
	EnvironmentID string    `json:"environment_id,omitempty"`
	Failure       string    `json:"failure,omitempty"`
	LastActiveAt  time.Time `json:"last_active_at"`
}

EnvironmentInputActivity is the reservation-owned override before a newer Turn exists.

func InputActivity

func InputActivity(state *EnvironmentInputState) (*EnvironmentInputActivity, bool)

InputActivity projects the Session's input activity from its latest reservation, nil when it has none, and reports whether that reservation is still pending and can start a Turn. A hosted initial input that is pending or cancelled has no activity: no Turn has started, and the pinned Session contract permits idle while a hosted Environment provisions, so neither a caller action nor an invented transition is reported. It still reports whether the input is pending.

type EnvironmentInputReservation

type EnvironmentInputReservation struct {
	ID        string
	SessionID string
	State     string
	IsInitial bool
	Inputs    []Input
	CreatedAt time.Time
	Deadline  time.Time
	SettledAt *time.Time
	Receipts  []InputReceipt
}

EnvironmentInputReservation is private admission state, not a public Session projection.

type EnvironmentInputState

type EnvironmentInputState struct {
	// State is the reservation's state.
	State   string
	Initial bool
	// CreatedAt is when the reservation was made, and SettledAt when it stopped
	// being pending; SettledAt is zero while it is pending.
	CreatedAt time.Time
	SettledAt time.Time
	// FailureCode is the recorded failure of a failed reservation, empty when
	// none was recorded.
	FailureCode   string
	EnvironmentID string
	// EnvironmentType is the type the Session's Environment configuration names.
	EnvironmentType string
	// EnvironmentStatus is the Environment's connection status.
	EnvironmentStatus string
}

EnvironmentInputState is the Session's latest Environment input reservation that no Turn has admitted or superseded, with the facts of its Environment. While a Turn is active or newer than the latest reservation, the Session has none.

type EnvironmentInputWork

type EnvironmentInputWork struct{ TenantID, SessionID, ReservationID string }

type EnvironmentKey

type EnvironmentKey struct{ TenantID, EnvironmentID string }

EnvironmentKey names one Environment of a tenant.

type EnvironmentReader

type EnvironmentReader interface {
	// GetEnvironment reads the tenant's Environment of a Session that was not
	// publicly deleted; otherwise it is ErrNotFound.
	GetEnvironment(ctx context.Context, tenant, environment string) (Environment, error)
	// GetSessionEnvironment reads the Environment of the tenant's Session
	// that was not publicly deleted; otherwise it is ErrNotFound.
	GetSessionEnvironment(ctx context.Context, tenant, session string) (Environment, error)
	// ListEnvironmentInitializations lists, in Environment order after the
	// given Environment, a page of the live Environments whose preparation is
	// pending or running.
	ListEnvironmentInitializations(ctx context.Context, after string) ([]EnvironmentInitialization, error)
	// ReadEnvironmentSetup opens the setup frozen for the Session's
	// Environment. A missing Session is ErrNotFound and a missing credential
	// key credentialcrypto.ErrUnavailable; frozen data that does not open or
	// validate is an internal error.
	ReadEnvironmentSetup(ctx context.Context, tenant, session string) (environmentconfig.Setup, error)
	// ReadInitialEnvironmentFile opens the initial file frozen at position for
	// the Session's Environment, so an installation holds one file at a time.
	// A missing file is ErrNotFound and a missing credential key
	// credentialcrypto.ErrUnavailable; a file that does not open or match its
	// recorded size is an internal error.
	ReadInitialEnvironmentFile(ctx context.Context, tenant, session string, position int) (environmentconfig.InitialFileMetadata, []byte, error)
}

EnvironmentReader reads Environments, their preparation and the Session data frozen for it.

type EnvironmentTerminationTx

type EnvironmentTerminationTx interface {
	EnvironmentFailureTx
	// LoadEnvironment reads the Session's Environment.
	LoadEnvironment(ctx context.Context) (Environment, error)
	// ExpireEnvironment sets the status of the Session's Environment to
	// expired.
	ExpireEnvironment(ctx context.Context, environment string) error
}

EnvironmentTerminationTx is the Session transaction TerminateEnvironment runs in.

type EventProjectionTx

type EventProjectionTx interface {
	ProjectionTx
	// CountEvents adds count entries of size payload bytes to what the Turn's
	// journal holds.
	CountEvents(ctx context.Context, turn string, count int32, size int64) error
	// LoadEventSources reads the Turn's journal entries from position first, in
	// order.
	LoadEventSources(ctx context.Context, turn string, first int32) ([]Source, error)
}

EventProjectionTx counts a Turn's new journal entries and projects them.

type ExecutionBinding

type ExecutionBinding struct {
	Device          ExecutionDevice
	NativeSessionID string
	HasStartedTurn  bool
}

ExecutionBinding identifies the Runtime and native history selected for one API Session.

type ExecutionDevice

type ExecutionDevice struct {
	ID            string
	Name          string
	EnvironmentID string
}

ExecutionDevice contains safe identity only, never a device credential.

type ExecutionEvent

type ExecutionEvent struct {
	Kind    string          `json:"kind"`
	Payload json.RawMessage `json:"payload"`
}

type ExecutionOperations

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

ExecutionOperations are the Session writes only the execution owner makes. Each runs in a Session transaction on the connection that holds the execution lease, so losing the lease fences it.

func NewExecutionOperations

func NewExecutionOperations(storage ExecutionStorage) (*ExecutionOperations, error)

NewExecutionOperations binds the Session execution operations to the lease-bound storage of one execution owner.

func (*ExecutionOperations) AppendTurnEvents

func (o *ExecutionOperations) AppendTurnEvents(ctx context.Context, tenant, session, turn string, first int32, events []ExecutionEvent) error

AppendTurnEvents records an ordered batch of a Turn's execution observations in its journal from position first and projects them, as the AppendTurnEvents procedure decides. A malformed tenant, Session or Turn ID is ErrInvalidInput, before the batch is validated and before the Session is looked up. The journal is Core-internal; it is not the public event stream.

func (*ExecutionOperations) BindSessionDevice

func (o *ExecutionOperations) BindSessionDevice(ctx context.Context, tenant, session, device string) error

BindSessionDevice binds the tenant's device to the Session, including a publicly deleted one. A retry with the same device succeeds and another device is ErrDeviceBindingConflict, so a Session's filesystem never moves silently. A malformed device ID is ErrInvalidInput, and a revoked or unknown device ErrNotFound. Dispatchers read the full Session binding before delivery.

func (*ExecutionOperations) ClaimEnvironmentInitialization

func (o *ExecutionOperations) ClaimEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization) error

ClaimEnvironmentInitialization starts the listed pending preparation on its device.

func (*ExecutionOperations) CompleteEnvironmentInitialization

func (o *ExecutionOperations) CompleteEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization) error

CompleteEnvironmentInitialization completes the claimed preparation.

func (*ExecutionOperations) ConfirmFunctionResult

func (o *ExecutionOperations) ConfirmFunctionResult(ctx context.Context, tenant, session, turn, call string) error

ConfirmFunctionResult records that the executor applied the call's saved result, not that the tool succeeded, and journals the Turn's remaining required actions. A repeated receipt changes nothing.

func (*ExecutionOperations) FailEnvironmentInitialization

func (o *ExecutionOperations) FailEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization, failure ProvisioningFailure) error

FailEnvironmentInitialization records the failure of a preparation that did not complete and fails the Environment, as FailEnvironment reports it. It records state and settles work; it never destroys compute or a workspace.

func (*ExecutionOperations) ObserveEnvironmentConnection

func (o *ExecutionOperations) ObserveEnvironmentConnection(ctx context.Context, tenant, environment, generation string, revision int64, connected bool) error

ObserveEnvironmentConnection commits only a newer observation of the current generation, with the status change it reports. Connectivity is transport evidence, not native preparation readiness or process quiescence. An observation of a failed or expired Environment is ErrInvalidInput.

func (*ExecutionOperations) PendingFunctionCalls

func (o *ExecutionOperations) PendingFunctionCalls(ctx context.Context, tenant, session, turn string) ([]FunctionCall, error)

PendingFunctionCalls returns the Turn's calls without an application receipt, with their saved results. A cancelling or ended Turn has none.

func (*ExecutionOperations) ReconcileEnvironmentConnections

func (o *ExecutionOperations) ReconcileEnvironmentConnections(ctx context.Context) error

ReconcileEnvironmentConnections runs before a new execution owner's connection producers start. It discards the generations of earlier processes and records that their connected transport was lost. An Environment that is gone by the time its turn comes is skipped.

func (*ExecutionOperations) RecordFunctionCall

func (o *ExecutionOperations) RecordFunctionCall(ctx context.Context, tenant, session, turn string, call FunctionCall) error

RecordFunctionCall records a call an executor reported for its Turn and journals the Turn's required actions with it. A retry of the recorded call changes nothing.

func (*ExecutionOperations) ReplaceEnvironmentConnection

func (o *ExecutionOperations) ReplaceEnvironmentConnection(ctx context.Context, tenant, environment, generation string) error

ReplaceEnvironmentConnection starts an ordered connection generation for the Environment without claiming a connection; a connected Environment becomes disconnected. The caller serializes replacements and never retries an older replacement after its successor. A failed or expired Environment is ErrInvalidInput.

func (*ExecutionOperations) ReserveEnvironmentFileWrite

func (o *ExecutionOperations) ReserveEnvironmentFileWrite(ctx context.Context, tenant, environment string, key FileWriteIdentity) (EnvironmentFileWrite, error)

ReserveEnvironmentFileWrite persists a file write's intent before it is dispatched to the Environment's Runtime device. A retry with the same identity replays the earlier write, Replayed, and never authorizes sending an unknown write again; another identity for the ID is ErrIdempotencyConflict. The write-audit source in ctx, when present, must be valid for the tenant; it is stored with the intent and audited when the write commits.

func (*ExecutionOperations) SettleEnvironmentFileWrite

func (o *ExecutionOperations) SettleEnvironmentFileWrite(ctx context.Context, tenant, environment string, key FileWriteIdentity, state string) (EnvironmentFileWrite, error)

SettleEnvironmentFileWrite settles a pending write as committed or rejected from an independently validated exact receipt. A missing receipt, cancellation or owner retirement is not a rejected upload, so the caller leaves the write pending. Settling it again in the same state replays it, Replayed; another identity or state is ErrIdempotencyConflict. It also settles a write whose Session was publicly deleted. A committed write records its upload_file write audit.

type ExecutionStorage

type ExecutionStorage interface {
	EnvironmentExecution
	FunctionExecution
	JournalExecution
}

ExecutionStorage is the lease-bound Session storage, one family per line.

type ExecutionWork

type ExecutionWork struct{ TenantID, SessionID, TurnID, Status string }

type ExecutorConnectionState

type ExecutorConnectionState struct {
	DeviceID          string     `json:"-"`
	BoundKeyID        *string    `json:"-"`
	EnrolledAt        *time.Time `json:"-"`
	LastSeenAt        *time.Time `json:"-"`
	CredentialHash    string     `json:"-"`
	EnvironmentStatus string     `json:"-"`
}

ExecutorConnectionState is an internal durable observation, never a wire payload. In particular the current credential digest must not be serialized.

type ExecutorCredential

type ExecutorCredential struct {
	KeyID     string     `json:"key_id" format:"uuid"`
	CreatedAt time.Time  `json:"created_at"`
	RevokedAt *time.Time `json:"revoked_at" extensions:"x-nullable"`
}

ExecutorCredential is the metadata of one Environment executor credential. Its secret is returned only when issued or rotated.

type ExecutorCredentialGrant

type ExecutorCredentialGrant struct {
	Principal     identity.Principal
	KeyID         string
	EnvironmentID string
	Digest        string
}

ExecutorCredentialGrant is a new executor credential: its key, the principal it executes as, the Environment it is restricted to, empty for none, and the SHA-256 digest of its secret.

type ExecutorCredentialReader

type ExecutorCredentialReader interface {
	// AuthenticateEnvironmentExecutor checks, in one database snapshot, that
	// the credential whose SHA-256 digest is given is current for the
	// Environment and belongs to its Session's creator, and returns the
	// Session's tenant. Any other credential is ErrNotFound.
	AuthenticateEnvironmentExecutor(ctx context.Context, environment, digest string) (string, error)
	// ProjectExecutorCredentialState reads, in one snapshot, the connection
	// facts of the tenant's self_hosted Environment and the metadata of the
	// credentials restricted to it that the Project's principal holds, oldest
	// first. An invalid principal is ErrInvalidInput; an Environment of a
	// publicly deleted Session, another type or another tenant is ErrNotFound.
	// The snapshot ends before any live observation of the connection.
	ProjectExecutorCredentialState(ctx context.Context, project identity.Principal, environment string) (ExecutorCredentialState, error)
}

ExecutorCredentialReader authenticates Environment executor credentials and reads a Project's credentials for an Environment.

type ExecutorCredentialState

type ExecutorCredentialState struct {
	EnvironmentID string `json:"-"`
	Credentials   []ExecutorCredential
	Connection    ExecutorConnectionState
}

type ExecutorCredentialStorage

type ExecutorCredentialStorage interface {
	// GetEnvironment reads the tenant's Environment of a Session that was not
	// publicly deleted, as EnvironmentReader does.
	GetEnvironment(ctx context.Context, tenant, environment string) (Environment, error)
	// LoadProjectArchived reports whether the tenant's Project is archived. A
	// tenant without a Project is ErrNotFound.
	LoadProjectArchived(ctx context.Context, tenant string) (bool, error)
	// ExecutorProjectExists reports whether the scope's organization and
	// Project map to its execution tenant.
	ExecutorProjectExists(ctx context.Context, scope identity.ProjectScope) (bool, error)
	// LoadExecutorCredentialRestriction reads the Environment the principal's
	// key is restricted to, empty for an unrestricted key. A key of another
	// principal or Project, or an unknown one, is ErrNotFound.
	LoadExecutorCredentialRestriction(ctx context.Context, principal identity.Principal, key string) (string, error)
	// SignInstallation returns the signature of an installation authorization
	// payload under the credential key. Without that key it is
	// credentialcrypto.ErrUnavailable.
	SignInstallation(ctx context.Context, payload string) (string, error)
	// VerifyInstallation checks the signature of an installation
	// authorization payload: another signature is
	// ErrInstallationAuthorization, and a service without the credential key
	// credentialcrypto.ErrUnavailable.
	VerifyInstallation(ctx context.Context, payload, signature string) error
	// WithExecutorCredentials runs apply in a transaction of the tenant.
	WithExecutorCredentials(ctx context.Context, tenant string, apply func(context.Context, ExecutorCredentialTx) error) error
	// WithEnvironmentExecutorCredentials reads the tenant's Environment, then
	// runs apply in the transaction of its Session, with what the Session lock
	// shows. A malformed Environment ID is ErrInvalidInput, and an Environment
	// of a publicly deleted Session, or a missing one, ErrNotFound.
	WithEnvironmentExecutorCredentials(ctx context.Context, tenant, environment string, apply func(context.Context, EnvironmentExecutorCredentialTx, LockedSession) error) error
}

ExecutorCredentialStorage stores Environment executor credentials and signs installation authorizations.

type ExecutorCredentialTx

type ExecutorCredentialTx interface {
	// LockProject share-locks the tenant's Project, which archiving updates,
	// and reports whether it is archived, so a write either commits before the
	// archive or sees it. A tenant without a Project is ErrNotFound.
	LockProject(ctx context.Context) (bool, error)
	// ListExecutorCredentials lists the subject's keys restricted to the
	// Environment, oldest first.
	ListExecutorCredentials(ctx context.Context, environment string, subject identity.Subject) ([]ExecutorCredential, error)
	// AuthenticateExecutor reports whether the secret with the SHA-256 digest
	// authenticates for the Environment, as AuthenticateEnvironmentExecutor
	// checks.
	AuthenticateExecutor(ctx context.Context, environment, digest string) (bool, error)
	// IssueExecutorCredential stores the new credential in its principal's
	// Project and returns its key and restriction. When no credential is
	// stored, because the key ID exists or the restriction names an
	// Environment the principal did not create, it is
	// ErrExecutorCredentialExists.
	IssueExecutorCredential(ctx context.Context, grant ExecutorCredentialGrant) (IssuedExecutorCredential, error)
	// RotateExecutorCredential replaces the secret of the subject's key with
	// the one whose SHA-256 digest is given, restores the key if it was
	// revoked, and returns its key and restriction. An unknown key is
	// ErrNotFound.
	RotateExecutorCredential(ctx context.Context, subject identity.Subject, key, digest string) (IssuedExecutorCredential, error)
	// RevokeExecutorCredential revokes the subject's key; revoking it again
	// changes nothing. An unknown key is ErrNotFound.
	RevokeExecutorCredential(ctx context.Context, subject identity.Subject, key string) error
	// RecordExecutorCredentialAudit records the administrator audit entry of
	// the action on the key under the provenance in ctx. It never records a
	// secret.
	RecordExecutorCredentialAudit(ctx context.Context, action, key string) error
}

ExecutorCredentialTx is the transaction of one tenant that executor credentials are written in.

type FileWriteGateTx

type FileWriteGateTx interface {
	// LoadPendingFileWrite reports whether a file write to the Session's
	// Environment is pending.
	LoadPendingFileWrite(ctx context.Context) (bool, error)
}

FileWriteGateTx reads the Session's Environment file writes for CheckFileWriteGate.

type FileWriteIdentity

type FileWriteIdentity struct {
	ID, DeviceID, RequestSHA256 string
}

FileWriteIdentity binds a private mutation to one dedicated local Runtime. RequestSHA256 covers the canonical destination, byte count and data digest. The caller must qualify that binding and validate native receipts independently; persistence alone is neither placement authority nor permission to send bytes.

func (FileWriteIdentity) Valid

func (k FileWriteIdentity) Valid() bool

type FileWriteReservationTx

type FileWriteReservationTx interface {
	FileWriteTx
	ComputeAdmissionTx
	InputStartTx
	// LoadEnvironment reads the Session's Environment.
	LoadEnvironment(ctx context.Context) (Environment, error)
	// LoadSessionDevice reads the Runtime device bound to the Session and
	// reports whether the Session has one that still has authority.
	LoadSessionDevice(ctx context.Context) (ExecutionDevice, bool, error)
	// LoadPendingInput reports whether Environment input reserved for the
	// Session is pending.
	LoadPendingInput(ctx context.Context) (bool, error)
	// CreateFileWrite stores the pending write to the Environment with the
	// write-audit source in ctx, if any, and returns it.
	CreateFileWrite(ctx context.Context, key FileWriteIdentity) (EnvironmentFileWrite, error)
}

FileWriteReservationTx is the Session transaction a file write is reserved in.

type FileWriteSettlementTx

type FileWriteSettlementTx interface {
	FileWriteTx
	// SettleFileWrite settles the pending write in the state and returns it.
	SettleFileWrite(ctx context.Context, write, state string) (EnvironmentFileWrite, error)
	// RecordFileWriteAudit records the upload_file write audit of the write
	// under the write-audit source stored when it was reserved. A write
	// reserved without one records nothing.
	RecordFileWriteAudit(ctx context.Context, write string) error
}

FileWriteSettlementTx is the Session transaction a file write is settled in.

type FileWriteTx

type FileWriteTx interface {
	// LoadFileWrite reads the write with the ID to the Environment and reports
	// whether it exists.
	LoadFileWrite(ctx context.Context, write string) (EnvironmentFileWrite, bool, error)
}

FileWriteTx reads the file writes to one Environment inside its Session's transaction.

type FunctionCall

type FunctionCall struct {
	CallID, ExecutorCallID, Name string
	Arguments                    json.RawMessage
	Result                       json.RawMessage
	Applied                      bool
}

FunctionCall retains public identity and its opaque execution-adapter reference.

type FunctionCallMatch

type FunctionCallMatch struct {
	// Recorded reports that the Turn already has a call with the public
	// identity.
	Recorded bool
	// Matches reports that the recorded call has the same executor identity,
	// name and arguments.
	Matches bool
}

FunctionCallMatch is what a Turn's stored call shows about a reported call.

type FunctionExecution

type FunctionExecution interface {
	// WithFunctionTurn runs apply in one transaction on the execution lease,
	// under the Session lock, with the tenant's Turn as the transaction reads
	// it. It commits only when apply succeeds. A malformed ID is
	// ErrInvalidInput, and a missing Session or Turn is ErrNotFound; a publicly
	// deleted Session still settles its Turn.
	WithFunctionTurn(ctx context.Context, tenant, session, turn string, apply func(context.Context, FunctionTx, Turn) error) error
}

FunctionExecution is the lease-bound storage of function calls.

type FunctionResultInput

type FunctionResultInput struct {
	TurnID string          `json:"turn_id"`
	CallID string          `json:"call_id"`
	Result json.RawMessage `json:"result"`
}

FunctionResultInput identifies a persisted call; Result is validated by the API. It is an internal command, not an upstream input event. TurnID is the caller's value and is resolved within the Session at admission.

func ParseFunctionResultInput

func ParseFunctionResultInput(raw json.RawMessage) (FunctionResultInput, error)

ParseFunctionResultInput decodes a tool_result input payload: a Turn ID, a call identity and a result object, which it normalizes. It does not check that the Turn or call exists; AdmitFunctionResult resolves them.

type FunctionResultMatch

type FunctionResultMatch struct {
	// Recorded reports that the Turn has the call.
	Recorded bool
	// Submitted reports that the call already has a result.
	Submitted bool
	// Matches reports that the saved result equals the submitted one.
	Matches bool
}

FunctionResultMatch is what a Turn's stored call shows about a submitted result.

type FunctionResultTx

type FunctionResultTx interface {
	// FindResultTurn reads the Session's Turn that a result names and reports
	// whether the Session has it. A malformed ID names no Turn.
	FindResultTurn(ctx context.Context, turn string) (Turn, bool, error)
	// MatchFunctionResult compares result with the Turn's call.
	MatchFunctionResult(ctx context.Context, turn, call string, result json.RawMessage) (FunctionResultMatch, error)
	// SubmitFunctionResult saves the result of the Turn's call.
	SubmitFunctionResult(ctx context.Context, turn, call string, result json.RawMessage) error
	// HasFunctionCall reports whether any Turn of the Session has the call.
	HasFunctionCall(ctx context.Context, call string) (bool, error)
}

FunctionResultTx is the Session transaction a function result is admitted in.

type FunctionTx

type FunctionTx interface {
	JournalTx
	PendingFunctionCallsTx
	// MatchFunctionCall compares call with the Turn's call of the same public
	// identity.
	MatchFunctionCall(ctx context.Context, turn string, call FunctionCall) (FunctionCallMatch, error)
	// CreateFunctionCall records a new call of the Turn. A call the Turn
	// already has is ErrIdempotencyConflict.
	CreateFunctionCall(ctx context.Context, turn string, call FunctionCall) error
	// LoadFunctionCall reads the Turn's call and reports whether it has it.
	LoadFunctionCall(ctx context.Context, turn, call string) (FunctionCall, bool, error)
	// ApplyFunctionResult records the application receipt of the call's
	// result.
	ApplyFunctionResult(ctx context.Context, turn, call string) error
	// ApplyFunctionTurnStatus moves the Turn from expected to status and
	// returns it as stored. A Turn no longer in expected is ErrTurnConflict.
	ApplyFunctionTurnStatus(ctx context.Context, turn, expected, status string) (Turn, error)
}

FunctionTx is one Turn's function calls inside a Session transaction on the execution lease.

type InitializationTx

type InitializationTx interface {
	EnvironmentFailureTx
	// LoadEnvironment reads the Session's Environment.
	LoadEnvironment(ctx context.Context) (Environment, error)
	// LoadSessionDevice reads the Runtime device bound to the Session and
	// reports whether the Session has one that still has authority.
	LoadSessionDevice(ctx context.Context) (ExecutionDevice, bool, error)
	// ClaimInitialization starts the pending preparation of the live
	// Environment and reports whether it did.
	ClaimInitialization(ctx context.Context, environment string) (bool, error)
	// CompleteInitialization completes the running preparation of the live
	// Environment and reports whether it did.
	CompleteInitialization(ctx context.Context, environment string) (bool, error)
	// FailInitialization marks the Environment's preparation failed unless it
	// completed.
	FailInitialization(ctx context.Context, environment string) error
}

InitializationTx is the Session transaction the Environment initialization operations run in.

type Input

type Input struct {
	Kind    string          `json:"kind"`
	Payload json.RawMessage `json:"payload"`
}

Input is a validated execution command, not an upstream wire type. The API validates event fields before constructing this storage input.

type InputActivityTx

type InputActivityTx interface {
	JournalTx
	// LoadEnvironmentInput reads the Session's latest Environment input
	// reservation that no Turn has admitted or superseded, nil when there is
	// none.
	LoadEnvironmentInput(ctx context.Context) (*EnvironmentInputState, error)
}

InputActivityTx is the Session transaction TrackInputActivity runs in.

type InputProjectionTx

type InputProjectionTx interface {
	ProjectionTx
	// LoadInputSource reads the Session's admitted input at sequence.
	LoadInputSource(ctx context.Context, sequence int64) (Source, error)
}

InputProjectionTx projects an admitted input.

type InputReceipt

type InputReceipt struct {
	Sequence int64
	TurnID   string // Empty for a cancellation accepted while the Session was idle.
	Replayed bool
}

type InputStartTx

type InputStartTx interface {
	FileWriteGateTx
	ActiveTurnTx
}

InputStartTx is the Session transaction CheckInputStart runs in.

type InstallationAuthorization

type InstallationAuthorization struct {
	Principal   identity.Principal `json:"principal"`
	Environment string             `json:"environment_id"`
	Version     string             `json:"version"`
	ExpiresAt   int64              `json:"expires_at"`
}

InstallationAuthorization permits claiming one Environment's connect-only key. The Environment UUID is reserved as that key's ID. Reissuing an authorization never rotates or revives the key, and a retry must prove the same local secret.

type IssuedExecutorCredential

type IssuedExecutorCredential struct {
	KeyID         string `json:"key_id"`
	EnvironmentID string `json:"environment_id,omitempty"`
	Token         string `json:"executor_token"`
}

type ItemDiagnosticTiming

type ItemDiagnosticTiming struct {
	ItemID      string
	StartedAt   time.Time
	CompletedAt *time.Time
}

ItemDiagnosticTiming records Core database receipt and settlement, never native execution duration. Historical terminal Items can have unknown settlement.

type ItemPage

type ItemPage struct {
	Items   []v1.Item
	HasMore bool
}

ItemPage is one page of a Session's root Items.

type ItemProjectionTx

type ItemProjectionTx interface {
	// LoadItem reads what the Session holds for update's Item in the Turn.
	LoadItem(ctx context.Context, turn string, update items.Update) (items.Stored, error)
	// PutItem stores a decided Item change of the Turn, first observed at
	// created, and returns the Item's output index, nil when it has none.
	PutItem(ctx context.Context, turn string, created time.Time, change items.Change) (*int32, error)
	// AppendChanges journals public changes in order.
	AppendChanges(ctx context.Context, changes ...SessionChange) error
}

ItemProjectionTx loads and stores the Session Items an observation projects, and journals their public changes.

type ItemReader

type ItemReader interface {
	// ListItems returns one page of the visible Session's root Items in
	// first-observation order, ascending or descending. A limit outside 1..100
	// is ErrInvalidInput. A cursor that is not an Item of the Session,
	// including a malformed one, is ErrItemCursor.
	ListItems(ctx context.Context, tenantID, sessionID, cursor string, limit int, ascending bool) (ItemPage, error)
}

ItemReader reads a Session's root Items.

type JournalBatch

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

JournalBatch is a validated batch of execution observations for a Turn's journal, each payload normalized. NewJournalBatch makes one.

func NewJournalBatch

func NewJournalBatch(turn string, first int32, events []ExecutionEvent) (JournalBatch, error)

NewJournalBatch validates an ordered batch of a Turn's execution observations that starts at journal position first. A malformed Turn ID is ErrInvalidInput before the batch is checked. Each observation needs a kind and a JSON object payload within the journal limits; a batch over the batch size limit is ErrEventLimit, and anything else invalid is ErrInvalidInput.

type JournalExecution

type JournalExecution interface {
	// WithTurnJournal runs apply in a Session transaction on the lease-bound
	// connection, with the tenant's Session locked, and passes apply the
	// transaction's context. A deleted Session still records its Turns'
	// observations.
	WithTurnJournal(ctx context.Context, tenant, session string, apply func(context.Context, TurnJournalTx) error) error
}

JournalExecution records execution observations in Turn journals.

type JournalTurn

type JournalTurn struct {
	Status     string
	EventCount int32
	EventBytes int64
}

JournalTurn is what decides whether a Turn's journal records a new batch: the Turn's status and what its journal holds.

type JournalTx

type JournalTx interface {
	// LoadUsage reads the Session's public usage as the transaction has left it.
	LoadUsage(ctx context.Context) (json.RawMessage, error)
	// AppendChanges journals public changes in order.
	AppendChanges(ctx context.Context, changes ...SessionChange) error
}

JournalTx reads the Session's public usage and journals its public changes.

type LockedSession

type LockedSession struct {
	// Deleted reports that the Session was publicly deleted. Its row stays so
	// that remaining execution can settle.
	Deleted bool
}

LockedSession is what locking a Session row shows.

func (LockedSession) Public

func (s LockedSession) Public() error

Public applies the public view of a locked Session: a deleted Session is ErrNotFound.

type ManagedArchive

type ManagedArchive struct {
	SessionID     string `json:"session_id"`
	EnvironmentID string `json:"environment_id"`
	State         string `json:"state"`
}

ManagedArchive reports resource disposal, not archive request provenance or Turn settlement. Existing expiry and failed provisioning use the same states.

type NativeSubagent

type NativeSubagent struct {
	ID              string
	Visible         bool
	NativeCreatedAt int64
	Status          string
	LifecycleAtMS   int64
}

NativeSubagent is what the Session holds for a native Subagent: its ID, whether it is public, when it was natively created (in seconds) and its lifecycle status as of LifecycleAtMS.

type Page

type Page struct {
	Sessions   []Session
	NextCursor string
}

type PendingFunctionCallsTx

type PendingFunctionCallsTx interface {
	// LoadPendingFunctionCalls reads the Turn's calls without an application
	// receipt, in creation order, while the Turn is in progress or waiting and
	// no cancellation was requested, and none otherwise.
	LoadPendingFunctionCalls(ctx context.Context, turn string) ([]FunctionCall, error)
}

PendingFunctionCallsTx reads a Turn's function calls that wait for a result or its application receipt.

type ProjectionTx

type ProjectionTx interface {
	ItemProjectionTx
	SubagentProjectionTx
	// PutTurnUsage replaces a root Turn's recorded usage with a measurement.
	PutTurnUsage(ctx context.Context, turn string, usage v1.TokenUsage) error
}

ProjectionTx loads and applies what projecting an observation reads and writes: Session Items, root Turn usage and Subagents.

type ProvisioningFailure

type ProvisioningFailure struct {
	Step     string
	Index    int
	ExitCode int
}

ProvisioningFailure identifies a confirmed failed initialization step. It cannot carry Runtime output: Step selects a fixed label, Index is the setup command position and ExitCode is the Runtime-reported status (0 when absent).

func (ProvisioningFailure) Detail

Detail is the private evidence recorded with the failure.

func (ProvisioningFailure) Reason

func (f ProvisioningFailure) Reason() string

Reason renders the public Session error. The setup_commands and Python package labels match observed official errors (which append raw pip output for Python; Core never does). The npm, file and Skill labels are unverified. A script step without a reported exit status keeps the generic reason.

type ProvisioningFailureDetail

type ProvisioningFailureDetail struct {
	Step     *string `json:"step"`
	Index    *int    `json:"index"`
	ExitCode *int    `json:"exit_code"`
}

ProvisioningFailureDetail is private, fixed-category evidence from a confirmed initialization receipt. It never contains command text, paths or Runtime output.

func SanitizedProvisioningDetail

func SanitizedProvisioningDetail(f ProvisioningFailureDetail) *ProvisioningFailureDetail

SanitizedProvisioningDetail keeps only the fields the step's category allows and returns nil for a missing or unknown step.

type Reader

Reader reads a Session's resources, Environment and devices, one family per line. Callers use it directly; no use case forwards a read.

type RuntimeEnrollment

type RuntimeEnrollment struct {
	DeviceID           string
	SessionID          string
	EnvironmentID      string
	WorkspaceDirectory string
}

RuntimeEnrollment is the resource binding an enrolled user-managed Runtime receives. It never carries another secret.

type Service

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

Service runs the pooled Session use cases: those that need no execution fencing, even when only execution calls them. Reads go through Reader.

func NewService

func NewService(storage Storage) (*Service, error)

NewService builds the Session use cases on storage.

func (*Service) AuthorizeEnvironmentInstallation

func (s *Service) AuthorizeEnvironmentInstallation(ctx context.Context, principal identity.Principal, environment, version string) (string, int64, error)

AuthorizeEnvironmentInstallation authorizes the installer of version to claim the connect-only key of the principal's self_hosted Environment, and returns the token and when it expires, in Unix seconds. The token is the base64url JSON authorization and its signature, joined by a dot. An archived Project gets none (projects.ErrArchived).

func (*Service) ClaimEnvironmentInstallation

func (s *Service) ClaimEnvironmentInstallation(ctx context.Context, token, version, secret string) error

ClaimEnvironmentInstallation stores only the digest of a secret the installer generated and persisted before this request. A lost response is safe to retry with the same secret; another machine, or a revoked or rotated key, cannot claim it again (ErrExecutorCredentialExists).

func (*Service) CreateDevice

func (s *Service) CreateDevice(ctx context.Context, tenant, name, credentialHash string) (ExecutionDevice, error)

CreateDevice provisions a device for an operator. It is not a tenant-facing registration API.

func (*Service) DeleteSessionArtifact

func (s *Service) DeleteSessionArtifact(ctx context.Context, command DeleteSessionArtifactCommand) error

DeleteSessionArtifact deletes the published copy and its content. The workspace file it was captured from stays, and reads admitted before the deletion finish.

func (*Service) EnrollRuntime

func (s *Service) EnrollRuntime(ctx context.Context, environment, credentialHash string) (RuntimeEnrollment, error)

EnrollRuntime binds a user-managed Runtime to one self_hosted Environment with the executor credential whose digest is credentialHash. A retry keeps the same device and key; it cannot replace compute or adopt another native history.

func (*Service) IssueExecutorCredential

func (s *Service) IssueExecutorCredential(ctx context.Context, principal identity.Principal, key, environment string) (IssuedExecutorCredential, error)

IssueExecutorCredential returns a new connect-only secret once, restricted to the Environment unless it is empty, without replacing an existing key: that is ErrExecutorCredentialExists. The principal's Project must be mapped to its tenant.

func (*Service) IssueProjectExecutorCredential

func (s *Service) IssueProjectExecutorCredential(ctx context.Context, project identity.Principal, environment, key string, rotate bool) (IssuedExecutorCredential, error)

IssueProjectExecutorCredential issues a new key restricted to the Environment or, with rotate, replaces the secret of an existing key restricted to it. The target is checked first, then the archived Project (projects.ErrArchived), then the key.

func (*Service) RevokeDevice

func (s *Service) RevokeDevice(ctx context.Context, tenant, device string) error

RevokeDevice revokes the tenant's device.

func (*Service) RevokeExecutorCredential

func (s *Service) RevokeExecutorCredential(ctx context.Context, principal identity.Principal, key string) error

RevokeExecutorCredential revokes the principal's key; revoking it again succeeds. An unknown key is ErrNotFound.

func (*Service) RevokeProjectExecutorCredential

func (s *Service) RevokeProjectExecutorCredential(ctx context.Context, project identity.Principal, environment, key string) error

RevokeProjectExecutorCredential revokes a key restricted to the Environment. Revoking it again succeeds, and so does revoking in an archived Project.

func (*Service) RotateExecutorCredential

func (s *Service) RotateExecutorCredential(ctx context.Context, principal identity.Principal, key string) (IssuedExecutorCredential, error)

RotateExecutorCredential returns a new secret for the principal's key once, keeping its restriction and restoring it if it was revoked. An unknown key is ErrNotFound.

func (*Service) StageTurnArtifacts

func (s *Service) StageTurnArtifacts(ctx context.Context, command StageTurnArtifactsCommand) error

StageTurnArtifacts stores a complete export as private Artifacts of the Turn, which the Turn's completion publishes or discards. It authorizes the Environment before reading the export or allocating storage, and takes the Session lock only after the transfer, so the export never holds admission. Under the lock the Turn must still be in progress without a cancellation request, or the export is ErrTurnConflict. A rejected export stores nothing.

func (*Service) TouchAgentDaemonHeartbeat

func (s *Service) TouchAgentDaemonHeartbeat(ctx context.Context, heartbeat runtimedevice.Heartbeat) (runtimedevice.HeartbeatStatus, error)

TouchAgentDaemonHeartbeat records an agent daemon heartbeat under the credential the gateway authenticated. A credential that lost its authority reports Deleted.

func (*Service) TouchRuntimeHeartbeat

func (s *Service) TouchRuntimeHeartbeat(ctx context.Context, device string) (runtimedevice.HeartbeatStatus, error)

TouchRuntimeHeartbeat records a Runtime connection. A device that lost its authority reports Deleted.

func (*Service) ValidateEnvironmentInstallation

func (s *Service) ValidateEnvironmentInstallation(ctx context.Context, token, version string) (InstallationAuthorization, error)

ValidateEnvironmentInstallation returns the authorization the token carries while it is signed, unexpired, for version, and still names a self_hosted Environment of an active Project. Any other token is ErrInstallationAuthorization.

type Session

type Session struct {
	ID                       string
	TenantID                 string
	Creator                  *identity.Subject
	Engine                   string
	Metadata                 map[string]string
	CreatedAt                time.Time
	Configuration            json.RawMessage
	LastTurn                 *Turn
	Usage                    json.RawMessage
	RequiredActions          []v1.FunctionCallAction
	Environment              *Environment
	EnvironmentInputActivity *EnvironmentInputActivity
	// EnvironmentFailure is the recorded provisioning failure of a failed hosted
	// Environment. It makes the Session failed and is terminal.
	EnvironmentFailure *EnvironmentFailure
	// PendingInput reports that the latest input reservation, read once no Turn
	// is active or newer, can still start a Turn. It only supports settlement
	// checks and is never rendered.
	PendingInput bool
}

Session is a durable execution context, separate from product conversations and from live daemon connections. Engine session IDs will be bound at execution.

type SessionChange

type SessionChange struct {
	Sequence                 int64                     `json:"-"`
	Event                    v1.SessionEvent           `json:"event"`
	Turn                     *Turn                     `json:"turn,omitempty"`
	SessionUsage             json.RawMessage           `json:"session_usage,omitempty"`
	RequiredActions          []v1.FunctionCallAction   `json:"required_actions,omitempty"`
	EnvironmentInputActivity *EnvironmentInputActivity `json:"environment_input_activity,omitempty"`
	// EnvironmentFailure is set on the agent.session.failed snapshot of a hosted
	// provisioning failure, which also ends live event streams.
	EnvironmentFailure *EnvironmentFailure `json:"environment_failure,omitempty"`
	// Settled marks an idle or failed snapshot recorded when a Turn ends, or when
	// the latest input reservation stops being pending (expired, cancelled or
	// failed). A reservation made while the ending Turn captured Artifacts can
	// still be pending and start a later Turn. It is internal, never a wire
	// field; snapshots recorded without it read as unsettled.
	Settled bool `json:"settled,omitempty"`
}

SessionChange keeps transition snapshots separate from public response rendering.

func ActivityChange

func ActivityChange(turn Turn, usage json.RawMessage, actions []v1.FunctionCallAction) SessionChange

ActivityChange returns the Session activity snapshot after a Turn change: requires_action while the Turn waits on actions, idle once it ended, failed when it failed, and in_progress otherwise. usage is the Session's public usage. The snapshot of a Turn that ended is settled: it marks that Turn's end, while an input reserved during its Artifact capture is newer work.

func EnvironmentStateChange

func EnvironmentStateChange(environment, kind, status string) SessionChange

EnvironmentStateChange is the pinned agent.session.environment.<status> event for an Environment status the transaction has written. A failure carries the observed official connection error; the failed step travels only in the separate error event and the Session's error.

func ItemChanges

func ItemChanges(change items.Change, outputIndex *int32) []SessionChange

ItemChanges returns the public changes that report an Item change, in publication order. outputIndex is the Item's output index, nil when it has none.

func TurnChanges

func TurnChanges(turn Turn, created bool) []SessionChange

TurnChanges returns the public change that reports a Turn's new status: agent.session.turn.created for a newly admitted Turn and agent.session.turn.<status> otherwise. A waiting Turn reports nothing; its Session activity carries the required actions. EndTurn reports a Turn that ended together with what it settles.

type Source

type Source struct {
	Turn string
	Kind string
	// Sequence is the entry's journal position or the input's sequence; a
	// terminal outcome projected without an entry has none.
	Sequence  int64
	Payload   json.RawMessage
	CreatedAt time.Time
}

Source is an observation the Session projects: an entry of a Turn's journal, an admitted input message, or a Turn's terminal outcome.

type StageTurnArtifactsCommand

type StageTurnArtifactsCommand struct {
	TenantID      string
	SessionID     string
	TurnID        string
	EnvironmentID string
	// Export is a tar archive of regular files under outputs/, followed by
	// nothing but zero padding until the transport ends.
	Export io.Reader
}

StageTurnArtifactsCommand stages what a completed Turn exported from its Session's Environment.

type Storage

Storage persists the pooled Session use cases, one family per line.

type StoredChildItem

type StoredChildItem struct {
	Turn     string
	Position int32
	Payload  json.RawMessage
	Same     bool
}

StoredChildItem is what the Session holds for a Subagent Item: its Turn, position and stored payload, and whether that payload equals the candidate it was loaded with.

type SubagentIdentity

type SubagentIdentity struct {
	NativeID, ParentNativeID string
	NativeCreatedAt          int64
	FirstTurn                string
	FirstOrdinal             int32
}

SubagentIdentity binds a native Subagent to the Session at the journal entry that first observed it. It is an execution binding, not a public Subagent.

type SubagentLifecycle

type SubagentLifecycle struct {
	Status     string
	ClosedAtMS *int64
	AtMS       int64
}

SubagentLifecycle is a Subagent's lifecycle status as of AtMS, and when it closed.

type SubagentProjectionTx

type SubagentProjectionTx interface {
	// LoadRootAgent reads the Session's Agent ID.
	LoadRootAgent(ctx context.Context) (string, error)
	// LoadNativeSubagent reads the Session's native Subagent and reports whether
	// the Session has it.
	LoadNativeSubagent(ctx context.Context, native string) (NativeSubagent, bool, error)
	// PutSubagentIdentity binds a native Subagent to the Session, or finds the
	// same binding, and returns its ID. A different binding of the native ID,
	// or a parent the Session does not know, is ErrIdempotencyConflict.
	PutSubagentIdentity(ctx context.Context, identity SubagentIdentity) (string, error)
	// PublishSubagent makes a Subagent public with its identity metadata.
	PublishSubagent(ctx context.Context, id string, name, instructions *string) error
	// LoadPublicSubagent reads a public Subagent of the Session.
	LoadPublicSubagent(ctx context.Context, id string) (v1.Subagent, error)
	// PutSubagentEffect records a native lifecycle effect once and reports
	// whether this call recorded it. Another payload under the same effect ID
	// is ErrIdempotencyConflict.
	PutSubagentEffect(ctx context.Context, effect string, payload json.RawMessage) (bool, error)
	// ApplySubagentLifecycle records a Subagent's lifecycle status.
	ApplySubagentLifecycle(ctx context.Context, id string, lifecycle SubagentLifecycle) error
	// LoadChildTurn reads a Turn of the Subagent and reports whether the
	// Subagent has it.
	LoadChildTurn(ctx context.Context, subagent, id string) (ChildTurn, bool, error)
	// PutChildTurn stores a Subagent Turn. A Turn whose identity differs from
	// the stored one is ErrIdempotencyConflict.
	PutChildTurn(ctx context.Context, turn ChildTurn) error
	// RecordTerminalActivity marks the Session's running managed compute
	// active.
	RecordTerminalActivity(ctx context.Context) error
	// LoadChildItem reads an Item of the Subagent, compares its payload with
	// candidate, and reports whether the Subagent has it.
	LoadChildItem(ctx context.Context, subagent, id string, candidate json.RawMessage) (StoredChildItem, bool, error)
	// PutChildItem stores a Subagent Item.
	PutChildItem(ctx context.Context, item ChildItem) error
}

SubagentProjectionTx loads and applies what projecting Subagent observations reads and writes.

type SubagentReader

type SubagentReader interface {
	// GetSubagent returns one Subagent of the Session, including a nested or
	// closed one.
	GetSubagent(ctx context.Context, tenantID, sessionID, subagentID string) (v1.Subagent, error)
	// ListSubagents returns one page of the Session's Subagents in opening
	// order.
	ListSubagents(ctx context.Context, tenantID, sessionID, cursor string, limit int, ascending bool) (v1.SubagentList, error)
	// ListSubagentItems returns one page of the Subagent's Items.
	ListSubagentItems(ctx context.Context, tenantID, sessionID, subagentID, cursor string, limit int, ascending bool) (v1.ItemList, error)
	// GetSubagentTurn returns one of the Subagent's Turns. Its agent_id is the
	// Session's Agent ID and its subagent_id names the child.
	GetSubagentTurn(ctx context.Context, tenantID, sessionID, subagentID, turnID string) (v1.Turn, error)
	// ListSubagentTurns returns one page of the Subagent's Turns in creation
	// order.
	ListSubagentTurns(ctx context.Context, tenantID, sessionID, subagentID, cursor string, limit int, ascending bool) (v1.TurnList, error)
	// ListSubagentTurnItems returns one page of the Items of one of the
	// Subagent's Turns. An empty Turn ID is ErrInvalidInput.
	ListSubagentTurnItems(ctx context.Context, tenantID, sessionID, subagentID, turnID, cursor string, limit int, ascending bool) (v1.ItemList, error)
}

SubagentReader reads the Subagents a visible Session observed, with their Turns and Items. A Subagent, Turn or Item outside the named Session or Subagent is ErrNotFound. A list limit outside 1..100 is ErrInvalidInput. A Subagent or Subagent Turn cursor outside its list, including a malformed one, is ErrResourceCursor; an Item cursor is ErrItemCursor.

type Turn

type Turn struct {
	ID, SessionID, Status string
	CreatedAt             time.Time
	StartedAt             time.Time
	CompletedAt           time.Time
	CancelRequestedAt     time.Time
	Usage                 json.RawMessage
	Outcome               json.RawMessage
	// ArtifactCaptureStarted is private Runtime coordination, never a wire field.
	ArtifactCaptureStarted bool `json:"-"`
}

Turn is a root Turn from the Core work queue and uses its Session's immutable execution configuration; Subagent Turns have a native writer and their own table. Zero timestamps mean the corresponding event has not occurred. Outcome is adapter-owned data, not an upstream response; the API must project supported wire types explicitly.

func AdmitFunctionResult

func AdmitFunctionResult(ctx context.Context, tx FunctionResultTx, input FunctionResultInput) (Turn, error)

AdmitFunctionResult saves a submitted function result for its Turn's call and returns that Turn, which the result's input joins. It never creates a Turn. A result whose Turn does not have the call is ErrFunctionCallTurnMismatch when another Turn of the Session has it and ErrUnknownFunctionCall otherwise; the answer depends only on the Session's own calls.

type TurnCancellationTx

type TurnCancellationTx interface {
	JournalTx
	// RequestTurnCancel records a cancellation request on an active Turn of
	// the Session. A queued Turn becomes cancelled; the database clock stamps
	// the request and the end.
	RequestTurnCancel(ctx context.Context, turn string) error
	// LoadTurn reads one of the Session's Turns.
	LoadTurn(ctx context.Context, turn string) (Turn, error)
	// LoadEnding reads the facts EndTurn settles an ended Turn with.
	LoadEnding(ctx context.Context, turn string) (Ending, error)
	// ApplyTurnEnd writes what EndTurn decided for an ended Turn.
	ApplyTurnEnd(ctx context.Context, turn string, end TurnEnd) error
}

TurnCancellationTx is the Session transaction CancelTurn runs in.

type TurnDiagnosticsSnapshot

type TurnDiagnosticsSnapshot struct {
	Session        Session
	Turn           Turn
	Items          []ItemDiagnosticTiming
	ItemsTruncated bool
}

type TurnEnd

type TurnEnd struct {
	// TerminalActivity marks managed compute activity when Core commits the
	// end, so managed idle time starts then and never on a Runtime clock.
	TerminalActivity bool
	Artifacts        ArtifactSettlement
	// PublishedAt is the publication time of PublishArtifacts.
	PublishedAt time.Time
	// FinishedItems are the IDs of the Turn's unfinished Items. Each takes
	// FinishedStatus, and all of them share one settlement time.
	FinishedItems  []string
	FinishedStatus string
	// Changes are the public changes: each finished Item's events in Session
	// position order, the Turn's event, then the Session's settled activity.
	Changes []SessionChange
}

TurnEnd is what a Turn that ended writes in the transaction that ends it, applied in field order.

func EndTurn

func EndTurn(turn Turn, ending Ending) TurnEnd

EndTurn decides what a Turn that ended settles. A completed Turn publishes its Artifacts and a failed or cancelled one discards them. Its unfinished Items become incomplete, keeping their partial content, so none is reported as a success the Turn never produced.

type TurnEvent

type TurnEvent struct {
	Ordinal   int32
	Kind      string
	Payload   json.RawMessage
	CreatedAt time.Time
}

type TurnEventTx

type TurnEventTx interface {
	EventProjectionTx
	// InsertEvent records event at the Turn's journal position ordinal.
	InsertEvent(ctx context.Context, turn string, ordinal int32, event ExecutionEvent) error
}

TurnEventTx records one entry in a Turn's journal and projects it.

type TurnInput

type TurnInput struct {
	Sequence  int64
	Kind      string
	Payload   json.RawMessage
	CreatedAt time.Time
}

type TurnJournalTx

type TurnJournalTx interface {
	EventProjectionTx
	// LoadJournalTurn reads the tenant's Turn in the Session and reports whether
	// it exists.
	LoadJournalTurn(ctx context.Context, turn string) (JournalTurn, bool, error)
	// MatchEvents reports whether the Turn's journal holds exactly events from
	// position first.
	MatchEvents(ctx context.Context, turn string, first int32, events []ExecutionEvent) (bool, error)
	// InsertEvents records events at the Turn's journal positions from first.
	InsertEvents(ctx context.Context, turn string, first int32, events []ExecutionEvent) error
}

TurnJournalTx records a batch in a Turn's journal and projects it.

type TurnPage

type TurnPage struct {
	Turns      []Turn
	NextCursor string
}

type TurnTransition

type TurnTransition struct {
	ExpectedStatus string
	Status         string
	Outcome        json.RawMessage
}

type UnfinishedItem

type UnfinishedItem struct {
	// Position is the Item's Session position.
	Position int32
	// OutputIndex is the Item's output index, nil when it has none.
	OutputIndex *int32
	Item        v1.Item
}

UnfinishedItem is an Item still in progress when its Turn ends.

Jump to

Keyboard shortcuts

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