run

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package run defines the Run, Step, and ToolCall entities for agent execution.

Index

Constants

View Source
const (
	FailureUnverified              = "run_unverified"
	FailureVerificationUnavailable = "verification_unavailable"
)

Public verification failure codes are stable across transport adapters.

Variables

This section is empty.

Functions

func ContentProtected

func ContentProtected(r *Run, readerConfigured bool) bool

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

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 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 ListFilter

type ListFilter struct {
	AgentID string
	State   State
	Exact   bool
	Limit   int
	Offset  int
}

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 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"`
}

Run represents a single execution of an agent.

func PublicView

func PublicView(r *Run, readerConfigured bool) *Run

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

func (r Run) MarshalJSON() ([]byte, error)

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

func (r *Run) UnmarshalJSON(data []byte) error

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"
)

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"
	StopPolicyUnavailable  StopReason = "policy_unavailable"
	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.

Jump to

Keyboard shortcuts

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