execution

package
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package execution defines cumulative execution limits and accounting.

Index

Constants

View Source
const (
	// EffectActionRetry and EffectActionCompensate require distinct current grants.
	EffectActionRetry      EffectAction = "retry"
	EffectActionCompensate EffectAction = "compensate"
	// MaxEffectContinuations bounds seven additional attempts and eight compensations.
	MaxEffectContinuations = 15
	ContinuationAbsence    = "permanent_absence"
	ContinuationIdempotent = "provider_idempotency"
	ContinuationApplied    = "applied_compensation"
)
View Source
const (
	MaxReservations     = 1024
	MaxReservationDepth = 16
)
View Source
const (
	MaxRunRecoveryEntries = 4096
	MaxRunRecoveryBytes   = 16 << 20
)

Recovery snapshots have explicit count and encoding bounds. Oversized journals cannot be represented as a truncated snapshot or treated as complete evidence.

View Source
const MaxEffectDuration = 30 * time.Second

MaxEffectDuration bounds one dispatch or reconciliation, including host resolution.

View Source
const PrefixEffectAttempt id.Prefix = "effat"

PrefixEffectAttempt identifies the original dispatch, retained across recovery.

View Source
const PrefixReservation id.Prefix = "bres"
View Source
const PrefixRunCall id.Prefix = "tcallguard"

PrefixRunCall identifies a guarded task invocation.

Variables

View Source
var (
	ErrEffectConflict    = cortex.ErrEffectConflict
	ErrEffectNotFound    = cortex.ErrEffectNotFound
	ErrEffectUncertain   = cortex.ErrEffectUncertain
	ErrEffectUnavailable = cortex.ErrEffectUnavailable
)
View Source
var (
	ErrInvalidReservation  = cortex.ErrInvalidReservation
	ErrReservationConflict = cortex.ErrReservationConflict
	ErrReservationNotFound = cortex.ErrReservationNotFound
	ErrBudgetExceeded      = cortex.ErrSharedBudgetExceeded
)
View Source
var (
	ErrInvalidRunCall  = cortex.ErrInvalidRunCall
	ErrRunCallConflict = cortex.ErrRunCallConflict
	ErrRunCallNotFound = cortex.ErrRunCallNotFound
)
View Source
var (
	ErrRunCallsSealed     = cortex.ErrRunCallsSealed
	ErrRunCallUnavailable = cortex.ErrRunCallUnavailable
)
View Source
var ErrInvalidEffect = errors.New("cortex: invalid effect requirement")

ErrInvalidEffect identifies an incomplete or unsafe host effect declaration.

View Source
var ErrProviderCallUncertain = cortex.ErrProviderCallUncertain

ErrProviderCallUncertain keeps unresolved provider calls reserved.

Functions

func AdmitReservation

func AdmitReservation(p ReservationPolicy, reservations []Reservation, r ReservationRequest, at time.Time) error

AdmitReservation checks both the root account and the immediate parent before admitting a new allocation. Account inputs must come from trusted storage.

func CheckReservationBudget

func CheckReservationBudget(p ReservationPolicy, reservations []Reservation, identifier id.ID, at time.Time) error

CheckReservationBudget checks an existing open allocation, its ancestors and the aggregate account before further work. Trusted storage must supply every reservation; this check grants no permission and does not enforce runtime use.

func CompensationOperationKey

func CompensationOperationKey(original EffectRequest) string

CompensationOperationKey is reserved for explicit continuation admissions.

func EffectPredecessorDigest

func EffectPredecessorDigest(request EffectRequest, receipt *EffectReceipt) (string, error)

EffectPredecessorDigest binds provider proof to the exact preceding observation.

func IsCompensationOperationKey

func IsCompensationOperationKey(key string) bool

IsCompensationOperationKey identifies a key unavailable to ordinary dispatch.

func RunCallKey

func RunCallKey(runID id.AgentRunID, operationDigest string) string

RunCallKey binds a logical operation to one run without retaining its input.

func WithRunCallContext

func WithRunCallContext(ctx context.Context, r RunCallRequest) context.Context

WithRunCallContext supplies detached correlation metadata to a provider. It does not authorize a call or imply provider support for idempotent requests.

Types

type BoundEffectStore

type BoundEffectStore interface {
	EffectStore
	BeginBoundEffect(context.Context, EffectRequest) (bool, error)
}

BoundEffectStore admits effects only against the exact retained, unfinished tool call. Fresh admission checks its deadline and serializes with run sealing and local call completion. A seal blocks admission, including replay, while CompleteEffect remains available for late terminal proof. Custom stores must implement this contract before serving guarded task tools.

type Budget

type Budget struct {
	MaxSteps     int       `json:"max_steps,omitempty"`
	MaxTokens    int       `json:"max_tokens,omitempty"`
	MaxToolCalls int       `json:"max_tool_calls,omitempty"`
	Deadline     time.Time `json:"deadline,omitempty"`
}

Budget bounds one run across steps and resumptions. Zero optional limits are disabled. MaxTokens gates further dispatch; provider-reported input usage can exceed the remaining allowance in one call and is never hidden or clamped.

func (Budget) Check

func (b Budget) Check(u Usage, now time.Time) Limit

Check reports whether another model step may start. Tool slots are checked separately, so a run can synthesize an answer after its final tool call.

func (Budget) CheckTool

func (b Budget) CheckTool(u Usage, now time.Time) Limit

CheckTool reports whether a logical tool call may be admitted.

func (Budget) Equal

func (b Budget) Equal(other Budget) bool

Equal compares persisted limits independently of timezone or monotonic clocks.

func (Budget) OutputLimit

