Documentation
¶
Overview ¶
Package run defines the Run, Step, and ToolCall entities for agent execution.
Index ¶
- Constants
- func ContentProtected(r *Run, readerConfigured bool) bool
- type CandidateCapture
- type CandidateStore
- type ContinuationStore
- type ExecutionProvenance
- type ExecutionPurpose
- type Lease
- type ListFilter
- type Outcome
- type Readiness
- type ReadyNotice
- type ReadySource
- type ReclaimNotice
- type Revision
- type Run
- type SourceSnapshot
- type State
- type Step
- type StopReason
- type Store
- type TerminalSummary
- type ToolCall
- type VerificationFailure
Constants ¶
const ( FailureUnverified = "run_unverified" )
Public verification failure codes are stable across transport adapters.
Variables ¶
This section is empty.
Functions ¶
func ContentProtected ¶
ContentProtected identifies historical reads that must use the guarded result endpoint for bytes. A saved requirement or result keeps protection active even when the current host has no reader configured.
Types ¶
type CandidateCapture ¶
type CandidateCapture struct {
Transcript []byte `json:"transcript,omitempty"`
SchemaVersion int `json:"schema_version"`
IntentID id.ID `json:"intent_id"`
ExpectedRunRevision int64 `json:"expected_run_revision"`
Output string `json:"output"`
FinishReason string `json:"finish_reason"`
Usage execution.Usage `json:"usage"`
}
CandidateCapture ends generation under a registered intent. Output is private candidate material, not an authorized public answer. The trusted runtime supplies cumulative usage and the saved running revision before finalization.
func (CandidateCapture) Freeze ¶
func (c CandidateCapture) Freeze() (CandidateCapture, string, error)
Freeze validates a final-answer capture and binds retries to identical content and accounting. It leaves room for capture, enqueue and commit revisions.
type CandidateStore ¶
type CandidateStore interface {
CaptureCandidate(context.Context, CandidateCapture) (verification.Job, error)
}
CandidateStore atomically saves private evidence, finishes generation and enqueues verification. Run output stays empty until guarded result commit. It is a raw host storage capability: authorize capture and reserve the budget before use. It does not gate the engine's streams, history or tool dispatch.
type ContinuationStore ¶ added in v1.10.0
type ContinuationStore interface {
// MarkReady moves a paused run whose suspension has not expired to StateReady, saves r and
// advances Revision. ErrNotSuspended when the run is not paused, or when its suspension is not
// r.SuspensionID; ErrSuspensionExpired when its suspension's deadline has passed. Then it
// clears the suspension's deadline.
MarkReady(ctx context.Context, runID id.AgentRunID, r Readiness) (*Run, error)
// HoldLease sets or extends the lease of a running run whose lease is unowned or owned by
// lease.Owner. ErrRunLeaseLost otherwise, and for a lease with no owner or no expiry. Never
// advances Revision.
HoldLease(ctx context.Context, runID id.AgentRunID, lease Lease) error
// MarkReclaimable moves a running run to StateReclaimable and clears its lease, advancing
// Revision. With owner == "" the lease must have expired at or before now (Reclaims+1,
// ErrRunLeased otherwise, including a run that holds no lease). With owner set the lease must
// be owner's (a graceful hand-off; Reclaims unchanged, ErrRunLeaseLost otherwise). A run that
// is no longer running returns ErrRunConflict.
MarkReclaimable(ctx context.Context, runID id.AgentRunID, now time.Time, owner string) (*Run, error)
// ClaimContinuation moves a ready or reclaimable run to running under lease, clears Ready and
// NotifiedAt, advances Revision. ErrRunNotContinuable otherwise. Two callers: exactly one wins.
// A zero Lease claims the run with no lease, which the lapsed listing never returns. A lease
// with an owner and no expiry, or an expiry and no owner, is refused with ErrRunLeaseLost.
ClaimContinuation(ctx context.Context, runID id.AgentRunID, lease Lease) (*Run, error)
// ListLapsedAcrossScopes lists running runs whose lease expiry is set and at or before now,
// oldest expiry first. It deliberately bypasses scope, for the sweeper only.
ListLapsedAcrossScopes(ctx context.Context, now time.Time, limit int) ([]*Run, error)
// ListContinuableAcrossScopes lists ready or reclaimable runs whose NotifiedAt is nil or before
// notifiedBefore, oldest UpdatedAt first. It deliberately bypasses scope, for the sweeper only.
ListContinuableAcrossScopes(ctx context.Context, notifiedBefore time.Time, limit int) ([]*Run, error)
// MarkNotified sets NotifiedAt on a ready or reclaimable run and never advances Revision.
// ErrRunNotContinuable when the run is in any other state.
MarkNotified(ctx context.Context, runID id.AgentRunID, at time.Time) error
}
ContinuationStore is an optional capability of run stores. Every method works at the caller's exact scope except the two AcrossScopes listings, which exist for the engine sweeper only.
type ExecutionProvenance ¶
type ExecutionProvenance struct {
ContextSelection *cognitive.ContextRecord `json:"context_selection,omitempty"`
OrchestrationID string `json:"orchestration_id,omitempty"`
OrchestrationDigest string `json:"orchestration_digest,omitempty"`
OrchestrationReservationID string `json:"orchestration_reservation_id,omitempty"`
// TaskClaimID requires live task-call leases, including after resume.
TaskClaimID string `json:"task_claim_id,omitempty"`
ExecutionInputsDigest string `json:"execution_inputs_digest,omitempty"`
VerificationRequired bool `json:"verification_required,omitempty"`
VerificationIntentID string `json:"verification_intent_id,omitempty"`
// SourceValidation distinguishes read-set checks from atomic store capture.
// read_set_checked detects observed changes but is not an atomic snapshot.
SourceSnapshot SourceSnapshot `json:"source_snapshot,omitzero"`
SourceValidation string `json:"source_validation,omitempty"`
SourceReads []Revision `json:"source_reads,omitempty"`
// RecalledLessons retains trusted retrieval identities before their content is used.
RecalledLessons []Revision `json:"recalled_lessons,omitempty"`
// ConversationWrites binds emitted memory messages to this source run.
ConversationWrites []Revision `json:"conversation_writes,omitempty"`
// UnattributedHistory excludes history with unavailable source receipts from learning.
UnattributedHistory bool `json:"unattributed_history,omitempty"`
PublicationStatus safety.PublicationStatus `json:"publication_status,omitempty"`
SchemaVersion int `json:"schema_version"`
PreparedDigest string `json:"prepared_digest"`
DerivedFrom string `json:"derived_from,omitempty"`
Purpose ExecutionPurpose `json:"purpose"`
// AssignmentDigest binds a trusted host execution to its sealed handoff.
AssignmentDigest string `json:"assignment_digest,omitempty"`
ParentRunID string `json:"parent_run_id,omitempty"`
ExperimentID string `json:"experiment_id,omitempty"`
CandidateID string `json:"candidate_id,omitempty"`
EnvironmentReceiptID string `json:"environment_receipt_id,omitempty"`
TrialID string `json:"trial_id,omitempty"`
HarnessID string `json:"harness_id,omitempty"`
HarnessVersion string `json:"harness_version,omitempty"`
AcceptanceRef string `json:"acceptance_ref,omitempty"`
ModelRevision string `json:"model_revision,omitempty"`
Sources []Revision `json:"sources,omitempty"`
Tools []Revision `json:"tools,omitempty"`
Diagnostics []string `json:"diagnostics,omitempty"`
}
ExecutionProvenance identifies the inputs behind a run without copying prompt or evidence bytes into metadata. Empty fields mean unavailable, not verified.
type ExecutionPurpose ¶
type ExecutionPurpose string
ExecutionPurpose is trusted host metadata. Model output cannot select it.
const ( PurposeNormal ExecutionPurpose = "normal" PurposeEvaluation ExecutionPurpose = "evaluation" PurposeOptimizationTrial ExecutionPurpose = "optimization_trial" PurposeOptimizationController ExecutionPurpose = "optimization_controller" )
type Lease ¶ added in v1.10.0
type Lease struct {
// Owner is the worker's id, which names its host. Stores keep it; it is
// never serialized, so run JSON and API responses do not carry it.
Owner string `json:"-"`
ExpiresAt time.Time `json:"expires_at"`
}
Lease is one worker's hold on a running run. A lease whose ExpiresAt has passed has lapsed, and the sweeper may hand the run to another replica.
type ListFilter ¶
ListFilter controls pagination and matching for run listing. Scope arrives on the context; Exact narrows the read to rows stored at precisely that depth instead of everything beneath it.
type Outcome ¶
type Outcome struct {
Transcript *verification.ExecutionTranscript `json:"-"`
StopReason StopReason
Output string
FinishReason string
StepCount int
TokensUsed int
CompletedAt time.Time
}
Outcome is an execution result, not a verification claim.
type Readiness ¶ added in v1.10.0
type Readiness struct {
Source ReadySource `json:"source"`
// Results holds the engine-encoded tool results. Stores keep the bytes
// exactly as given and never interpret them.
Results json.RawMessage `json:"results,omitempty"`
CheckpointID id.CheckpointID `json:"checkpoint_id,omitempty"`
At time.Time `json:"at"`
// SuspensionID is the pause the decision or the results answer.
// MarkReady refuses with cortex.ErrNotSuspended when the run's current
// suspension is a different one, so an answer to one pause can never
// be applied to the next.
SuspensionID id.SuspensionID `json:"suspension_id,omitempty"`
// DecidedBy and DecidedByPrincipal are the checkpoint decider, kept
// so the decision can still be recorded with its real decider if the
// write to the checkpoint is lost. Empty for external results.
DecidedBy string `json:"decided_by,omitempty"`
DecidedByPrincipal []byte `json:"decided_by_principal,omitempty"`
}
Readiness is what a ready run continues with.
type ReadyNotice ¶ added in v1.10.0
type ReadyNotice struct {
Source ReadySource
// CheckpointID is the checkpoint whose decision made the run ready. It
// is zero when Source is ReadyExternalResults.
CheckpointID id.CheckpointID
At time.Time
// Renotified is true when the sweeper repeats the notice for a run
// that has waited longer than it should, false the first time.
Renotified bool
}
ReadyNotice is what a host hears when a run becomes ready to continue: what made it ready, and when. The run's scope travels on the hook's ctx.
type ReadySource ¶ added in v1.10.0
type ReadySource string
ReadySource says what made a paused run ready.
const ( // ReadyApproval is a reviewer's approval of the run's pending calls. ReadyApproval ReadySource = "approval" // ReadyExternalResults is a caller's answers to the run's external calls. ReadyExternalResults ReadySource = "external_results" // ReadyRejection is a reviewer's rejection that goes back to the model. // It only appears with engine.WithRejectionsReturnToModel. ReadyRejection ReadySource = "rejection" )
type ReclaimNotice ¶ added in v1.10.0
type ReclaimNotice struct {
// PreviousOwner is the worker whose lease the run was under.
PreviousOwner string
// LeaseExpiredAt is when the lease lapsed, or, for a hand-off, when
// the worker released it.
LeaseExpiredAt time.Time
// Reclaims counts how often the run has been reclaimed after a lapsed
// lease. A hand-off does not add to it.
Reclaims int
// HandOff is true when the worker released the run at shutdown rather
// than its lease lapsing.
HandOff bool
// Renotified is true when the sweeper repeats the notice for a run
// that has waited longer than it should, false the first time. A
// repeated notice carries what the run still records: PreviousOwner is
// empty, HandOff is false and LeaseExpiredAt is when the run became
// reclaimable.
Renotified bool
}
ReclaimNotice is what a host hears when a run becomes reclaimable: whose lease it was, when that lease ended, and how often the run has been reclaimed. The run's scope travels on the hook's ctx.
type Revision ¶
type Revision struct {
Name string `json:"name"`
Digest string `json:"digest,omitempty"`
Revision string `json:"revision,omitempty"`
}
Revision binds a named source or tool to its frozen content or host revision.
type Run ¶
type Run struct {
// Revision is the persisted write version. UpdateRun compares and advances it.
// Zero identifies a historical record that has not been updated yet.
Revision int64 `json:"revision"`
Provenance ExecutionProvenance `json:"provenance,omitempty"`
Budget execution.Budget `json:"budget,omitempty"`
Usage execution.Usage `json:"usage,omitempty"`
cortex.Entity
ID id.AgentRunID `json:"id"`
AgentID id.AgentID `json:"agent_id"`
SessionID id.SessionID `json:"session_id,omitempty"`
Scope cortex.Scope `json:"scope"`
State State `json:"state"`
FinishReason string `json:"finish_reason,omitempty"`
VerificationStatus verification.Status `json:"verification_status"`
ResultRef string `json:"result_ref,omitempty"`
StopReason StopReason `json:"stop_reason,omitempty"`
Input string `json:"input"`
Output string `json:"output,omitempty"`
Error string `json:"error,omitempty"`
StepCount int `json:"step_count"`
TokensUsed int `json:"tokens_used"`
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
PersonaRef string `json:"persona_ref,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
// Principal is the run's caller, as the engine's cortex.PrincipalCodec
// encoded it when the run was created. A resume decodes it and runs
// under it, never under whoever resumed. Stores persist it and never
// rewrite it; it is never serialized, so an API reader cannot see it.
Principal []byte `json:"-"`
// ReplyRoute is where the answer goes for a run the messaging bus
// started for a directive, encoded by the engine, reply token
// included. Only the engine reads it. Stores persist it once, when the
// run is created, and never rewrite it; it is never serialized, so the
// token stays out of run JSON, events and API responses.
ReplyRoute []byte `json:"-"`
// Lease names the worker that holds a running run and when its hold
// lapses. Nil means no worker holds a lease on the run.
Lease *Lease `json:"lease,omitempty"`
// Ready is what a ready run continues with. Stores persist it; it is
// never serialized, because Results carries tool output.
Ready *Readiness `json:"-"`
// Reclaims counts how many times a lapsed lease moved the run to
// StateReclaimable.
Reclaims int `json:"reclaims,omitempty"`
// NotifiedAt is when the host was last told a ready or reclaimable run
// is waiting. It is store bookkeeping for the sweeper and never
// serialized.
NotifiedAt *time.Time `json:"-"`
}
Run represents a single execution of an agent.
func PublicView ¶
PublicView preserves ordinary legacy reads and projects protected runs onto an explicit metadata allowlist. It never authorizes content or mutates the source. Trusted host code can still obtain the original through the engine/store APIs.
func (Run) MarshalJSON ¶
MarshalJSON makes unchecked explicit for legacy runs and zero-value structs.
func (*Run) TerminalSummary ¶
func (r *Run) TerminalSummary() TerminalSummary
TerminalSummary returns outcome metadata with legacy verification normalized.
func (*Run) UnmarshalJSON ¶
UnmarshalJSON preserves unknown enum values and defaults missing assurance.
func (*Run) ValidateExecutionInputs ¶
func (r *Run) ValidateExecutionInputs(inputs verification.ExecutionInputs) error
ValidateExecutionInputs checks saved run identity against the immutable input artifact. History and the model selector are bound through the artifact and prepared digest; model and tool implementation pins also match provenance.
type SourceSnapshot ¶
type SourceSnapshot struct {
ID string `json:"id"`
Provider string `json:"provider"`
Isolation string `json:"isolation"`
Scope string `json:"scope"`
}
SourceSnapshot records a successful store capture. ID identifies this capture, not a reusable database revision or a model/tool implementation pin. External retrieval is not covered by a store transaction.
type State ¶
type State string
State represents the lifecycle state of an agent run.
const ( StateCreated State = "created" StateRunning State = "running" StateCompleted State = "completed" StateIncomplete State = "incomplete" StateFailed State = "failed" StateCancelled State = "cancelled" StatePaused State = "paused" // StateReady is a paused run whose decision or answers are recorded. It // waits for ContinueRun, and any replica may continue it. StateReady State = "ready" // StateReclaimable is a running run whose worker's lease lapsed or was // handed off. It waits for ContinueRun, and any replica may continue it. StateReclaimable State = "reclaimable" )
type Step ¶
type Step struct {
cortex.Entity
ID id.StepID `json:"id"`
RunID id.AgentRunID `json:"run_id"`
Scope cortex.Scope `json:"scope"`
Index int `json:"index"`
Type string `json:"type,omitempty"`
Input string `json:"input,omitempty"`
Output string `json:"output,omitempty"`
TokensUsed int `json:"tokens_used"`
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Step represents a single reasoning step within a run.
type StopReason ¶
type StopReason string
StopReason records why execution ended. Empty means historical or unknown.
const ( StopExecutionError StopReason = "execution_error" StopInvalidResponse StopReason = "invalid_response" StopProviderUnknown StopReason = "provider_unknown" StopFinalAnswer StopReason = "final_answer" StopStepLimit StopReason = "step_limit" StopToolLimit StopReason = "tool_limit" StopTokenLimit StopReason = "token_limit" StopCostLimit StopReason = "cost_limit" StopDeadline StopReason = "deadline" StopCancelled StopReason = "cancelled" StopSafetyBlock StopReason = "safety_block" StopToolError StopReason = "tool_error" StopPersistenceError StopReason = "persistence_error" StopVerificationFailed StopReason = "verification_failed" )
type Store ¶
type Store interface {
CreateRun(ctx context.Context, run *Run) error
GetRun(ctx context.Context, runID id.AgentRunID) (*Run, error)
// UpdateRun compares the stored Revision and advances it on success.
// A stale or exhausted revision returns cortex.ErrRunConflict. Reload and
// reconsider the update; blindly retrying would overwrite another writer.
// Failed updates leave the caller's revision and UpdatedAt unchanged.
UpdateRun(ctx context.Context, run *Run) error
ListRuns(ctx context.Context, filter *ListFilter) ([]*Run, error)
CountRuns(ctx context.Context, filter *ListFilter) (int64, error)
CreateStep(ctx context.Context, step *Step) error
ListSteps(ctx context.Context, runID id.AgentRunID) ([]*Step, error)
CreateToolCall(ctx context.Context, tc *ToolCall) error
ListToolCalls(ctx context.Context, stepID id.StepID) ([]*ToolCall, error)
}
Store defines persistence for runs, steps, and tool calls.
type TerminalSummary ¶
type TerminalSummary struct {
State State `json:"state"`
StopReason StopReason `json:"stop_reason"`
VerificationStatus verification.Status `json:"verification_status"`
PublicationStatus safety.PublicationStatus `json:"publication_status"`
}
TerminalSummary contains bounded outcome metadata without model or tool text. It describes a persisted execution, independently of factual verification.
type ToolCall ¶
type ToolCall struct {
cortex.Entity
ID id.ToolCallID `json:"id"`
StepID id.StepID `json:"step_id"`
RunID id.AgentRunID `json:"run_id"`
Scope cortex.Scope `json:"scope"`
ToolName string `json:"tool_name"`
Arguments string `json:"arguments,omitempty"`
Result string `json:"result,omitempty"`
Error string `json:"error,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
ToolCall represents a single tool invocation within a step.
type VerificationFailure ¶
type VerificationFailure struct {
Code string `json:"code"`
Message string `json:"message"`
RunID string `json:"run_id,omitempty"`
State State `json:"state,omitempty"`
VerificationStatus string `json:"verification_status,omitempty"`
Retryable bool `json:"retryable"`
}
VerificationFailure contains safe metadata for inspecting a failed request. Retryable is false: a new run can repeat generation or external tool effects. An unavailable verifier may already have performed durable work; recover that work through its saved identities rather than automatically starting again.
func DescribeVerificationFailure ¶
func DescribeVerificationFailure(err error, r *Run) (VerificationFailure, bool)
DescribeVerificationFailure classifies wrapped sentinels without preserving private diagnostics. A run supplies identity and status only, never its output.
func (VerificationFailure) Fields ¶
func (f VerificationFailure) Fields() map[string]any
Fields returns a detached, transport-neutral error payload. Missing run identity means this response cannot identify saved work, not that none exists.