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 an input batch, moving a Turn's status, 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 moving and completing Turns, recording function calls and their application receipts and journaling a Turn's observations, over the lease-bound ExecutionStorage.
Index ¶
- Constants
- Variables
- func AppendTurnEvent(ctx context.Context, tx TurnEventTx, turn string, last int32, ...) error
- func AppendTurnEvents(ctx context.Context, tx TurnJournalTx, batch JournalBatch) error
- func CancelTurn(ctx context.Context, tx TurnCancellationTx, turn Turn) error
- func CancelWork(ctx context.Context, tx CancellationTx) error
- func CheckComputeAdmission(ctx context.Context, tx ComputeAdmissionTx) error
- func CheckFileWriteGate(ctx context.Context, tx FileWriteGateTx) error
- func CheckInputStart(ctx context.Context, tx InputStartTx) error
- func CreateEnvironmentDevice(ctx context.Context, tx EnvironmentDeviceTx, device ExecutionDevice, ...) error
- func EnvironmentType(configuration json.RawMessage) (string, error)
- func ExecutionModel(configuration []byte) (*string, error)
- func FailEnvironment(ctx context.Context, tx EnvironmentFailureTx, environment Environment, ...) error
- func LoadRequiredActions(ctx context.Context, tx PendingFunctionCallsTx, turn Turn) ([]v1.FunctionCallAction, error)
- func MeasuredUsage(kind string, raw json.RawMessage) *v1.TokenUsage
- func NormalizeExecutionProjection(projection *v1.SessionExecutionConfiguration, sessionID string)
- func ProjectInput(ctx context.Context, tx InputProjectionTx, sequence int64) error
- func ProjectSource(ctx context.Context, tx ProjectionTx, source Source) error
- func TerminalStatus(status string) bool
- func TerminateEnvironment(ctx context.Context, tx EnvironmentTerminationTx, computeExpired bool, ...) error
- func TrackInputActivity(ctx context.Context, tx InputActivityTx, apply func(context.Context) error) error
- func ValidEngine(engine string) bool
- func ValidTransition(from, to string) bool
- func ValidateInputKey(key string) error
- func ValidateRetainedHistory(required, supported bool) error
- type ActiveTurnTx
- type AdminAssetCounts
- type AdminReader
- type AdminRuntimeTarget
- type AdminRuntimeTargetPage
- type AdminSummaryFilter
- type Artifact
- type ArtifactPage
- type ArtifactReader
- type ArtifactSettlement
- type ArtifactStagingKey
- type ArtifactStagingTx
- type ArtifactStorage
- type AuditSessionOperationCommand
- type CancellationTx
- type ChildItem
- type ChildTurn
- type ComputeAdmissionTx
- type ConnectionTx
- type CreateSession
- type Creation
- type CreationRecord
- type CreationStorage
- type CreationTx
- type CursorError
- type DeleteSessionArtifactCommand
- type DeleteSessionCommand
- type DeviceBindingTx
- type DeviceReader
- type DeviceRegistration
- type DeviceStorage
- type Ending
- type EnrolledRuntimeBinding
- type EnrollmentAuthority
- type EnrollmentTx
- type Environment
- type EnvironmentConnection
- type EnvironmentDeviceTx
- type EnvironmentExecution
- type EnvironmentExecutorCredentialTx
- type EnvironmentFailure
- type EnvironmentFailureTx
- type EnvironmentFileWrite
- type EnvironmentInitialization
- type EnvironmentInputActivity
- type EnvironmentInputReservation
- type EnvironmentInputState
- type EnvironmentInputWork
- type EnvironmentKey
- type EnvironmentReader
- type EnvironmentTerminationTx
- type EventProjectionTx
- type ExecutionBinding
- type ExecutionDevice
- type ExecutionEvent
- type ExecutionOperations
- func (o *ExecutionOperations) AppendTurnEvents(ctx context.Context, tenant, session, turn string, first int32, ...) error
- func (o *ExecutionOperations) BeginTurnArtifactCapture(ctx context.Context, tenant, session, turn string, appliedThrough int64) error
- func (o *ExecutionOperations) BindSessionDevice(ctx context.Context, tenant, session, device string) error
- func (o *ExecutionOperations) ClaimEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization) error
- func (o *ExecutionOperations) CompleteEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization) error
- func (o *ExecutionOperations) CompleteExecution(ctx context.Context, tenant, session, turn, status string, ...) (Turn, error)
- func (o *ExecutionOperations) ConfirmFunctionResult(ctx context.Context, tenant, session, turn, call string) error
- func (o *ExecutionOperations) ExpireEnvironmentInputs(ctx context.Context) (int64, error)
- func (o *ExecutionOperations) FailEnvironmentInitialization(ctx context.Context, owner EnvironmentInitialization, ...) error
- func (o *ExecutionOperations) FailEnvironmentInput(ctx context.Context, tenant, session, reservation, code string) error
- func (o *ExecutionOperations) ObserveEnvironmentConnection(ctx context.Context, tenant, environment, generation string, revision int64, ...) error
- func (o *ExecutionOperations) PendingFunctionCalls(ctx context.Context, tenant, session, turn string) ([]FunctionCall, error)
- func (o *ExecutionOperations) PromoteEnvironmentInput(ctx context.Context, tenant, session, reservation string) (EnvironmentInputReservation, error)
- func (o *ExecutionOperations) ReconcileEnvironmentConnections(ctx context.Context) error
- func (o *ExecutionOperations) RecordFunctionCall(ctx context.Context, tenant, session, turn string, call FunctionCall) error
- func (o *ExecutionOperations) ReplaceEnvironmentConnection(ctx context.Context, tenant, environment, generation string) error
- func (o *ExecutionOperations) ReserveEnvironmentFileWrite(ctx context.Context, tenant, environment string, key FileWriteIdentity) (EnvironmentFileWrite, error)
- func (o *ExecutionOperations) SettleEnvironmentFileWrite(ctx context.Context, tenant, environment string, key FileWriteIdentity, ...) (EnvironmentFileWrite, error)
- func (o *ExecutionOperations) TransitionTurn(ctx context.Context, tenant, session, turn string, transition TurnTransition) (Turn, error)
- type ExecutionStorage
- type ExecutionWork
- type ExecutorConnectionState
- type ExecutorCredential
- type ExecutorCredentialGrant
- type ExecutorCredentialReader
- type ExecutorCredentialState
- type ExecutorCredentialStorage
- type ExecutorCredentialTx
- type FileWriteGateTx
- type FileWriteIdentity
- type FileWriteReservationTx
- type FileWriteSettlementTx
- type FileWriteTx
- type FunctionCall
- type FunctionCallMatch
- type FunctionExecution
- type FunctionResultInput
- type FunctionResultMatch
- type FunctionResultTx
- type FunctionTx
- type InitializationTx
- type Input
- type InputActivityTx
- type InputAdmissionTx
- type InputExecution
- type InputGate
- type InputProjectionTx
- type InputReader
- type InputReceipt
- type InputStartTx
- type InputStorage
- type InputTx
- type InstallationAuthorization
- type IssuedExecutorCredential
- type ItemDiagnosticTiming
- type ItemPage
- type ItemProjectionTx
- type ItemReader
- type JournalBatch
- type JournalTurn
- type JournalTx
- type LockedSession
- type ManagedArchive
- type ManagedArchiveState
- type ModelExecutionReader
- type NativeSubagent
- type NewSession
- type Page
- type PendingFunctionCallsTx
- type ProjectionTx
- type ProvisioningFailure
- type ProvisioningFailureDetail
- type Reader
- type RuntimeEnrollment
- type Service
- func (s *Service) AuditSessionOperation(ctx context.Context, command AuditSessionOperationCommand) error
- func (s *Service) AuthorizeEnvironmentInstallation(ctx context.Context, principal identity.Principal, environment, version string) (string, int64, error)
- func (s *Service) ClaimEnvironmentInstallation(ctx context.Context, token, version, secret string) error
- func (s *Service) CreateDevice(ctx context.Context, tenant, name, credentialHash string) (ExecutionDevice, error)
- func (s *Service) CreateSession(ctx context.Context, tenant string, input CreateSession) (Creation, error)
- func (s *Service) DeleteSession(ctx context.Context, command DeleteSessionCommand) error
- func (s *Service) DeleteSessionArtifact(ctx context.Context, command DeleteSessionArtifactCommand) error
- func (s *Service) EnrollRuntime(ctx context.Context, environment, credentialHash string) (RuntimeEnrollment, error)
- func (s *Service) ExpireEnvironmentInput(ctx context.Context, tenant, session, reservation string) (EnvironmentInputReservation, error)
- func (s *Service) FindSessionCreation(ctx context.Context, tenant, key string, request json.RawMessage, ...) (Creation, error)
- func (s *Service) IssueExecutorCredential(ctx context.Context, principal identity.Principal, key, environment string) (IssuedExecutorCredential, error)
- func (s *Service) IssueProjectExecutorCredential(ctx context.Context, project identity.Principal, environment, key string, ...) (IssuedExecutorCredential, error)
- func (s *Service) ReserveEnvironmentInput(ctx context.Context, tenant, session, key string, inputs []Input) (EnvironmentInputReservation, error)
- func (s *Service) RevokeDevice(ctx context.Context, tenant, device string) error
- func (s *Service) RevokeExecutorCredential(ctx context.Context, principal identity.Principal, key string) error
- func (s *Service) RevokeProjectExecutorCredential(ctx context.Context, project identity.Principal, environment, key string) error
- func (s *Service) RotateExecutorCredential(ctx context.Context, principal identity.Principal, key string) (IssuedExecutorCredential, error)
- func (s *Service) StageTurnArtifacts(ctx context.Context, command StageTurnArtifactsCommand) error
- func (s *Service) SubmitInputs(ctx context.Context, tenant, session, key string, inputs []Input) ([]InputReceipt, error)
- func (s *Service) TouchAgentDaemonHeartbeat(ctx context.Context, heartbeat runtimedevice.Heartbeat) (runtimedevice.HeartbeatStatus, error)
- func (s *Service) TouchRuntimeHeartbeat(ctx context.Context, device string) (runtimedevice.HeartbeatStatus, error)
- func (s *Service) UpdateSessionMetadata(ctx context.Context, command UpdateSessionMetadataCommand) (Session, error)
- func (s *Service) ValidateEnvironmentInstallation(ctx context.Context, token, version string) (InstallationAuthorization, error)
- type Session
- type SessionChange
- func ActivityChange(turn Turn, usage json.RawMessage, actions []v1.FunctionCallAction) SessionChange
- func EnvironmentStateChange(environment, kind, status string) SessionChange
- func ItemChanges(change items.Change, outputIndex *int32) []SessionChange
- func TurnChanges(turn Turn, created bool) []SessionChange
- type SessionDeletionTx
- type SessionReader
- type SessionStorage
- type Source
- type StageTurnArtifactsCommand
- type Storage
- type StoredChildItem
- type SubagentIdentity
- type SubagentLifecycle
- type SubagentProjectionTx
- type SubagentReader
- type Turn
- type TurnCancellationTx
- type TurnDiagnosticsSnapshot
- type TurnEnd
- type TurnEvent
- type TurnEventTx
- type TurnExecution
- type TurnInput
- type TurnJournalTx
- type TurnPage
- type TurnReader
- type TurnStatusChange
- type TurnTransition
- type TurnTransitionTx
- type TurnTx
- type UnfinishedItem
- type UpdateSessionMetadataCommand
Constants ¶
const ( EnvironmentInputPending = "pending" EnvironmentInputAdmitted = "admitted" EnvironmentInputExpired = "expired" EnvironmentInputCancelled = "cancelled" EnvironmentInputFailed = "failed" )
const ( ProvisioningSetupCommand = "setup" ProvisioningPythonPackages = "python" ProvisioningNPMPackages = "npm" ProvisioningInitialFile = "file" ProvisioningSkill = "skill" ProvisioningHarness = "harness" )
Provisioning step kinds for ProvisioningFailure.Step.
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.
const ( TurnQueued = "queued" TurnInProgress = "in_progress" TurnWaiting = "waiting" TurnCompleted = "completed" TurnFailed = "failed" TurnCancelled = "cancelled" )
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 ¶
var ( ErrInvalidInput = errors.New("invalid session input") ErrNotFound = errors.New("session not found") ErrIdempotencyConflict = errors.New("idempotency key was already used with different input") )
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).
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.
var ErrDeviceBindingConflict = errors.New("session is already bound to a different device")
var ErrEventLimit = errors.New("execution event storage limit exceeded")
var ErrExecutorCredentialExists = errors.New("executor key ID already exists; rotate explicitly")
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).
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.
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.
var ErrInstallationAuthorization = errors.New("installation authorization is invalid or expired; obtain a new command from the Session")
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.
var ErrStreamGap = errors.New("live event buffer exceeded; recover through Session and Items reads")
var ErrTurnConflict = errors.New("turn state changed or cancellation was requested")
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 EnvironmentType ¶
func EnvironmentType(configuration json.RawMessage) (string, error)
EnvironmentType returns the type an Environment configuration snapshot names: self_hosted or openai_hosted.
func ExecutionModel ¶ added in v0.0.10
ExecutionModel returns the model a stored Session configuration selects, nil when it selects none.
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 NormalizeExecutionProjection ¶ added in v0.0.10
func NormalizeExecutionProjection(projection *v1.SessionExecutionConfiguration, sessionID string)
NormalizeExecutionProjection completes a Session's frozen execution configuration for sessionID as it is stored and read: the object and schema version, an unknown harness configuration source, the resolved harness configuration, and the provider view only while it is available. A deployment provider frozen without its safe view stays redacted.
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 ¶
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 ValidTransition ¶
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 ¶
ValidateInputKey enforces the shared request identity limit, including no-op requests.
func ValidateRetainedHistory ¶ added in v0.0.10
ValidateRetainedHistory checks the selected external filesystem and Harness combination.
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 AdminAssetCounts ¶ added in v0.0.10
type AdminAssetCounts struct {
Agents int64 `json:"agents" binding:"required"`
Skills int64 `json:"skills" binding:"required"`
EnvironmentTemplates int64 `json:"environment_templates" binding:"required"`
Files int64 `json:"files" binding:"required"`
Vaults int64 `json:"vaults" binding:"required"`
Credentials int64 `json:"credentials" binding:"required"`
}
AdminAssetCounts counts a tenant's assets.
type AdminReader ¶ added in v0.0.10
type AdminReader interface {
// ListAdminRuntimeTargets pages the live Sessions of the tenants by
// creation time, then ID, ascending or descending, after the Session
// after. A limit outside 1 to 100 or a malformed tenant is
// ErrInvalidInput; an after Session that is malformed, deleted or
// outside the tenants is ErrNotFound.
ListAdminRuntimeTargets(ctx context.Context, tenants []string, after string, limit int, ascending bool) (AdminRuntimeTargetPage, error)
// ReadAdminSummary counts the tenant's assets and visits each live Session
// the filter selects, with GetSession's activity and the ID of the key that
// created it, nil when none is recorded, from one read-only snapshot. A
// malformed tenant is ErrInvalidInput; an error from visit ends the read.
ReadAdminSummary(ctx context.Context, tenant string, filter AdminSummaryFilter, visit func(Session, *string) error) (AdminAssetCounts, error)
}
AdminReader reads the administrator's cross-Project Session views.
type AdminRuntimeTarget ¶ added in v0.0.10
type AdminRuntimeTarget struct{ SessionID, TenantID string }
AdminRuntimeTarget names a live Session whose Runtime an administrator observes, with its tenant.
type AdminRuntimeTargetPage ¶ added in v0.0.10
type AdminRuntimeTargetPage struct {
Data []AdminRuntimeTarget
HasMore bool
}
AdminRuntimeTargetPage is one page of AdminRuntimeTargets.
type AdminSummaryFilter ¶ added in v0.0.10
AdminSummaryFilter selects the Sessions created in [CreatedAfter, CreatedBefore); a nil bound is open.
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 ¶
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 AuditSessionOperationCommand ¶ added in v0.0.10
type AuditSessionOperationCommand struct {
TenantID string
SessionID string
// Action is create or send_events.
Action string
}
AuditSessionOperationCommand records an authorized public operation that changes no Session: a no-op or a creation replay.
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 {
// SupportsRetainedNativeHistory is trusted admission input from the immutable engine profile.
// It is not persisted and never contributes to the caller's retry identity.
SupportsRetainedNativeHistory bool `json:"-"`
// DeploymentProviderRevision is private creation metadata, never retry identity.
DeploymentProviderRevision uuid.UUID `json:"-"`
ExecutionConfiguration *v1.SessionExecutionConfiguration
ModelProvider *v1.ModelProviderInput
ModelProviderSource v1.ExecutionSource // 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 ¶
Creation starts observation at the Session upsert. Session is the Session projection the creation transaction read last, after any initial input; Cursor is the event sequence the upsert returned, before that input, so its events remain observable exactly once. Only a new creation emits a created snapshot and streams from Cursor; a stream retry of an existing creation sends no events. FindSessionCreation returns only the Session ID.
type CreationRecord ¶ added in v0.0.10
type CreationRecord struct {
SessionID string
Deleted bool
// Creator is nil when the Session records no complete creator.
Creator *identity.Subject
// IntentHash is nil when the creation recorded no caller intent.
IntentHash *string
}
CreationRecord is what a retry identity lookup compares.
type CreationStorage ¶ added in v0.0.10
type CreationStorage interface {
// FingerprintProviderKey returns the keyed fingerprint of a model
// provider key, so retry identities tell keys apart without hashing a key.
FingerprintProviderKey(secret string) (string, error)
// WithCreation runs apply in one pooled transaction and commits only when
// apply returns nil. A malformed tenant is ErrInvalidInput.
WithCreation(ctx context.Context, tenant string, apply func(context.Context, CreationTx) error) error
// FindCreation reads the tenant's Session created under key, deleted or
// not, or ErrNotFound. A malformed tenant is ErrInvalidInput.
FindCreation(ctx context.Context, tenant, key string) (CreationRecord, error)
}
CreationStorage persists Session creation and finds an earlier one.
type CreationTx ¶ added in v0.0.10
type CreationTx interface {
InputAdmissionTx
InputActivityTx
// UpsertSession inserts the Session or, under the tenant and key, returns
// the stored one with Created false when its creator and identity match:
// the intent hash when the stored Session has one, else the request hash.
// A deleted or mismatched one is ErrIdempotencyConflict. Cursor is the
// Session's event sequence before anything the transaction admits.
UpsertSession(ctx context.Context, session NewSession) (Creation, error)
// LockDeployment locks and reads the sandbox deployment, serializing
// hosted creation with deployment changes, restore and node removal.
LockDeployment(ctx context.Context) (placement.Deployment, error)
// LockSkills locks the tenant's Skills in ID order, whatever the order of
// ids, and returns them by ID. A missing one is ErrNotFound.
LockSkills(ctx context.Context, ids []string) (map[string]skills.Skill, error)
// ReadSkillVersion opens and verifies a version of a locked Skill. A
// missing one is ErrNotFound; one that does not open or verify is an
// internal error.
ReadSkillVersion(ctx context.Context, skill string, version int64) (skills.Content, error)
// SaveModelExecution seals the Session's model provider bundle.
SaveModelExecution(ctx context.Context, provider v1.ModelProviderInput) error
// SaveExecutionConfiguration records the frozen execution projection and,
// unless it is uuid.Nil, the deployment provider revision it resolved.
SaveExecutionConfiguration(ctx context.Context, projection v1.SessionExecutionConfiguration, revision uuid.UUID) error
// SaveInitialFiles copies the validated initial files, a file_id one from
// its locked source File, seals them under the Session and records their
// metadata in its configuration. A missing source is ErrNotFound and one
// beyond environmentconfig.MaxInitialFileBytes ErrInvalidInput.
SaveInitialFiles(ctx context.Context, files []environmentconfig.InitialFile) error
// SaveSetup seals the installed setup under the Session and records its
// metadata in its configuration.
SaveSetup(ctx context.Context, setup environmentconfig.Setup) error
// CreateEnvironment creates the Session's Environment, pending
// preparation when the Session froze a setup or initial files, and
// returns its ID.
CreateEnvironment(ctx context.Context) (string, error)
// CreateInputReservation reserves the batch under key until the deadline
// the database clock sets, marked as the Session's initial input.
CreateInputReservation(ctx context.Context, key string, batch json.RawMessage, initial bool) (EnvironmentInputReservation, error)
// PruneChanges bounds the Session's retained public changes.
PruneChanges(ctx context.Context) error
// AuditCreation records the create write audit, listing created.
AuditCreation(ctx context.Context, created ...writeaudit.Resource) error
// LoadSession reads the Session with its Environment and activity as the
// transaction has left it.
LoadSession(ctx context.Context) (Session, error)
}
CreationTx is the Session creation transaction. UpsertSession binds it to the stored Session, which every later method acts on.
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 ¶
DeleteSessionArtifactCommand deletes one published Artifact.
type DeleteSessionCommand ¶ added in v0.0.10
DeleteSessionCommand deletes one Session.
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)
// ArchivedCancellationReceipt reads the receipt window that archiving a
// Session leaves the device's exact authenticated delivery of one of
// runIDs; without one it is the zero receipt.
ArchivedCancellationReceipt(ctx context.Context, device, credentialHash string, runIDs []string) (runtimedevice.ArchivedCancellationReceipt, error)
// ListEnrolledRuntimeBindings lists the enrolled user-managed Runtimes of
// live Environments.
ListEnrolledRuntimeBindings(ctx context.Context) ([]EnrolledRuntimeBinding, error)
// GetSessionExecutionBinding reads the Runtime device that executes the
// Session's Turns, with the native session that continues its history,
// once its Environment preparation completed; before that, and without an
// authorized bound device, it is ErrNotFound.
GetSessionExecutionBinding(ctx context.Context, tenant, session string) (ExecutionBinding, error)
// ListExecutionDevices lists the tenant's unrevoked devices that belong
// to no Environment, in ID order.
ListExecutionDevices(ctx context.Context, tenant string) ([]ExecutionDevice, error)
}
DeviceReader reads Runtime devices and their Session bindings.
type DeviceRegistration ¶
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, kinds []runtimedevice.SupportedAgentKind) (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 ¶
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 {
// ExternalWorkspace is a read projection of the immutable filesystem binding, not a setting.
ExternalWorkspace bool
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 ¶
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 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
// Key is the idempotency key the reservation's batch is admitted under.
Key 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; 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; 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 ¶
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) BeginTurnArtifactCapture ¶ added in v0.0.10
func (o *ExecutionOperations) BeginTurnArtifactCapture(ctx context.Context, tenant, session, turn string, appliedThrough int64) error
BeginTurnArtifactCapture admits the capture of an in-progress Turn's Artifacts once the execution applied its message inputs through appliedThrough; otherwise it is ErrUnappliedInputs. A Turn that is not in progress, has a cancellation request or already captures is ErrTurnConflict. A malformed ID or a negative appliedThrough is ErrInvalidInput.
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) CompleteExecution ¶ added in v0.0.10
func (o *ExecutionOperations) CompleteExecution(ctx context.Context, tenant, session, turn, status string, outcome json.RawMessage, nativeID string, appliedThrough int64) (Turn, error)
CompleteExecution ends the Turn an execution ran with the execution's terminal status and outcome. The status change, the outcome's journal entry, the native session that continues the Session's history and the Turn's settlement, which publishes or discards its staged Artifacts, commit together. A Turn completes only when the execution applied its message inputs through appliedThrough; otherwise it is ErrUnappliedInputs. A malformed ID, a status that does not end the Turn, an outcome that is not one JSON object of at most 512 KiB, a native session ID over 512 bytes and a negative appliedThrough are ErrInvalidInput.
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) ExpireEnvironmentInputs ¶ added in v0.0.10
func (o *ExecutionOperations) ExpireEnvironmentInputs(ctx context.Context) (int64, error)
ExpireEnvironmentInputs expires one bounded batch of pending reservations whose deadline has passed, reports the input activity each changes, creates no Turn history and returns how many it expired. It is cross-Session maintenance only the execution owner runs.
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) FailEnvironmentInput ¶ added in v0.0.10
func (o *ExecutionOperations) FailEnvironmentInput(ctx context.Context, tenant, session, reservation, code string) error
FailEnvironmentInput settles a pending reservation as failed before admission with code, model_provider_required or runtime_preparation_failed, once execution confirmed the failure. A reservation that already settled, including one cancelled meanwhile, keeps its outcome, and one whose deadline has passed expires instead. Any other code and a malformed reservation ID are ErrInvalidInput.
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) PromoteEnvironmentInput ¶ added in v0.0.10
func (o *ExecutionOperations) PromoteEnvironmentInput(ctx context.Context, tenant, session, reservation string) (EnvironmentInputReservation, error)
PromoteEnvironmentInput admits a pending reservation's batch into a new Turn and claims that Turn as in progress for the execution owner's retained native preparation. The reservation settles as admitted with the batch's receipts. A reservation that already settled, or expires now because its deadline has passed, is returned as it is. The Session must be idle with no pending file write; otherwise it is ErrTurnConflict and the reservation stays pending. A malformed reservation ID is ErrInvalidInput, and a missing reservation ErrNotFound.
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.
func (*ExecutionOperations) TransitionTurn ¶ added in v0.0.10
func (o *ExecutionOperations) TransitionTurn(ctx context.Context, tenant, session, turn string, transition TurnTransition) (Turn, error)
TransitionTurn moves the tenant's root Turn as transition asks, as the TransitionTurn procedure decides. A dispatcher claims a queued Turn as in progress before it sends the Turn's work to a Runtime. A malformed ID is ErrInvalidInput.
type ExecutionStorage ¶
type ExecutionStorage interface {
EnvironmentExecution
FunctionExecution
InputExecution
TurnExecution
}
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" binding:"required"`
CreatedAt time.Time `json:"created_at" binding:"required"`
RevokedAt *time.Time `json:"revoked_at" extensions:"x-nullable" binding:"required"`
}
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.
SignInstallation(ctx context.Context, payload string) (string, error)
// VerifyInstallation checks the signature of an installation
// authorization payload: another signature is
// ErrInstallationAuthorization.
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
// ApplyTurnStatus moves the Turn as change decides and returns it as
// stored. A Turn no longer in the expected status is ErrTurnConflict.
ApplyTurnStatus(ctx context.Context, turn string, change TurnStatusChange) (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.
func ValidateInputs ¶ added in v0.0.10
func ValidateInputs(inputs []Input) ([]Input, json.RawMessage, error)
ValidateInputs checks and normalizes an input batch: 1..64 messages, cancellations and function results whose nonempty JSON object payloads total at most 512 KiB, an empty cancellation payload and a well-formed function result. It returns the normalized batch and its encoding, the batch's retry identity.
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 InputAdmissionTx ¶ added in v0.0.10
type InputAdmissionTx interface {
FunctionResultTx
TurnCancellationTx
InputProjectionTx
ActiveTurnTx
// CreateTurn creates a queued Turn in the Session and returns it as
// stored.
CreateTurn(ctx context.Context) (Turn, error)
// CreateTurnInput records input at position of the batch admitted under
// key, joined to turn, or to no Turn when turn is empty, and returns the
// Session sequence it allocates.
CreateTurnInput(ctx context.Context, turn, key string, position int32, input Input) (int64, error)
}
InputAdmissionTx is the Session transaction AdmitInputs runs in.
type InputExecution ¶ added in v0.0.10
type InputExecution interface {
// WithInputs runs apply in one transaction on the execution lease, under
// the lock of the tenant's Session, and commits only when apply succeeds.
// A malformed tenant is ErrInvalidInput; a malformed, missing or deleted
// Session is ErrNotFound.
WithInputs(ctx context.Context, tenant, session string, apply func(context.Context, InputTx) error) error
// WithDueInputReservations runs apply in one transaction on the execution
// lease for each of at most 32 pending Environment input reservations
// whose deadline has passed, earliest deadline first, of live Sessions
// whose lock no other transaction holds, with that Session's transaction
// and the reservation's ID. It commits only when every apply succeeds.
WithDueInputReservations(ctx context.Context, apply func(context.Context, InputTx, string) error) error
}
InputExecution is the lease-bound storage of Environment input settlement.
type InputGate ¶ added in v0.0.10
type InputGate struct {
// Matches reports that the Session has no reservation under the batch's
// idempotency key, or one with the same batch.
Matches bool
// Blocked reports that a reservation is pending or one holds the batch's
// idempotency key.
Blocked bool
}
InputGate is what the Session's Environment input reservations show about a new input batch.
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 InputReader ¶ added in v0.0.10
type InputReader interface {
// ListTurnInputs pages a Turn's admitted inputs in sequence order after
// sequence after, at most limit of 1..100. It is an internal recovery
// read, not the public event stream. A malformed ID, a negative after and
// a limit out of range are ErrInvalidInput; a missing Turn is ErrNotFound.
ListTurnInputs(ctx context.Context, tenant, session, turn string, after int64, limit int) ([]TurnInput, error)
// GetEnvironmentInputReservation reads one of the tenant's Session's
// Environment input reservations; an admitted one carries the receipts of
// its batch. A malformed tenant or reservation ID is ErrInvalidInput; a
// missing or deleted Session and a missing reservation are ErrNotFound.
GetEnvironmentInputReservation(ctx context.Context, tenant, session, reservation string) (EnvironmentInputReservation, error)
// ListEnvironmentInputWork lists, in ID order after the reservation ID
// after or from the first when it is empty, at most 100 pending
// reservations before their deadline of live Sessions whose tenant has an
// unrevoked device among connectedDevices, the Session's bound device when
// it has one. A malformed ID is ErrInvalidInput.
ListEnvironmentInputWork(ctx context.Context, after string, connectedDevices []string) ([]EnvironmentInputWork, error)
}
InputReader reads a Session's admitted inputs, its Environment input reservations and the reservations execution may admit.
type InputReceipt ¶
type InputReceipt struct {
Sequence int64
TurnID string // Empty for a cancellation accepted while the Session was idle.
Replayed bool
}
func AdmitInputs ¶ added in v0.0.10
func AdmitInputs(ctx context.Context, tx InputAdmissionTx, key string, batch []Input) ([]InputReceipt, error)
AdmitInputs admits the validated batch under key, input by input in batch order, and returns their receipts. A function result joins the Turn whose call it answers. A message steers the Session's active Turn or, on an idle Session, starts a new Turn, which publishes turn.created, then the message's Items, then the Session activity. A cancellation requests the cancellation of the active Turn; on an idle Session it joins no Turn and keeps only its retry identity.
type InputStartTx ¶
type InputStartTx interface {
FileWriteGateTx
ActiveTurnTx
}
InputStartTx is the Session transaction CheckInputStart runs in.
type InputStorage ¶ added in v0.0.10
type InputStorage interface {
// WithInputs runs apply in one pooled transaction under the lock of the
// tenant's Session and commits only when apply succeeds. A malformed
// tenant is ErrInvalidInput; a malformed, missing or deleted Session is
// ErrNotFound.
WithInputs(ctx context.Context, tenant, session string, apply func(context.Context, InputTx) error) error
}
InputStorage is the pooled storage of the input use cases.
type InputTx ¶ added in v0.0.10
type InputTx interface {
InputAdmissionTx
InputActivityTx
InputStartTx
TurnTransitionTx
// LoadInputBatch reads the receipts of the inputs the Session admitted
// under key, in batch order and marked replayed, none when it admitted
// none, and reports whether they are batch.
LoadInputBatch(ctx context.Context, key string, batch json.RawMessage) ([]InputReceipt, bool, error)
// LoadInputGate reads what the Session's Environment input reservations
// show about batch under key.
LoadInputGate(ctx context.Context, key string, batch json.RawMessage) (InputGate, error)
// LoadEnvironment reads the Session's Environment; a Session without one
// is ErrNotFound.
LoadEnvironment(ctx context.Context) (Environment, error)
// FindInputReservation reads the Session's Environment input reservation
// under key when its batch is batch, nil otherwise, and reports whether
// the Session reserved key at all.
FindInputReservation(ctx context.Context, key string, batch json.RawMessage) (*EnvironmentInputReservation, bool, error)
// LoadInputReservation reads one of the Session's Environment input
// reservations; a missing one is ErrNotFound. An admitted reservation
// carries the receipts of its batch.
LoadInputReservation(ctx context.Context, reservation string) (EnvironmentInputReservation, error)
// CreateInputReservation reserves batch under key until the deadline the
// database clock sets, marked initial when it is the Session's initial
// input, and returns the pending reservation as stored.
CreateInputReservation(ctx context.Context, key string, batch json.RawMessage, initial bool) (EnvironmentInputReservation, error)
// ExpireInputReservation expires the reservation while it is pending and
// its deadline has passed by the database clock; otherwise it changes
// nothing.
ExpireInputReservation(ctx context.Context, reservation string) error
// AdmitInputReservation settles the pending reservation as admitted and
// returns when the database clock settled it.
AdmitInputReservation(ctx context.Context, reservation string) (time.Time, error)
// FailInputReservation settles the reservation as failed with code while
// it is pending; otherwise it changes nothing.
FailInputReservation(ctx context.Context, reservation, code string) error
// RecordInputAudit records the send_events write audit of the Session.
RecordInputAudit(ctx context.Context) error
}
InputTx is the Session transaction of the input use cases.
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 ItemDiagnosticTiming ¶
ItemDiagnosticTiming records Core database receipt and settlement, never native execution duration. Historical terminal Items can have unknown settlement.
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 JournalTurn ¶
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 {
// Engine is the immutable Harness selected when the Session was created.
Engine string
// 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" binding:"required"`
EnvironmentID string `json:"environment_id" binding:"required"`
State ManagedArchiveState `json:"state" binding:"required"`
}
ManagedArchive reports resource disposal, not archive request provenance or Turn settlement. Existing expiry and failed provisioning use the same states.
type ManagedArchiveState ¶ added in v0.0.10
type ManagedArchiveState string
const ( ManagedArchiveActive ManagedArchiveState = "active" ManagedArchiveCleanupPending ManagedArchiveState = "cleanup_pending" ManagedArchiveReleased ManagedArchiveState = "released" )
type ModelExecutionReader ¶ added in v0.0.10
type ModelExecutionReader interface {
// SessionModelExecution opens the model provider the tenant's Session
// froze at creation. A Session without one is ErrNotFound; a frozen
// provider that does not open, decode or validate is an internal error.
SessionModelExecution(ctx context.Context, tenant, session string) (*v1.ModelProviderInput, error)
}
ModelExecutionReader reads the model execution a Session froze at creation.
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 NewSession ¶ added in v0.0.10
type NewSession struct {
Key string
Creator identity.Subject
Engine string
Metadata json.RawMessage
Configuration json.RawMessage
// RequestHash identifies the resolved request; IntentHash, when set, the
// caller's intent before mutable sources resolved.
RequestHash string
IntentHash *string
}
NewSession is a validated Session creation with its retry identity.
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 ¶
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 ¶
func (f ProvisioningFailure) Detail() *ProvisioningFailureDetail
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 ¶
type Reader interface {
AdminReader
ArtifactReader
DeviceReader
EnvironmentReader
ExecutorCredentialReader
InputReader
ItemReader
ModelExecutionReader
SessionReader
SubagentReader
TurnReader
}
Reader reads Sessions and their resources, Environment and devices, and the administrator's cross-Project Session views, 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 ¶
NewService builds the Session use cases on storage. rules admit and place hosted Session creation; nil rules serve a service that never creates hosted Sessions, whose hosted creation then fails.
func (*Service) AuditSessionOperation ¶ added in v0.0.10
func (s *Service) AuditSessionOperation(ctx context.Context, command AuditSessionOperationCommand) error
AuditSessionOperation records the write audit of a public no-op or creation replay on the visible Session. It cannot create ownership or admit execution work. Another action is ErrInvalidInput.
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) CreateSession ¶ added in v0.0.10
func (s *Service) CreateSession(ctx context.Context, tenant string, input CreateSession) (Creation, error)
CreateSession creates a Session under a tenant-scoped key, so retries, including concurrent ones, return the stored Session. The same key with different input or another creator is ErrIdempotencyConflict. Only the new Session freezes resources and admits its initial inputs, so a retry after completion or later Turns never submits them again.
func (*Service) DeleteSession ¶ added in v0.0.10
func (s *Service) DeleteSession(ctx context.Context, command DeleteSessionCommand) error
DeleteSession removes public access to a settled Session while keeping the state execution needs to settle. It decides under the Session lock that also orders Turn and input admission, so a concurrent admission either commits first and is rejected here with ErrNotIdle, or observes the deletion. A repeated deletion only records the write audit; foreign and missing Sessions are ErrNotFound.
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) ExpireEnvironmentInput ¶ added in v0.0.10
func (s *Service) ExpireEnvironmentInput(ctx context.Context, tenant, session, reservation string) (EnvironmentInputReservation, error)
ExpireEnvironmentInput returns the Session's Environment input reservation, expired first when it is pending and its deadline has passed by the database clock. A malformed reservation ID is ErrInvalidInput, and a missing reservation ErrNotFound.
func (*Service) FindSessionCreation ¶ added in v0.0.10
func (s *Service) FindSessionCreation(ctx context.Context, tenant, key string, request json.RawMessage, creator identity.Subject) (Creation, error)
FindSessionCreation recovers a creation by its recorded caller intent, without resolving a mutable source. It returns only the Session ID; a recovered creation is never Created.
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) ReserveEnvironmentInput ¶ added in v0.0.10
func (s *Service) ReserveEnvironmentInput(ctx context.Context, tenant, session, key string, inputs []Input) (EnvironmentInputReservation, error)
ReserveEnvironmentInput admits a message batch for a Session whose Environment runs it. Under the Session lock it joins the active Turn at once, unless that Turn captures its Artifacts, or otherwise reserves the batch until a deadline, for the execution owner to promote into a new Turn. A retry returns the reservation under its key, expired once its deadline has passed, or the receipts the batch was admitted with. The checks of SubmitInputs apply, and a failed or expired Environment rejects new input.
func (*Service) RevokeDevice ¶
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) SubmitInputs ¶ added in v0.0.10
func (s *Service) SubmitInputs(ctx context.Context, tenant, session, key string, inputs []Input) ([]InputReceipt, error)
SubmitInputs admits a request's input batch in order under one Session lock and returns a receipt per input. The whole batch under its key is the retry identity: a retry replays the receipts of the batch it admitted, whatever has changed since, and the same key with a different batch is ErrIdempotencyConflict. A batch with a message waits for a pending file write to the Session's Environment (ErrTurnConflict), and no batch is admitted while an Environment input reservation is pending or holds the key (ErrInputPending). Internal receipts are not the response body of the public events endpoint.
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) UpdateSessionMetadata ¶ added in v0.0.10
func (s *Service) UpdateSessionMetadata(ctx context.Context, command UpdateSessionMetadataCommand) (Session, error)
UpdateSessionMetadata replaces the visible Session's metadata and returns the Session. Invalid metadata is ErrInvalidInput.
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 SessionDeletionTx ¶ added in v0.0.10
type SessionDeletionTx interface {
ActiveTurnTx
// 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)
// ApplyDeletion deletes the Session's Artifacts, releases the node
// placement of its Environments that have no allocation and removes the
// Session from public access. Its row stays so that execution can settle.
ApplyDeletion(ctx context.Context) error
// RecordDeletionAudit records the write audit of the deletion.
RecordDeletionAudit(ctx context.Context) error
}
SessionDeletionTx is the Session transaction DeleteSession runs in.
type SessionReader ¶ added in v0.0.10
type SessionReader interface {
// GetSession returns the tenant's visible Session with its Environment,
// input activity and latest Turn, read from one snapshot, or ErrNotFound.
GetSession(ctx context.Context, tenantID, sessionID string) (Session, error)
// ListSessions returns one page of the tenant's visible Sessions in
// creation-time and ID order; a non-nil agentID keeps that root Agent's
// Sessions. The cursor is the last returned Session ID and must belong to
// the tenant; it grants no additional access. A limit outside 1..100 is
// ErrInvalidInput.
ListSessions(ctx context.Context, tenantID, cursor string, limit int, ascending bool, agentID *string) (Page, error)
// SessionStreamSnapshot reads the projection GetSession returns and the
// committed Session event cursor from the same snapshot.
SessionStreamSnapshot(ctx context.Context, tenantID, sessionID string) (Session, int64, error)
// SessionEventCursor returns the sequence of the visible Session's latest
// public change, or ErrNotFound.
SessionEventCursor(ctx context.Context, tenantID, sessionID string) (int64, error)
// ListSessionEvents returns the retained public changes after the
// sequence, in order. A negative after is ErrInvalidInput; a pruned change
// in between is ErrStreamGap.
ListSessionEvents(ctx context.Context, tenantID, sessionID string, after int64) ([]SessionChange, error)
// GetTurnDiagnosticsSnapshot reads a root Turn and the timing of up to
// 1000 of its root Items with the Session in one read-only snapshot.
GetTurnDiagnosticsSnapshot(ctx context.Context, tenantID, sessionID, turnID string) (TurnDiagnosticsSnapshot, error)
// GetSessionExecutionConfiguration reads only the safe committed
// configuration. It never loads provider ciphertext, current defaults or
// runtime health.
GetSessionExecutionConfiguration(ctx context.Context, tenantID, sessionID string) (v1.SessionExecutionConfiguration, error)
// MeasuredSessionUsage returns Core-internal measured usage for Runtime
// telemetry: the sum of every recorded root Turn snapshot, active Turns
// included, and null only when nothing is recorded. Public Session usage
// keeps the official rule. A missing Session reads as null, so callers
// resolve the Session first.
MeasuredSessionUsage(ctx context.Context, tenantID, sessionID string) (json.RawMessage, error)
// GetManagedSessionArchive reads the resource disposal of the tenant's
// hosted Session and never contacts compute. A missing Session is
// ErrNotFound; one that is not hosted is ErrInvalidInput.
GetManagedSessionArchive(ctx context.Context, tenantID, sessionID string) (ManagedArchive, error)
}
SessionReader reads Sessions, their public change journal and their diagnostics.
type SessionStorage ¶ added in v0.0.10
type SessionStorage interface {
// WithSessionDeletion runs apply in one Session transaction of the
// tenant's Session, publicly deleted or not, with what the Session lock
// shows. It prunes the Session's journal after apply and commits only
// when both succeed. A malformed tenant is ErrInvalidInput; a malformed or
// missing Session is ErrNotFound.
WithSessionDeletion(ctx context.Context, tenantID, sessionID string, apply func(context.Context, LockedSession, SessionDeletionTx) error) error
// UpdateSessionMetadata replaces the visible Session's metadata with the
// encoded object, records the write audit and reads the Session as
// GetSession does, in one transaction, or returns ErrNotFound.
UpdateSessionMetadata(ctx context.Context, tenantID, sessionID string, encoded []byte) (Session, error)
// AuditSessionOperation records the write audit of action on the visible
// Session under its lock, or returns ErrNotFound.
AuditSessionOperation(ctx context.Context, tenantID, sessionID, action string) error
}
SessionStorage persists the public Session writes.
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 ¶
type Storage interface {
ArtifactStorage
CreationStorage
DeviceStorage
ExecutorCredentialStorage
SessionStorage
InputStorage
}
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 ¶
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.
func TransitionTurn ¶ added in v0.0.10
func TransitionTurn(ctx context.Context, tx TurnTransitionTx, turn string, transition TurnTransition) (Turn, error)
TransitionTurn moves the Session's root Turn as transition asks, a compare-and-set on its status, and publishes what the move settles. A Turn that keeps running journals its event. A Turn that ends projects its outcome, then settles as EndTurn decides from the Turn read after the projection, which may record its usage. An ended Turn is never reopened and its outcome never overwritten, including by retries.
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.
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 TurnExecution ¶ added in v0.0.10
type TurnExecution interface {
// WithTurns runs apply in one transaction on the execution lease, under
// the tenant's Session lock, and commits only when apply succeeds. A
// malformed ID is ErrInvalidInput and a missing Session ErrNotFound; a
// publicly deleted Session still journals and settles its Turns.
WithTurns(ctx context.Context, tenant, session string, apply func(context.Context, TurnTx) error) error
}
TurnExecution is the lease-bound storage of the Turn execution operations.
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 TurnReader ¶ added in v0.0.10
type TurnReader interface {
// GetTurn reads the tenant's root Turn of the Session. A malformed tenant
// is ErrInvalidInput; a malformed Session or Turn ID, a Subagent Turn ID
// and a missing Turn are ErrNotFound.
GetTurn(ctx context.Context, tenant, session, turn string) (Turn, error)
// ListTurns pages the root Turns of the tenant's Session that was not
// publicly deleted by creation time and ID, after the Turn cursor names.
// A page size outside 1..100 is ErrInvalidInput; a missing Session or
// cursor Turn is ErrNotFound.
ListTurns(ctx context.Context, tenant, session, cursor string, limit int, ascending bool) (TurnPage, error)
// ListExecutionWork lists, in ID order after the Turn after names, up to
// 100 root Turns in statuses across tenants; the queued Turns of a publicly
// deleted Session are not work. With connectedDevices not nil, it lists
// only the Turns of tenants that own one of those devices, unrevoked.
ListExecutionWork(ctx context.Context, after string, statuses, connectedDevices []string) ([]ExecutionWork, error)
}
TurnReader reads root Turns. Subagent Turns are not Session Turns; SubagentReader reads them.
type TurnStatusChange ¶ added in v0.0.10
type TurnStatusChange struct {
Expected string
Status string
Outcome json.RawMessage
// SourceCompletedAt is when the native source completed a Turn that ends
// completed, zero when it reported none.
SourceCompletedAt time.Time
}
TurnStatusChange is a decided change of a Turn's status.
type TurnTransition ¶
type TurnTransition struct {
ExpectedStatus string
Status string
Outcome json.RawMessage
}
TurnTransition asks to move a Turn from ExpectedStatus to Status. Only a Turn that ends carries an outcome.
type TurnTransitionTx ¶ added in v0.0.10
type TurnTransitionTx interface {
ProjectionTx
ComputeAdmissionTx
// LoadTurn reads one of the Session's Turns; a missing one is ErrNotFound.
LoadTurn(ctx context.Context, turn string) (Turn, error)
// ApplyTurnStatus moves the Turn as change decides and returns it as
// stored. The database clock stamps the first start of a Turn that moves
// to in progress and the end of a Turn that ends, unless the change carries
// the source completion time. A Turn no longer in the expected status is
// ErrTurnConflict.
ApplyTurnStatus(ctx context.Context, turn string, change TurnStatusChange) (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
}
TurnTransitionTx is the Session transaction TransitionTurn runs in.
type TurnTx ¶ added in v0.0.10
type TurnTx interface {
TurnTransitionTx
TurnEventTx
TurnJournalTx
// HasUnappliedInputs reports whether the Turn has message inputs after
// sequence appliedThrough.
HasUnappliedInputs(ctx context.Context, turn string, appliedThrough int64) (bool, error)
// RememberNativeSession records the native session that continues the
// Session's history on its bound device. A Session without a bound device
// is ErrNotFound.
RememberNativeSession(ctx context.Context, native string) error
// BeginArtifactCapture marks that the Turn captures its Artifacts. A Turn
// that already does is ErrTurnConflict.
BeginArtifactCapture(ctx context.Context, turn string) error
}
TurnTx is the Session transaction of the Turn execution operations.
Source Files
¶
- admin.go
- admission.go
- artifacts.go
- cancellation.go
- creation.go
- devices.go
- doc.go
- environment.go
- environment_device.go
- environment_inputs.go
- environment_installation.go
- environment_termination.go
- errors.go
- execution.go
- execution_configuration.go
- execution_environment.go
- execution_file_writes.go
- execution_functions.go
- execution_inputs.go
- execution_turns.go
- executor_credentials.go
- functions.go
- input_activity.go
- inputs.go
- items.go
- journal.go
- model_execution.go
- project_executor_credentials.go
- projection.go
- provisioning.go
- reader.go
- reads.go
- service.go
- session.go
- session_change.go
- subagents.go
- transaction.go
- turn.go
- turn_changes.go
- usage.go