func (b Budget) OutputLimit(configured int, u Usage) int

OutputLimit narrows the provider's per-call output cap to the remaining total.

func (Budget) Validate

func (b Budget) Validate() error

Validate rejects negative limits, which cannot mean unlimited by accident.

type BudgetSnapshot

type BudgetSnapshot struct {
	Policy       ReservationPolicy `json:"policy"`
	Charged      Resources         `json:"charged"`
	Overflow     bool              `json:"overflow"`
	Reservations int               `json:"reservations"`
}

BudgetSnapshot reports conservative charges. Overflow means aggregation or a leaf's observed usage exceeded int64. Original usage evidence must be retained separately from the saturated charge.

func AccountReservations

func AccountReservations(p ReservationPolicy, reservations []Reservation) (BudgetSnapshot, error)

AccountReservations charges each branch once while propagating child overruns immediately to its ancestors. Closed branches refund only unallocated or known unused capacity; every retained reservation consumes one fan-out slot.

type BudgetStore

type BudgetStore interface {
	CreateReservationPolicy(context.Context, ReservationPolicy) error
	GetReservationPolicy(context.Context, id.ID) (ReservationPolicy, error)
	Reserve(context.Context, ReservationRequest) (Reservation, error)
	Settle(context.Context, Settlement) error
	GetReservation(context.Context, id.ID) (Reservation, error)
	ListReservations(context.Context, ReservationListRequest) ([]Reservation, error)
	GetBudgetSnapshot(context.Context, id.ID) (BudgetSnapshot, error)
}

BudgetStore is optional shared accounting. Callers provide authenticated usage and bounded provider estimates; neither reservations nor receipts grant access. Branches settle only after every child has final accounting. Unknown usage is charged pessimistically and never refunded merely because its lease expired.

type EffectAction

type EffectAction string

EffectAction lets host policy distinguish mutations from recovery reads.

const (
	EffectActionExecute   EffectAction = "execute"
	EffectActionReconcile EffectAction = "reconcile"
)

type EffectAdapter

type EffectAdapter interface {
	Execute(context.Context, EffectRequest, []byte) (EffectReceipt, error)
	Reconcile(context.Context, EffectRequest) (EffectStatus, error)
}

EffectAdapter is a trusted registered handler. Execute must enforce current authorization at its external write boundary, honor deadlines, and use the stable OperationKey for provider idempotency when declared. Reconcile is read-only and must never dispatch, compensate or infer failure from absence. It must bind provider evidence to the full request and original attempt.

type EffectClass

type EffectClass string

EffectClass is trusted handler metadata, never inferred from model text.

const (
	EffectReadOnly      EffectClass = "read_only"
	EffectIdempotent    EffectClass = "idempotent_mutation"
	EffectNonIdempotent EffectClass = "non_idempotent_mutation"
	EffectCompensatable EffectClass = "compensatable_mutation"
)

type EffectContinuation

type EffectContinuation struct {
	Request       EffectContinuationRequest `json:"request"`
	RequestDigest string                    `json:"request_digest"`
	Reservation   Reservation               `json:"reservation"`
	At            time.Time                 `json:"at"`
	Fresh         bool                      `json:"-"`
}

EffectContinuation retains intent before dispatch and its optional terminal observation. Fresh is process-local permission and is never serialized.

func (EffectContinuation) Validate

func (a EffectContinuation) Validate() error

Validate checks immutable intent and its independent reservation.

type EffectContinuationAuthority

type EffectContinuationAuthority interface {
	WithEffectContinuationAuthority(context.Context, EffectContinuationRequest, func(EffectContinuationRequest) error) error
	AuthorizeEffectContinuation(context.Context, EffectContinuationRequest, EffectAction) error
}

EffectContinuationAuthority authenticates provider proof and current grants. WithAuthority holds permanent original-worker exclusion and current grant guards through the callback. Authorize must independently permit compensation, verify predecessor proof and enforce any monetary ceiling at the provider. Reconciliation authorizes reads only and never grants replay of a mutation.

type EffectContinuationProof

type EffectContinuationProof struct {
	Mode       string    `json:"mode"`
	Issuer     string    `json:"issuer"`
	Revision   string    `json:"revision"`
	Reference  string    `json:"reference"`
	Digest     string    `json:"digest"`
	ObservedAt time.Time `json:"observed_at"`
	ExpiresAt  time.Time `json:"expires_at"`
}

EffectContinuationProof is a host-authenticated provider attestation. The host must verify the exact predecessor, permanently exclude the original worker, authenticate the stated absence or idempotency guarantee, and enforce the reserved spend ceiling. A digest or model assertion alone is not proof.

type EffectContinuationRequest

type EffectContinuationRequest struct {
	SchemaVersion     int                     `json:"schema_version"`
	ResultID          id.ID                   `json:"result_id"`
	ResultRetention   time.Duration           `json:"result_retention"`
	Original          EffectRequest           `json:"original"`
	Operation         EffectRequest           `json:"operation"`
	Sequence          int                     `json:"sequence"`
	Action            EffectAction            `json:"action"`
	ClaimDigest       string                  `json:"claim_digest"`
	Seal              RunCallSeal             `json:"seal"`
	SnapshotDigest    string                  `json:"snapshot_digest"`
	PredecessorDigest string                  `json:"predecessor_digest"`
	Proof             EffectContinuationProof `json:"proof"`
	Reservation       ReservationRequest      `json:"reservation"`
}

EffectContinuationRequest describes an independently charged external action. Original stays immutable. Operation has no RunCall and cannot reopen a sealed journal; its RunID retains provenance only. Compensation never proves rollback or success of the original task. Sequence and PredecessorDigest fence retries.

func (EffectContinuationRequest) Freeze

Freeze validates and detaches a request without authenticating its proof.

func (EffectContinuationRequest) Key

Key identifies one immutable sequence position in the original operation.

type EffectContinuationResult

type EffectContinuationResult struct {
	RequestDigest string            `json:"request_digest"`
	Evidence      evidence.Ref      `json:"evidence"`
	Receipt       EffectReceipt     `json:"receipt"`
	Settlement    SettlementReceipt `json:"settlement"`
	At            time.Time         `json:"at"`
}

EffectContinuationResult is an observation requiring normal task verification. It is never an acceptance receipt. Unknown billing stays fully charged.

func (EffectContinuationResult) Validate

Validate checks receipt and accounting bindings against the retained admission.

type EffectContinuationStore

type EffectContinuationStore interface {
	AdmitEffectContinuation(context.Context, EffectContinuationRequest) (EffectContinuation, error)
	ListEffectContinuations(context.Context, EffectRequest) ([]EffectContinuation, error)
	GetEffectContinuationResult(context.Context, EffectContinuationRequest) (*EffectContinuationResult, error)
	CompleteEffectContinuation(context.Context, EffectContinuationRequest, EffectReceipt) (EffectContinuationResult, error)
}

EffectContinuationStore atomically reserves shared capacity and exact sequence before dispatch, then stores terminal observation and conservative settlement. Historical admission retries never return Fresh, including lost acknowledgments.

type EffectDiscoveryStore

type EffectDiscoveryStore interface {
	ListEffects(context.Context, EffectListRequest) ([]EffectRecord, error)
}

EffectDiscoveryStore is an optional host-only journal capability. Results include at most Limit records, ordered by operation-key digest, strictly after After. Implementations must validate complete request/receipt bindings and exact context scope. Pages are observations, not an atomic database snapshot.

type EffectExecutor

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

EffectExecutor dispatches an operation once and recovers through read-only reconciliation. It never automatically retries a mutation, including declared idempotent operations. Retrying a request returns its retained receipt or probes the original attempt; unknown outcomes remain reserved indefinitely.

func NewEffectExecutor

func NewEffectExecutor(cfg EffectExecutorConfig) (*EffectExecutor, error)

NewEffectExecutor copies host registrations and rejects ambiguous revisions.

func (*EffectExecutor) ContinueEffect

ContinueEffect admits an independent attempt before any adapter dispatch. Only an acknowledged fresh admission permits invocation. A duplicate or lost acknowledgment requires observation-only recovery. It never resumes the run.

func (*EffectExecutor) Execute

func (e *EffectExecutor) Execute(ctx context.Context, request EffectRequest, args []byte) (EffectReceipt, error)

Execute reserves before dispatch. An error after reservation is uncertain even if no adapter call occurred; recovery must inspect the original operation.

func (*EffectExecutor) Reconcile

func (e *EffectExecutor) Reconcile(ctx context.Context, request EffectRequest) (EffectReceipt, error)

Reconcile recovers an existing operation after a restart or deadline expiry. Fresh host authorization is required. It never creates or dispatches an effect.

func (*EffectExecutor) ReconcileContinuation

ReconcileContinuation observes one retained attempt without dispatching it.

func (*EffectExecutor) RecoverPage

func (e *EffectExecutor) RecoverPage(ctx context.Context, request EffectListRequest) (EffectRecoveryPage, error)

RecoverPage discovers operations from the executor's journal and reconciles each original attempt. The host must authorize exact-scope discovery before calling this internal API. Every operation also requires current authorization through Reconcile. Recovery never dispatches mutations or resumes agent runs.

func (*EffectExecutor) RecoverSealedPage

func (e *EffectExecutor) RecoverSealedPage(ctx context.Context, request EffectRecoveryPageRequest) (EffectRecoveryPage, error)

RecoverSealedPage checks current scan authority and the retained seal before and after reconciliation. The store must implement BoundEffectStore, EffectDiscoveryStore and RunCallSealStore, and every effect writer must honor that seal. Per-operation authorization remains mandatory through Reconcile. Errors return no cursor, although earlier terminal receipts may have committed. Legacy unbound operations are included; terminal status does not establish a task-call binding, successful task acceptance or complete usage accounting.

type EffectExecutorConfig

type EffectExecutorConfig struct {
	Store     EffectStore
	Adapters  []EffectRegistration
	Authorize func(context.Context, EffectRequest, EffectAction) error
	// AuthorizeScan is required by RecoverSealedPage for exact-run discovery.
	AuthorizeScan func(context.Context, RunCallSeal) error
	MaxConcurrent int
}

EffectExecutorConfig has no permissive policy or in-memory storage fallback. Authorize authenticates the current caller, resolves live grants and checks run/assignment ownership. Adapters must enforce those grants at the write.

type EffectListRequest

type EffectListRequest struct {
	RunID id.AgentRunID
	After string
	Limit int
}

EffectListRequest bounds a scan in one exact context scope. After is the SHA-256 digest of the last operation key, not a timestamp. RunID is optional. Scans include terminal records so discovering pending work remains bounded.

func (EffectListRequest) Validate

func (r EffectListRequest) Validate() error

Validate rejects unbounded scans and malformed filters before storage access.

type EffectOutcome

type EffectOutcome string

EffectOutcome distinguishes terminal provider knowledge from ambiguity.

const (
	EffectApplied    EffectOutcome = "applied"
	EffectNotApplied EffectOutcome = "not_applied"
	EffectUnknown    EffectOutcome = "unknown"
)

type EffectReceipt

type EffectReceipt struct {
	SchemaVersion   int           `json:"schema_version"`
	RequestDigest   string        `json:"request_digest"`
	Outcome         EffectOutcome `json:"outcome"`
	ExternalID      string        `json:"external_id,omitempty"`
	ExternalVersion string        `json:"external_version,omitempty"`
	EvidenceRef     string        `json:"evidence_ref"`
}

EffectReceipt is trusted adapter evidence about the exact request. NotApplied must prove the original dispatch cannot later apply, not merely that a read currently finds no object. EvidenceRef identifies retained provider evidence. Applied does not establish task acceptance or correctness of the artifact.

func (EffectReceipt) Validate

func (v EffectReceipt) Validate(r EffectRequest) error

Validate binds terminal knowledge to the complete operation request.

type EffectRecord

type EffectRecord struct {
	Request EffectRequest  `json:"request"`
	Receipt *EffectReceipt `json:"receipt,omitempty"`
}

EffectRecord retains the original operation and optional terminal receipt.

type EffectRecoveryItem

type EffectRecoveryItem struct {
	OperationDigest string               `json:"operation_digest"`
	RunID           id.AgentRunID        `json:"run_id"`
	Status          EffectRecoveryStatus `json:"status"`
	Outcome         EffectOutcome        `json:"outcome,omitempty"`
}

EffectRecoveryItem excludes arguments, authority and provider evidence. Outcome is populated only after an authorized terminal receipt is observed.

type EffectRecoveryPage

type EffectRecoveryPage struct {
	Items     []EffectRecoveryItem `json:"items"`
	NextAfter string               `json:"next_after,omitempty"`
}

EffectRecoveryPage advances past every inspected operation, including denied and unknown operations. Empty NextAfter starts a new scan; callers must revisit earlier pages because new operations may sort before a retained cursor.

type EffectRecoveryPageRequest

type EffectRecoveryPageRequest struct {
	Seal  RunCallSeal
	After string
	Limit int
}

EffectRecoveryPageRequest selects a bounded page from a permanently sealed run. Restart each pass with After empty and revisit uncertain operations.

type EffectRecoveryStatus

type EffectRecoveryStatus string

EffectRecoveryStatus reports observation progress, never task acceptance.

const (
	EffectRecoveryTerminal    EffectRecoveryStatus = "terminal"
	EffectRecoveryUncertain   EffectRecoveryStatus = "uncertain"
	EffectRecoveryUnavailable EffectRecoveryStatus = "unavailable"
)

type EffectReference

type EffectReference struct {
	Tool     string `json:"tool"`
	Revision string `json:"revision"`
}

EffectReference pins a separately authorized compensation handler.

type EffectRegistration

type EffectRegistration struct {
	Requirement EffectRequirement
	Adapter     EffectAdapter
}

EffectRegistration pins trusted behavior to a handler revision.

type EffectRequest

type EffectRequest struct {
	SchemaVersion int               `json:"schema_version"`
	Scope         cortex.Scope      `json:"scope"`
	RunID         id.AgentRunID     `json:"run_id"`
	OperationKey  string            `json:"operation_key"`
	AttemptID     id.ID             `json:"attempt_id"`
	ArgsDigest    string            `json:"args_digest"`
	PrincipalRef  string            `json:"principal_ref"`
	AuthorityRef  string            `json:"authority_ref"`
	Deadline      time.Time         `json:"deadline"`
	Requirement   EffectRequirement `json:"requirement"`
	RunCall       *RunCallRequest   `json:"run_call,omitempty"`
}

EffectRequest is a host-bound logical operation. OperationKey is unique across tools in its exact scope. Retain the entire request, including AttemptID, for retries and worker replacement. Arguments are hashed, not stored in the journal. AuthorityRef identifies current authorization; it is never a bearer credential.

func (EffectRequest) Freeze

func (r EffectRequest) Freeze() (EffectRequest, string, error)

Freeze validates and detaches the request and hashes its canonical encoding. Deadline expiry is checked at dispatch, so expired operations remain readable and can still be reconciled with fresh host authorization.

type EffectRequirement

type EffectRequirement struct {
	Tool                string          `json:"tool"`
	Revision            string          `json:"revision"`
	Class               EffectClass     `json:"class"`
	Retry               RetryPolicy     `json:"retry"`
	IdempotencyRevision string          `json:"idempotency_revision,omitempty"`
	ReconcileRevision   string          `json:"reconcile_revision,omitempty"`
	Compensation        EffectReference `json:"compensation,omitzero"`
}

EffectRequirement pins a host handler's declared behavior. IdempotencyRevision identifies its stable-operation-key contract. ReconcileRevision identifies a host probe for authoritative external state. Neither field executes a probe.

func (EffectRequirement) Validate

func (r EffectRequirement) Validate() error

Validate requires bounded attempts and explicit mutation/recovery contracts.

type EffectStatus

type EffectStatus struct {
	Outcome EffectOutcome
	Receipt *EffectReceipt
}

EffectStatus is a read-only authoritative probe. Unknown carries no receipt.

type EffectStore

type EffectStore interface {
	BeginEffect(context.Context, EffectRequest) (bool, error)
	GetEffect(context.Context, string) (EffectRecord, error)
	CompleteEffect(context.Context, EffectRequest, EffectReceipt) error
}

EffectStore is optional durable effect persistence. BeginEffect returns true only to the successful first insert, never on replay or an uncertain database acknowledgement. Same-key changes conflict. CompleteEffect is immutable and idempotent only for the identical receipt. Every method uses exact context scope. Rows must outlive all possible delivery retries and provider effects. These methods are host infrastructure, not directly exposed to model tools.

type KnownResources

type KnownResources uint8

KnownResources marks dimensions with a trusted usage receipt.

const (
	KnownSteps KnownResources = 1 << iota
	KnownTokens
	KnownToolCalls
	KnownFanOut
	KnownReplans
	KnownMoney
	KnownAll = KnownSteps | KnownTokens | KnownToolCalls | KnownFanOut | KnownReplans | KnownMoney
)

type Limit

type Limit string

Limit identifies which configured allowance prevents dispatch.

const (
	LimitSteps    Limit = "step_limit"
	LimitTokens   Limit = "token_limit"
	LimitTools    Limit = "tool_limit"
	LimitDeadline Limit = "deadline"
)

type ProviderCallOutcome

type ProviderCallOutcome string

ProviderCallOutcome describes terminal provider knowledge. A transient lookup miss is unresolved and cannot be represented as a terminal receipt.

const (
	ProviderCallSucceeded   ProviderCallOutcome = "succeeded"
	ProviderCallFailed      ProviderCallOutcome = "failed"
	ProviderCallNotAccepted ProviderCallOutcome = "not_accepted"
)

type ProviderCallReceipt

type ProviderCallReceipt struct {
	SchemaVersion   int                 `json:"schema_version"`
	RequestDigest   string              `json:"request_digest"`
	Outcome         ProviderCallOutcome `json:"outcome"`
	Provider        string              `json:"provider"`
	AdapterRevision string              `json:"adapter_revision"`
	AccountRef      string              `json:"account_ref"`
	OperationID     string              `json:"operation_id"`
	ProofRef        string              `json:"proof_ref"`
	ProofDigest     string              `json:"proof_digest"`
	ObservedAt      time.Time           `json:"observed_at"`
	ResultDigest    string              `json:"result_digest,omitempty"`
	Usage           ReservationUsage    `json:"usage"`
}

ProviderCallReceipt binds host-authenticated proof to the full frozen journal request. References contain no credentials or result bytes. The host must authenticate provider/account/routing identity against original dispatch evidence, never current agent configuration. NotAccepted proves the original request cannot subsequently be accepted, including delayed delivery. ObservedAt is the host observation time, checked by its authenticator. Usage is authoritative only for marked token/money dimensions. A receipt does not settle reservations, authorize retry or accept a task output.

func (ProviderCallReceipt) Freeze

Freeze checks shape and exact request binding, without authenticating proof. Successful result digests use the original invocation's result encoding.

func (ProviderCallReceipt) ValidateObservation

func (c ProviderCallReceipt) ValidateObservation(record RunCallRecord) error

ValidateObservation rejects contradictions with the current local journal. Call this again before adoption: a local return can arrive after reconciliation. Reported token counts remain observations and need not equal billable usage.

type ProviderCallReceiptStore

type ProviderCallReceiptStore interface {
	RunCallStore
	PutProviderCallReceipt(context.Context, RunCallRequest, ProviderCallReceipt) error
	GetProviderCallReceipt(context.Context, RunCallRequest) (*ProviderCallReceipt, error)
}

ProviderCallReceiptStore retains immutable terminal proof separately from local returns. Get returns nil when the original call exists without proof. Writes require a host authority fence and authenticated proof. Storage checks shape and original request identity, not provider authenticity. Consumers must compare the latest local observation before adoption. Both records survive a disagreement; neither record permits dispatch or releases shared capacity.

type ProviderCallRecoveryAdapter

type ProviderCallRecoveryAdapter interface {
	ReconcileProviderCall(context.Context, RunCallRequest) (ProviderCallReceipt, error)
}

ProviderCallRecoveryAdapter queries retained provider state for one original call. It must never generate, execute, resend or change the provider operation. A lookup miss, partial stream or inconclusive proof returns uncertainty. Implementations must honor cancellation and retain original routing evidence.

type ProviderCallRecoveryFence

type ProviderCallRecoveryFence interface {
	WithProviderCallFence(context.Context, RunCallRequest, func() error) error
}

ProviderCallRecoveryFence holds current host authority through the synchronous commit callback. Its guard must cover revocation and relevant dispatch routing revisions. It does not renew expired execution leases or authorize new calls.

type ProviderReconciler

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

ProviderReconciler authenticates and retains terminal proof for journaled model calls. It exposes no execution path. Callers discover work through bounded RunCallStore pages and authorize any later adoption or settlement separately.

func NewProviderReconciler

func NewProviderReconciler(config ProviderRecoveryConfig) (*ProviderReconciler, error)

NewProviderReconciler defaults to four concurrent operations and thirty seconds per operation, including queue wait. The timeout cannot exceed thirty seconds.

func (*ProviderReconciler) Reconcile

Reconcile queries and authenticates a single original call, or reauthenticates its immutable receipt. Lease expiry never proves an outcome. Errors can follow a durable write; repeating reconciliation reads proof and cannot dispatch.

func (*ProviderReconciler) ReconcilePage

ReconcilePage validates the full page before querying any provider. It requires AuthorizeScan and a RunCallSealStore on the configured receipt store. Every model call uses Reconcile's current authorization and authenticated proof path. Errors return no cursor, although earlier proof writes may have committed. Retrying the same page reauthenticates those receipts without repeating calls. Timeout bounds the whole page including its queue wait. MaxConcurrent bounds pages separately from provider operations so queued pages cannot deadlock calls.

type ProviderRecoveryConfig

type ProviderRecoveryConfig struct {
	Store        ProviderCallReceiptStore
	Adapter      ProviderCallRecoveryAdapter
	Authorize    func(context.Context, RunCallRequest) error
	Authenticate func(context.Context, RunCallRequest, ProviderCallReceipt) error
	Fence        ProviderCallRecoveryFence
	// AuthorizeScan is required only by ReconcilePage. It checks current read
	// and recovery permission for the exact sealed run before and after a page.
	AuthorizeScan func(context.Context, RunCallSeal) error
	Timeout       time.Duration
	MaxConcurrent int
}

ProviderRecoveryConfig supplies mandatory trusted host ports. Authorize checks the current caller before lookup and inside the commit fence. Authenticate verifies terminal proof, original provider/account/routing binding and usage, including when returning stored proof. No default authorizer or verifier exists. Timeout includes waiting for a slot; adapters, stores and guards must honor it.

type ProviderRecoveryPage

type ProviderRecoveryPage struct {
	NextAfter                                string
	Scanned, Terminal, Unresolved, ToolCalls int
}

ProviderRecoveryPage counts observations, not newly committed transitions. Terminal includes authenticated success, failure and non-acceptance. ToolCalls require separate effect recovery. An empty NextAfter ends only this scan pass; it does not establish task success, complete accounting or permission to retry.

type ProviderRecoveryPageRequest

type ProviderRecoveryPageRequest struct {
	Seal  RunCallSeal
	After string
	Limit int
}

ProviderRecoveryPageRequest selects one bounded page in an already sealed journal. The caller starts each pass with After empty and follows NextAfter. Revisit unresolved calls on a new pass; a cursor never proves their completion.

type RecoveredRunCall

type RecoveredRunCall struct {
	Call     RunCallRecord        `json:"call"`
	Provider *ProviderCallReceipt `json:"provider,omitempty"`
}

RecoveredRunCall keeps a local observation and independent provider proof. Missing or contradictory proof is preserved for the adoption policy to reject.

type Reservation

type Reservation struct {
	Request       ReservationRequest `json:"request"`
	RequestDigest string             `json:"request_digest"`
	CreatedAt     time.Time          `json:"created_at"`
	Settlement    *SettlementReceipt `json:"settlement,omitempty"`
}

Reservation retains immutable allocation and optional final accounting.

func (Reservation) Validate

func (r Reservation) Validate() error

Validate checks identity and timestamps without authenticating receipts.

type ReservationKind

type ReservationKind string

ReservationKind distinguishes an executable leaf from delegated capacity.

const (
	ReservationLeaf   ReservationKind = "leaf"
	ReservationBranch ReservationKind = "branch"
)

type ReservationListRequest

type ReservationListRequest struct {
	PlanID id.ID
	After  id.ID
	Limit  int
}

ReservationListRequest bounds discovery for an exact-scope plan account.

type ReservationPolicy

type ReservationPolicy struct {
	SchemaVersion   int          `json:"schema_version"`
	PlanID          id.ID        `json:"plan_id"`
	Scope           cortex.Scope `json:"scope"`
	Limits          Resources    `json:"limits"`
	Deadline        time.Time    `json:"deadline"`
	TokenOnly       bool         `json:"token_only"`
	PricingRevision string       `json:"pricing_revision,omitempty"`
}

ReservationPolicy fixes one shared account for a plan's lifetime. TokenOnly explicitly disables a money ceiling. Monetary bounds require host price data.

func (ReservationPolicy) Admit

Admit checks deadline, policy pins and conservative aggregate capacity.

func (ReservationPolicy) Freeze

Freeze validates and detaches the immutable account policy.

type ReservationRequest

type ReservationRequest struct {
	SchemaVersion   int             `json:"schema_version"`
	ID              id.ID           `json:"id"`
	PlanID          id.ID           `json:"plan_id"`
	PlanDigest      string          `json:"plan_digest"`
	Scope           cortex.Scope    `json:"scope"`
	TaskID          id.ID           `json:"task_id"`
	ParentID        id.ID           `json:"parent_id,omitempty"`
	OwnerRef        string          `json:"owner_ref"`
	Kind            ReservationKind `json:"kind"`
	Allocation      Resources       `json:"allocation"`
	Deadline        time.Time       `json:"deadline"`
	MoneyBound      bool            `json:"money_bound"`
	PricingRevision string          `json:"pricing_revision,omitempty"`
}

ReservationRequest binds capacity to a task and host-owned attempt reference. Branches allocate to children and cannot report their own execution usage.

func (ReservationRequest) Freeze

Freeze validates immutable reservation identity and bounded allocation.

type ReservationUsage

type ReservationUsage struct {
	Actual Resources      `json:"actual"`
	Known  KnownResources `json:"known"`
}

ReservationUsage distinguishes known zero from missing usage.

type Resources

type Resources struct {
	Steps     int64 `json:"steps"`
	Tokens    int64 `json:"tokens"`
	ToolCalls int64 `json:"tool_calls"`
	FanOut    int64 `json:"fan_out"`
	Replans   int64 `json:"replans"`
	USDMicros int64 `json:"usd_micros"`
}

Resources uses explicit nonnegative allowances. Zero permits no consumption, unlike the optional zero limits in a single-run Budget. Money is USD micros.

func SettlementCharge

func SettlementCharge(r ReservationRequest, s Settlement) (Resources, error)

SettlementCharge refunds only known unused leaf capacity. Each reservation consumes at least one fan-out slot, including an attempt that never dispatched.

func (Resources) Add

func (r Resources) Add(other Resources) (Resources, bool)

Add conservatively saturates aggregate overflow. Individual receipts retain their original amounts; Overflow prohibits admission instead of wrapping.

func (Resources) Admit

func (r Resources) Admit(used, want Resources) error

Admit checks a new allocation against charged capacity without overflow.

func (Resources) Covers

func (r Resources) Covers(other Resources) bool

Covers tests every dimension without arithmetic that can overflow.

func (Resources) Max

func (r Resources) Max(other Resources) Resources

Max retains the larger charge in each dimension.

func (Resources) Validate

func (r Resources) Validate() error

Validate refuses negative amounts.

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts    int           `json:"max_attempts"`
	InitialBackoff time.Duration `json:"initial_backoff_ns,omitempty"`
	MaxBackoff     time.Duration `json:"max_backoff_ns,omitempty"`
}

RetryPolicy bounds attempts and backoff. A bound is not permission to retry an unknown effect; reconciliation and current authorization still apply.

type RunCallCompletion

type RunCallCompletion struct {
	SchemaVersion  int    `json:"schema_version"`
	RequestDigest  string `json:"request_digest"`
	ResultDigest   string `json:"result_digest"`
	ReportedTokens int64  `json:"reported_tokens"`
	TokensReported bool   `json:"tokens_reported"`
}

RunCallCompletion records a normal local return. TokensReported distinguishes an observation from missing usage. Neither the count nor ResultDigest proves billable usage, current authority, external effects or task acceptance. Those require the corresponding provider, effect and verification evidence.

func (RunCallCompletion) Validate

func (c RunCallCompletion) Validate(r RunCallRequest) error

Validate checks exact request binding and well-formed usage observations.

type RunCallKind

type RunCallKind string

RunCallKind identifies a locally observed invocation, not an effect class.

const (
	RunCallComplete RunCallKind = "complete"
	RunCallStream   RunCallKind = "stream"
	RunCallTool     RunCallKind = "tool"
)

type RunCallListRequest

type RunCallListRequest struct {
	RunID id.AgentRunID
	After string
	Limit int
}

RunCallListRequest bounds exact-scope discovery for a single run. A new scan revisits earlier pages because concurrent inserts may precede a saved cursor.

func (RunCallListRequest) Validate

func (r RunCallListRequest) Validate() error

Validate rejects missing run identity and unbounded or malformed cursors.

type RunCallRecord

type RunCallRecord struct {
	Request     RunCallRequest     `json:"request"`
	StartedAt   time.Time          `json:"started_at"`
	Completion  *RunCallCompletion `json:"completion,omitempty"`
	CompletedAt time.Time          `json:"completed_at,omitzero"`
}

RunCallRecord preserves a dispatch reservation and optional local return. An absent completion is unresolved, even after the deadline or lease expires.

func (RunCallRecord) Validate

func (r RunCallRecord) Validate() error

Validate checks journal consistency, not permission to reuse an invocation.

type RunCallRequest

type RunCallRequest struct {
	SchemaVersion    int           `json:"schema_version"`
	ID               id.ID         `json:"id"`
	Scope            cortex.Scope  `json:"scope"`
	RunID            id.AgentRunID `json:"run_id"`
	AgentID          id.AgentID    `json:"agent_id"`
	ClaimID          id.ID         `json:"claim_id"`
	ParentRunID      id.AgentRunID `json:"parent_run_id"`
	Kind             RunCallKind   `json:"kind"`
	OperationDigest  string        `json:"operation_digest"`
	RequestDigest    string        `json:"request_digest"`
	PreparedDigest   string        `json:"prepared_digest"`
	AssignmentDigest string        `json:"assignment_digest"`
	Deadline         time.Time     `json:"deadline"`
}

RunCallRequest retains metadata about one exact leased invocation. It contains no prompt, tool arguments or result bytes. OperationDigest identifies the logical slot within RunID; changing ID cannot authorize another dispatch. RequestDigest binds the complete private request accepted by the host lease. These references provide no authority and are not provider idempotency keys.

func RunCallFromContext

func RunCallFromContext(ctx context.Context) (RunCallRequest, bool)

RunCallFromContext retrieves a copy of runtime correlation metadata.

func (RunCallRequest) Freeze

func (r RunCallRequest) Freeze() (RunCallRequest, string, error)

Freeze validates and detaches journal metadata without authorizing execution.

func (RunCallRequest) Key

func (r RunCallRequest) Key() string

Key is the stable journal identity and lexical discovery cursor within scope.

type RunCallSeal

type RunCallSeal struct {
	Request       RunCallSealRequest `json:"request"`
	RequestDigest string             `json:"request_digest"`
	At            time.Time          `json:"at"`
}

RunCallSeal is a permanent admission barrier, not proof of provider completion. Already admitted calls may still finish. Their late returns and external proof remain writable. No closure grants a retry, result acceptance or usage refund.

func (RunCallSeal) Validate

func (s RunCallSeal) Validate() error

Validate checks immutable closure metadata, not host authorization.

type RunCallSealAuthorizer

type RunCallSealAuthorizer interface {
	AuthorizeRunCallSeal(context.Context, RunCallSealRequest) error
}

RunCallSealAuthorizer authenticates the closure actor and current exact-run permission, including on historical retries. Stored references grant no access.

type RunCallSealFence

type RunCallSealFence interface {
	WithRunCallSeal(context.Context, RunCallSealRequest, func(RunCallSealRequest) error) error
}

RunCallSealFence holds current host authority through one synchronous callback. It must not substitute another request. The seal closes journal membership; stopping already admitted external work still requires its call-lease controls.

type RunCallSealRequest

type RunCallSealRequest struct {
	SchemaVersion int           `json:"schema_version"`
	Scope         cortex.Scope  `json:"scope"`
	RunID         id.AgentRunID `json:"run_id"`
	Actor         string        `json:"actor"`
	Reason        string        `json:"reason"`
}

RunCallSealRequest closes admission to one exact run journal. The host authenticates Actor and authorizes the closure under its current authority fence. Closing an empty journal is valid: a delayed worker must not start it.

func (RunCallSealRequest) Freeze

Freeze binds and detaches a bounded journal closure request.

type RunCallSealStore

type RunCallSealStore interface {
	RunCallStore
	SealRunCalls(context.Context, RunCallSealRequest) (RunCallSeal, error)
	GetRunCallSeal(context.Context, id.AgentRunID) (*RunCallSeal, error)
}

RunCallSealStore serializes closure with every call admission in the exact run and scope. After an acknowledged seal, bounded journal scans have stable membership. Historical BeginRunCall attempts also return ErrRunCallsSealed. All writers must implement this protocol; older writers cannot be fenced by it. Reads return nil for unsealed runs. Retain seals at least as long as call rows and possible delayed workers. There is no reopen operation.

type RunCallSealer

type RunCallSealer interface {
	Seal(context.Context, RunCallSealRequest) (RunCallSeal, error)
}

RunCallSealer closes call admission under current host guards. It never settles usage, accepts results or infers that already admitted calls have finished.

func NewRunCallSealer

func NewRunCallSealer(store RunCallSealStore, fence RunCallSealFence, authorizer RunCallSealAuthorizer) (RunCallSealer, error)

NewRunCallSealer requires explicit storage, authority fencing and authorization. Each operation has a thirty-second deadline; all host ports must honor it.

type RunCallStore

type RunCallStore interface {
	BeginRunCall(context.Context, RunCallRequest) (bool, error)
	CompleteRunCall(context.Context, RunCallRequest, RunCallCompletion) error
	GetRunCall(context.Context, id.AgentRunID, string) (RunCallRecord, error)
	ListRunCalls(context.Context, RunCallListRequest) ([]RunCallRecord, error)
}

RunCallStore is an optional durable invocation journal. BeginRunCall returns true only on a confirmed first insert. Identical replay returns false; changed attempts in the same logical slot conflict. Completion is immutable. All reads use exact scope. Hosts authorize discovery and fence current authority before writes. No transaction spans a provider callback. Rows must outlive possible provider effects and retries; missing completion never permits reinvocation.

type RunRecoverySnapshot

type RunRecoverySnapshot struct {
	SchemaVersion int                `json:"schema_version"`
	Seal          RunCallSeal        `json:"seal"`
	Calls         []RecoveredRunCall `json:"calls,omitempty"`
	Effects       []EffectRecord     `json:"effects,omitempty"`
	Digest        string             `json:"digest"`
}

RunRecoverySnapshot pins an exact sealed journal view. Its digest includes every call, local return, provider receipt, effect binding and effect receipt. Shape validation does not prove terminal outcomes, provider authenticity, verifier acceptance, current authority or permission to release capacity.

func SealRunRecoverySnapshot

func SealRunRecoverySnapshot(s RunRecoverySnapshot) (RunRecoverySnapshot, error)

SealRunRecoverySnapshot validates membership, bounds and order, then detaches the entire observation. Legacy unbound effects and unresolved calls stay visible.

func (RunRecoverySnapshot) Validate

func (s RunRecoverySnapshot) Validate() error

Validate checks integrity and complete binding, not readiness for adoption.

type RunRecoverySnapshotStore

type RunRecoverySnapshotStore interface {
	SnapshotRunRecovery(context.Context, RunCallSeal) (RunRecoverySnapshot, error)
}

RunRecoverySnapshotStore reads the entire sealed journal under one admission guard shared by local completions and terminal receipt writers. All writers must implement that protocol. Reads are bounded and exact-scope. The caller authorizes discovery; a snapshot alone never grants adoption or settlement.

type Settlement

type Settlement struct {
	ReservationID id.ID            `json:"reservation_id"`
	RequestDigest string           `json:"request_digest"`
	CloseBranch   bool             `json:"close_branch,omitempty"`
	Usage         ReservationUsage `json:"usage"`
	Receipt       string           `json:"receipt,omitempty"`
	// Minimum retains observed lower bounds when usage is incomplete.
	Minimum *Resources `json:"minimum,omitempty"`
	// Overflow marks unknown dimensions whose observed sum exceeded int64.
	Overflow KnownResources `json:"overflow,omitempty"`
}

Settlement is final host-attributed usage. Unknown dimensions retain their allocation or the attributed minimum, whichever is larger. A branch closes only from its stored child charges, not this usage.

func (Settlement) Freeze

func (s Settlement) Freeze() (Settlement, string, error)

Freeze validates and fingerprints a settlement without trusting its receipt.

type SettlementReceipt

type SettlementReceipt struct {
	Request Settlement `json:"request"`
	Digest  string     `json:"digest"`
	At      time.Time  `json:"at"`
}

SettlementReceipt retains the final accounting request and observation time. Its digest proves integrity only; the host authenticates usage evidence.

type Usage

type Usage struct {
	Steps          int  `json:"steps"`
	Tokens         int  `json:"tokens"`
	ReportedTokens int  `json:"reported_tokens"`
	ToolCalls      int  `json:"tool_calls"`
	Estimated      bool `json:"estimated"`
}

Usage is cumulative. Tokens includes conservative charges for missing usage; ReportedTokens retains the separately observed total.

func (*Usage) ChargeTokens

func (u *Usage) ChargeTokens(reported int, b Budget)

ChargeTokens retains known usage. Unknown or invalid usage consumes all of a configured remaining token allowance, so missing accounting cannot reset it.

Jump to

Keyboard shortcuts

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