Documentation
¶
Overview ¶
Package engine provides the central Cortex agent orchestration coordinator.
Index ¶
- Constants
- Variables
- func DetachTrace(ctx context.Context) context.Context
- func ExecutionProvenanceFromContext(ctx context.Context) (run.ExecutionProvenance, bool)
- type AdaptiveReviewAuthorizer
- type AdaptiveReviewConfig
- type AdaptiveReviewPage
- type AdaptiveReviewResource
- type AdaptiveReviewer
- type AgentReplyRecoveryConfig
- type ContextBudgetConfig
- type EffectRequestResolver
- type Engine
- func (e *Engine) A2A() *a2a.Bus
- func (e *Engine) AgentInbox(ctx context.Context, agentName string, filter a2a.InboxFilter) ([]a2a.InboxItem, error)
- func (e *Engine) AgentReplyRecoveryStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) ArtifactPublicationStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) BuildSystemPrompt(ctx context.Context, ag *agent.Config, overrides *RunOverrides) (string, error)
- func (e *Engine) CancelRun(ctx context.Context, runID id.AgentRunID) error
- func (e *Engine) CheckPreparedBindings(ctx context.Context, p *PreparedAgent) error
- func (e *Engine) CheckPreparedOrchestrationBindings(ctx context.Context, p *PreparedOrchestration) error
- func (e *Engine) CheckPreparedOrchestrationSources(ctx context.Context, p *PreparedOrchestration) (*PreparedSourceCheck, error)
- func (e *Engine) CheckPreparedSources(ctx context.Context, p *PreparedAgent) (*PreparedSourceCheck, error)
- func (e *Engine) ClaimRecoveryStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) ClearConversation(ctx context.Context, agentID id.AgentID, sessionID id.SessionID) error
- func (e *Engine) CloneAgent(ctx context.Context, sourceName, newName string) (*agent.Config, error)
- func (e *Engine) ClonePersona(ctx context.Context, sourceName, newName string) (*persona.Persona, error)
- func (e *Engine) Config() cortex.Config
- func (e *Engine) ContinueRun(ctx context.Context, runID id.AgentRunID) (*run.Run, error)
- func (e *Engine) ContinueRunStream(ctx context.Context, runID id.AgentRunID, events chan<- StreamEvent) (err error)
- func (e *Engine) CoordinationEventStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) CountAgents(ctx context.Context, filter *agent.ListFilter) (int64, error)
- func (e *Engine) CountBehaviors(ctx context.Context, filter *behavior.ListFilter) (int64, error)
- func (e *Engine) CountOrchestrationRuns(ctx context.Context, filter *orchestration.RunListFilter) (int64, error)
- func (e *Engine) CountOrchestrations(ctx context.Context, filter *orchestration.ConfigListFilter) (int64, error)
- func (e *Engine) CountPendingCheckpoints(ctx context.Context, filter *checkpoint.ListFilter) (int64, error)
- func (e *Engine) CountPersonas(ctx context.Context, filter *persona.ListFilter) (int64, error)
- func (e *Engine) CountRuns(ctx context.Context, filter *run.ListFilter) (int64, error)
- func (e *Engine) CountSkills(ctx context.Context, filter *skill.ListFilter) (int64, error)
- func (e *Engine) CountTraits(ctx context.Context, filter *trait.ListFilter) (int64, error)
- func (e *Engine) CreateAgent(ctx context.Context, config *agent.Config) error
- func (e *Engine) CreateBehavior(ctx context.Context, b *behavior.Behavior) error
- func (e *Engine) CreateOrchestration(ctx context.Context, c *orchestration.Config) error
- func (e *Engine) CreatePersona(ctx context.Context, p *persona.Persona) error
- func (e *Engine) CreateRun(ctx context.Context, r *run.Run) error
- func (e *Engine) CreateSkill(ctx context.Context, s *skill.Skill) error
- func (e *Engine) CreateTrait(ctx context.Context, t *trait.Trait) error
- func (e *Engine) DecideCheckpoint(ctx context.Context, checkpointID id.CheckpointID, d checkpoint.Decision) error
- func (e *Engine) DeleteAgent(ctx context.Context, agentID id.AgentID) error
- func (e *Engine) DeleteBehavior(ctx context.Context, behaviorID id.BehaviorID) error
- func (e *Engine) DeleteOrchestration(ctx context.Context, orchID id.OrchestrationConfigID) error
- func (e *Engine) DeletePersona(ctx context.Context, personaID id.PersonaID) error
- func (e *Engine) DeleteSkill(ctx context.Context, skillID id.SkillID) error
- func (e *Engine) DeleteTrait(ctx context.Context, traitID id.TraitID) error
- func (e *Engine) Dispatch(ctx context.Context, name, arguments string) string
- func (e *Engine) EffectContinuationStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) EffectRecoveryStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) Extensions() *plugin.Registry
- func (e *Engine) GetAgent(ctx context.Context, agentID id.AgentID) (*agent.Config, error)
- func (e *Engine) GetAgentByName(ctx context.Context, name string) (*agent.Config, error)
- func (e *Engine) GetBehavior(ctx context.Context, behaviorID id.BehaviorID) (*behavior.Behavior, error)
- func (e *Engine) GetBehaviorByName(ctx context.Context, name string) (*behavior.Behavior, error)
- func (e *Engine) GetCheckpoint(ctx context.Context, cpID id.CheckpointID) (*checkpoint.Checkpoint, error)
- func (e *Engine) GetConversation(ctx context.Context, convID id.ConversationID) (*a2a.Conversation, error)
- func (e *Engine) GetOrchestration(ctx context.Context, orchID id.OrchestrationConfigID) (*orchestration.Config, error)
- func (e *Engine) GetOrchestrationByName(ctx context.Context, name string) (*orchestration.Config, error)
- func (e *Engine) GetOrchestrationRun(ctx context.Context, runID id.OrchestrationID) (*orchestration.Run, error)
- func (e *Engine) GetPersona(ctx context.Context, personaID id.PersonaID) (*persona.Persona, error)
- func (e *Engine) GetPersonaByName(ctx context.Context, name string) (*persona.Persona, error)
- func (e *Engine) GetRun(ctx context.Context, runID id.AgentRunID) (*run.Run, error)
- func (e *Engine) GetSkill(ctx context.Context, skillID id.SkillID) (*skill.Skill, error)
- func (e *Engine) GetSkillByName(ctx context.Context, name string) (*skill.Skill, error)
- func (e *Engine) GetTrait(ctx context.Context, traitID id.TraitID) (*trait.Trait, error)
- func (e *Engine) GetTraitByName(ctx context.Context, name string) (*trait.Trait, error)
- func (e *Engine) HasToolAuthorizer() bool
- func (e *Engine) Health(ctx context.Context) error
- func (e *Engine) InterveneReflection(ctx context.Context, runID id.AgentRunID, source cognitive.ContextSource) (cognitive.ReflectionReceipt, error)
- func (e *Engine) Knowledge() knowledge.Provider
- func (e *Engine) LLM() llm.Client
- func (e *Engine) ListAgents(ctx context.Context, filter *agent.ListFilter) ([]*agent.Config, error)
- func (e *Engine) ListBehaviors(ctx context.Context, filter *behavior.ListFilter) ([]*behavior.Behavior, error)
- func (e *Engine) ListConversations(ctx context.Context, filter *a2a.ConversationListFilter) ([]*a2a.Conversation, error)
- func (e *Engine) ListMessages(ctx context.Context, filter *a2a.MessageListFilter) ([]*a2a.Envelope, error)
- func (e *Engine) ListOrchestrationRuns(ctx context.Context, filter *orchestration.RunListFilter) ([]*orchestration.Run, error)
- func (e *Engine) ListOrchestrations(ctx context.Context, filter *orchestration.ConfigListFilter) ([]*orchestration.Config, error)
- func (e *Engine) ListPendingCheckpoints(ctx context.Context, filter *checkpoint.ListFilter) ([]*checkpoint.Checkpoint, error)
- func (e *Engine) ListPersonas(ctx context.Context, filter *persona.ListFilter) ([]*persona.Persona, error)
- func (e *Engine) ListRuns(ctx context.Context, filter *run.ListFilter) ([]*run.Run, error)
- func (e *Engine) ListSkills(ctx context.Context, filter *skill.ListFilter) ([]*skill.Skill, error)
- func (e *Engine) ListSteps(ctx context.Context, runID id.AgentRunID) ([]*run.Step, error)
- func (e *Engine) ListToolCalls(ctx context.Context, stepID id.StepID) ([]*run.ToolCall, error)
- func (e *Engine) ListTraits(ctx context.Context, filter *trait.ListFilter) ([]*trait.Trait, error)
- func (e *Engine) LoadConversation(ctx context.Context, agentID id.AgentID, sessionID id.SessionID, limit int) ([]memory.Message, error)
- func (e *Engine) NewPlanReplanRuntime(source PlanReplanInputSource) (coordination.PlanReplanRuntime, error)
- func (e *Engine) NewResumeCloser(fence suspension.ResumeClosureFence, ...) (suspension.ResumeCloser, error)
- func (e *Engine) NewRunCallSealer(fence execution.RunCallSealFence, authorizer execution.RunCallSealAuthorizer) (execution.RunCallSealer, error)
- func (e *Engine) NewTaskReviewRuntime(c TaskReviewRuntimeConfig) (coordination.TaskCompletionReviewer, error)
- func (e *Engine) NewTaskWorker(config TaskWorkerConfig) (coordination.ClaimedTaskWorker, error)
- func (e *Engine) ObservePreparedRecipient(ctx context.Context, req a2a.RecipientRequest, ...) (a2a.RecipientObservation, error)
- func (e *Engine) OrchestrationExpiryStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) OrchestrationRecoveryStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) PendingVerificationTools(ctx context.Context, runID id.AgentRunID) ([]suspension.PendingCall, error)
- func (e *Engine) PlanReplanningStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) PrepareAgent(ctx context.Context, agentID id.AgentID, overrides *RunOverrides) (*PreparedAgent, error)
- func (e *Engine) PrepareOrchestration(ctx context.Context, key id.OrchestrationConfigID) (*PreparedOrchestration, error)
- func (e *Engine) PrepareOrchestrationWithBudgets(ctx context.Context, key id.OrchestrationConfigID, ...) (*PreparedOrchestration, error)
- func (e *Engine) PrepareTaskRun(ctx context.Context, p *PreparedAgent, input string, ...) (coordination.TaskRunRequest, error)
- func (e *Engine) ProvideResults(ctx context.Context, runID id.AgentRunID, in ResumeInput) error
- func (e *Engine) ProviderRecoveryStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) PublicEventReplayAvailable() bool
- func (e *Engine) ReadPublicEvents(ctx context.Context, request event.ReadRequest) (event.Page, error)
- func (e *Engine) ReadResultContent(ctx context.Context, request verification.ResultContentRequest) (verification.PublishedResult, error)
- func (e *Engine) RecoverAgentReply(ctx context.Context, runID id.AgentRunID, key id.SuspensionID, ...) (*run.Run, error)
- func (e *Engine) RecoverVerificationPage(ctx context.Context, request VerificationRecoveryRequest) (VerificationRecoveryPage, error)
- func (e *Engine) ResolveCheckpoint(ctx context.Context, cpID id.CheckpointID, decision checkpoint.Decision) error
- func (e *Engine) ResultContentAvailable() bool
- func (e *Engine) Resume(ctx context.Context, runID id.AgentRunID, in ResumeInput) (*run.Run, error)
- func (e *Engine) ResumePreparedOrchestration(ctx context.Context, team id.OrchestrationID) (rec *orchestration.Run, err error)
- func (e *Engine) ResumeStream(ctx context.Context, runID id.AgentRunID, in ResumeInput, ...) (err error)
- func (e *Engine) RunAgent(ctx context.Context, agentName, input string, overrides *RunOverrides) (r *run.Run, err error)
- func (e *Engine) RunConcurrency() int
- func (e *Engine) RunOrchestration(ctx context.Context, name, input string) (*orchestration.Run, error)
- func (e *Engine) RunPrepared(ctx context.Context, p *PreparedAgent, input string, opts PreparedRunOptions) (r *run.Run, err error)
- func (e *Engine) RunPreparedOrchestration(ctx context.Context, p *PreparedOrchestration, input string, ...) (rec *orchestration.Run, err error)
- func (e *Engine) RunPreparedTask(ctx context.Context, p *PreparedAgent, request coordination.TaskRunRequest) (r *run.Run, err error)
- func (e *Engine) RunVerificationRecovery(ctx context.Context, config VerificationRecoveryLoop) error
- func (e *Engine) RuntimeCapabilities() RuntimeCapabilities
- func (e *Engine) Safety() safety.Scanner
- func (e *Engine) SendMessage(ctx context.Context, params a2a.SendParams) (*a2a.SendResult, error)
- func (e *Engine) Start(ctx context.Context) error
- func (e *Engine) Stop(ctx context.Context) error
- func (e *Engine) Store() store.Store
- func (e *Engine) StreamAgent(ctx context.Context, agentName, input string, overrides *RunOverrides, ...) (err error)
- func (e *Engine) StreamPrepared(ctx context.Context, p *PreparedAgent, input string, opts PreparedRunOptions, ...) (err error)
- func (e *Engine) StreamPreparedTask(ctx context.Context, p *PreparedAgent, request coordination.TaskRunRequest, ...) (err error)
- func (e *Engine) TaskAdoptionStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) TaskCompletionStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) TaskRetirementStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) TaskSchedulingStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) TaskSettlementStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) ToolRetrySafe(name string) bool
- func (e *Engine) Tools() []ToolInfo
- func (e *Engine) UpdateAgent(ctx context.Context, config *agent.Config) error
- func (e *Engine) UpdateBehavior(ctx context.Context, b *behavior.Behavior) error
- func (e *Engine) UpdateConfig(update cortex.Config) cortex.Config
- func (e *Engine) UpdateOrchestration(ctx context.Context, c *orchestration.Config) error
- func (e *Engine) UpdatePersona(ctx context.Context, p *persona.Persona) error
- func (e *Engine) UpdateRun(ctx context.Context, r *run.Run) error
- func (e *Engine) UpdateSkill(ctx context.Context, s *skill.Skill) error
- func (e *Engine) UpdateTrait(ctx context.Context, t *trait.Trait) error
- func (e *Engine) VerificationRecoveryStatus() (coordination.TaskServiceStatus, bool)
- func (e *Engine) VerifyRun(ctx context.Context, request VerifyRunRequest) (VerificationRunResult, error)
- func (e *Engine) VisibleTools(ctx context.Context, agentID id.AgentID) ([]llm.Tool, error)
- func (e *Engine) WorkerID() string
- type ExternalToolOption
- type OperationalAwarenessConfig
- type OperationalCalibrationObservation
- type OperationalCalibrationProvider
- type OperationalCalibrationRequest
- type Option
- func WithA2A(opts a2a.Options) Option
- func WithA2AHandoffHandler(handler a2a.HandoffHandler) Option
- func WithAgentReplyGrace(d time.Duration) Option
- func WithAgentReplyRecovery(config AgentReplyRecoveryConfig) Option
- func WithArtifactPublication(config coordination.ArtifactPublicationConfig) Option
- func WithAtomicPreparation() Option
- func WithClaimRecovery(config coordination.ClaimRecoveryConfig) Option
- func WithConfig(cfg cortex.Config) Option
- func WithContextBudget(config ContextBudgetConfig) Option
- func WithCoordinationEvents(config coordination.EventServiceConfig) Option
- func WithEffectContinuation(config coordination.EffectContinuationServiceConfig) Option
- func WithEffectRecovery(config coordination.EffectRecoveryServiceConfig) Option
- func WithExtension(ext plugin.Extension) Option
- func WithExternalTool(def llm.Tool, opts ...ExternalToolOption) Option
- func WithKnowledge(provider knowledge.Provider) Option
- func WithLLM(client llm.Client) Option
- func WithLogger(l log.Logger) Option
- func WithMetrics(m gometrics.Metrics) Option
- func WithModelRevision(model, revision string) Option
- func WithOperationalAwareness(config ...OperationalAwarenessConfig) Option
- func WithOrchestrationExpiry(config coordination.OrchestrationExpiryConfig) Option
- func WithOrchestrationRecovery(config OrchestrationRecoveryConfig) Option
- func WithPlanReplanning(config coordination.PlanReplanServiceConfig) Option
- func WithPreparedTeamMessaging(config PreparedTeamMessagingConfig) Option
- func WithPrincipalCodec(c cortex.PrincipalCodec) Option
- func WithProviderRecovery(config coordination.ProviderRecoveryServiceConfig) Option
- func WithPublicEventRecording() Option
- func WithPublicEventReplay(authorizer event.Authorizer) Option
- func WithPublicationGate(gate safety.PublicationGate) Option
- func WithPublicationPolicy(policy safety.Policy) Option
- func WithReadyRenotify(d time.Duration) Option
- func WithReclaimLimit(n int) Option
- func WithReflection(config ReflectionConfig) Option
- func WithRejectionsReturnToModel() Option
- func WithRequiredVerification(config RequiredVerificationConfig) Option
- func WithResultContent(config ResultContentConfig) Option
- func WithRunConcurrency(n int) Option
- func WithRunLease(ttl time.Duration) Option
- func WithSafety(scanner safety.Scanner) Option
- func WithStore(s store.Store) Option
- func WithSuspensionSweepInterval(d time.Duration) Option
- func WithSuspensionSweepLimit(n int) Option
- func WithSuspensionTTL(d time.Duration) Option
- func WithTaskAdoption(config coordination.TaskAdoptionServiceConfig) Option
- func WithTaskCallGuard(guard TaskCallGuard) Option
- func WithTaskCompletion(config coordination.TaskCompletionServiceConfig) Option
- func WithTaskRetirement(config coordination.TaskRetirementServiceConfig) Option
- func WithTaskRunAdmitter(admitter coordination.TaskRunAdmitter) Option
- func WithTaskScheduling(config TaskSchedulingConfig) Option
- func WithTaskSettlement(config coordination.TaskSettlementServiceConfig) Option
- func WithTool(def llm.Tool, h ToolHandler) Option
- func WithToolAuthorizer(a cortex.ToolAuthorizer) Option
- func WithToolRetrySafe(names ...string) Option
- func WithToolRevision(name, revision string) Option
- func WithVerificationRecovery(config VerificationRecoveryConfig) Option
- func WithVerificationWorker(config VerificationWorkerConfig) Option
- func WithWorkerID(id string) Option
- type OrchestrationRecoveryConfig
- type PlanReplanInputSource
- type PreparedAgent
- type PreparedConfig
- type PreparedEdits
- type PreparedOrchestration
- func (p *PreparedOrchestration) Derive(edits map[string]PreparedEdits) (*PreparedOrchestration, error)
- func (p *PreparedOrchestration) Digest() string
- func (p *PreparedOrchestration) Inspect() (PreparedOrchestrationView, error)
- func (p PreparedOrchestration) MarshalJSON() ([]byte, error)
- func (p *PreparedOrchestration) UnmarshalJSON(data []byte) error
- type PreparedOrchestrationView
- type PreparedRunOptions
- type PreparedSourceCheck
- type PreparedStartError
- type PreparedTaskRunOptions
- type PreparedTeamMessagingConfig
- type PreparedView
- type ReflectionAuthorizer
- type ReflectionConfig
- type ReflectionFence
- type ReflectionObservationInput
- type ReflectionObserver
- type ReflectionReplanSource
- type ReflectionReview
- type RequiredVerificationConfig
- type ResultContentConfig
- type ResumeInput
- type RunOverrides
- type RuntimeCapabilities
- type StreamEvent
- type StreamEventType
- type TaskCallGuard
- type TaskCallKind
- type TaskCallLease
- type TaskCallRequest
- type TaskReviewAction
- type TaskReviewAuthorizer
- type TaskReviewFence
- type TaskReviewRuntimeConfig
- type TaskReviewWork
- type TaskReviewWorkResolver
- type TaskSchedulingConfig
- type TaskWork
- type TaskWorkResolver
- type TaskWorkerConfig
- type ToolHandler
- type ToolHandoffAuthorizer
- type ToolInfo
- type ToolKind
- type ToolResult
- type VerificationIntentBuilder
- type VerificationIntentInput
- type VerificationRecoveryConfig
- type VerificationRecoveryItem
- type VerificationRecoveryLoop
- type VerificationRecoveryPage
- type VerificationRecoveryRequest
- type VerificationRecoveryStatus
- type VerificationRunResult
- type VerificationWorkerConfig
- type VerifyRunRequest
Examples ¶
Constants ¶
const ToolOperationalCapabilities = "cortex_capabilities"
ToolOperationalCapabilities names the opt-in operational inspection tool.
Variables ¶
var ErrNoA2A = errors.New("cortex: agent-to-agent messaging is not configured")
ErrNoA2A is returned when a caller reaches for messaging on an engine that was never configured with WithA2A. It is distinct from ErrNoStore: the store may be perfectly fine and messaging simply switched off.
var ErrNotAgentReplyResumable = errors.New("cortex: run is waiting on an agent reply")
ErrNotAgentReplyResumable is returned when something other than the messaging bus tries to answer a run that is waiting on a peer agent.
Functions ¶
func DetachTrace ¶
DetachTrace returns ctx for a run that outlives the request or start hook that launched it. The run agent span started from it is a new root that links to the span ctx carried, rather than a child that keeps running after its parent has ended. Values and cancellation are kept.
The dashboard's live runs use it: they go on for minutes after the command that started them has returned.
func ExecutionProvenanceFromContext ¶
func ExecutionProvenanceFromContext(ctx context.Context) (run.ExecutionProvenance, bool)
ExecutionProvenanceFromContext returns trusted execution identity for adapters and hooks. The copy prevents a consumer from changing another observer's view.
Types ¶
type AdaptiveReviewAuthorizer ¶
type AdaptiveReviewAuthorizer interface {
AuthorizeAdaptiveReview(context.Context, AdaptiveReviewResource) error
}
AdaptiveReviewAuthorizer checks current run and source disclosure grants. Historical review does not require adaptation to remain enabled.
type AdaptiveReviewConfig ¶
type AdaptiveReviewConfig struct {
Store store.Store
Evidence evidence.Repository
Authority AdaptiveReviewAuthorizer
}
AdaptiveReviewConfig supplies durable history and current disclosure authority.
type AdaptiveReviewPage ¶
type AdaptiveReviewPage struct {
Items []ReflectionReview `json:"items"`
After int64 `json:"after,omitempty"`
Reliability cognitive.ReliabilityMeasurement `json:"reliability"`
}
AdaptiveReviewPage is a bounded chronological window, with unknown reliability unless a separate authenticated calibration measurement is available.
type AdaptiveReviewResource ¶
type AdaptiveReviewResource struct {
RunID id.AgentRunID
Scope cortex.Scope
References []evidence.Ref
}
AdaptiveReviewResource asks the host to authorize historical disclosure. References include source grants and sensitivity, not merely a dashboard role.
type AdaptiveReviewer ¶
type AdaptiveReviewer struct {
// contains filtered or unexported fields
}
AdaptiveReviewer reads historical observations. It cannot dispatch decisions.
func NewAdaptiveReviewer ¶
func NewAdaptiveReviewer(config AdaptiveReviewConfig) (*AdaptiveReviewer, error)
NewAdaptiveReviewer is independent of runtime adaptation and worker lifecycle.
func (*AdaptiveReviewer) ReviewRun ¶
func (r *AdaptiveReviewer) ReviewRun(ctx context.Context, key id.AgentRunID, after int64, limit int) (AdaptiveReviewPage, error)
ReviewRun checks current grants before lookup and again after evidence access. Deleted evidence hides source content while retaining the decision metadata.
type AgentReplyRecoveryConfig ¶
type AgentReplyRecoveryConfig struct {
Service coordination.AgentReplyRecoveryConfig
Authorize func(context.Context, id.AgentRunID) error
}
AgentReplyRecoveryConfig installs current host authority for discovered runs. Leave Service.Recoverer unset. Authorize runs before private reads, admission, start and every provider/tool dispatch, with the exact run scope on context.
type ContextBudgetConfig ¶
type ContextBudgetConfig struct {
Policy cognitive.ContextPolicy
CountTokens func(context.Context, *llm.Request) (int, error)
OptionalHistory func(context.Context, cortex.Subject, [][]llm.Message) ([]int, error)
}
ContextBudgetConfig installs trusted context counting and optional-history classification. Policy.Revision covers classification semantics; CounterRevision covers provider framing/tokenization. Change the revision when either changes. CountTokens counts input tokens for the complete request, excluding output. OptionalHistory receives detached chronological turns and returns optional turn indices. Nil pins all history. Never derive these permissions from model text.
type EffectRequestResolver ¶
type EffectRequestResolver func(context.Context, cortex.Invocation) (execution.EffectRequest, error)
EffectRequestResolver returns a retained host operation for an invocation. The host owns the stable operation-to-run mapping and original attempt ID. Resolve must return the same complete request across transport retries and worker replacement. A model call ID is correlation data, not authorization or proof of a new logical operation. Do not mint a replacement key after an uncertain outcome. Resolve current identity through the executor's authorizer.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the central coordinator for the Cortex agent system.
func (*Engine) A2A ¶
A2A returns the message bus, or nil when messaging is off. A host needs it to inject a message from outside a run: an operator answering an agent, or an HTTP handler carrying one in.
func (*Engine) AgentInbox ¶
func (e *Engine) AgentInbox(ctx context.Context, agentName string, filter a2a.InboxFilter) ([]a2a.InboxItem, error)
AgentInbox returns an agent's delivered messages.
It goes through the bus rather than the store because reading an inbox marks what it returns as read, and that is the bus's rule rather than a storage detail.
func (*Engine) AgentReplyRecoveryStatus ¶
func (e *Engine) AgentReplyRecoveryStatus() (coordination.TaskServiceStatus, bool)
AgentReplyRecoveryStatus reports configuration and local lifecycle counters.
func (*Engine) ArtifactPublicationStatus ¶
func (e *Engine) ArtifactPublicationStatus() (coordination.TaskServiceStatus, bool)
ArtifactPublicationStatus reports bounded publication counters and configuration.
func (*Engine) BuildSystemPrompt ¶
func (e *Engine) BuildSystemPrompt(ctx context.Context, ag *agent.Config, overrides *RunOverrides) (string, error)
BuildSystemPrompt assembles the full system prompt for one run.
It is a pipeline. Collect the sections the agent, its persona, its skills, the knowledge those skills reference and its traits produce; walk the run scope's ancestry and apply the overlay found at each rung, broadest first; assemble the result in Order.
Persona, skill and trait lookups are scope-guarded: they resolve against cortex.ScopeFromContext(ctx), the same as the agent itself. A requested-but-unresolved persona, skill or trait fails the whole call loudly instead of dropping its fragment, because swallowing that error would let an agent quietly stop being itself with no signal anywhere. Section collection returns those errors rather than logging past them.
func (*Engine) CancelRun ¶
CancelRun ends a run at an operator's request, and it is the only way a host should end one: a plain UpdateRun to cancelled is the fourth writer to a paused run, and the other three go through a claim for a reason.
A paused run is cancelled through ClaimSuspension, the same atomic paused-to-running transition a resume, a rejected checkpoint and the expiry sweep all take. Without it, cancel read a paused run and wrote unconditionally, so a resume that had already claimed the run got its state stomped to cancelled and then wrote its own terminal state back over the cancel a moment later. The operator was told the run was cancelled and the run went on to complete. Losing the claim is reported as cortex.ErrNotSuspended rather than worked around, because somebody else is already moving this run.
The claim also hands back the row, which is what lets cancel clean up after itself: the suspension is dropped, and any checkpoint the pause opened is resolved, so nobody is left holding a decision on a run that has ended.
A ready or reclaimable run is claimed with ClaimContinuation, the same transition ContinueRun takes, and then ended exactly like a paused one.
A run that is merely running is cancelled as before, with no claim to take: there is no suspension behind it, and a running run has no engine-side transition to race with that a store predicate could settle.
func (*Engine) CheckPreparedBindings ¶
func (e *Engine) CheckPreparedBindings(ctx context.Context, p *PreparedAgent) error
CheckPreparedBindings requires current host-declared model and selected-tool revisions to match a prepared agent. Selected tools must have unambiguous schemas and executable implementations; caller-executed external declarations alone cannot satisfy this check. Derived tool descriptions may differ.
This point-in-time check performs no source, model, scanner or tool calls and grants no execution authority. It does not attest remote provider identity, external knowledge, host policy or grants. Normal prepared execution still permits unpinned bindings; callers opt into this stricter compatibility check.
func (*Engine) CheckPreparedOrchestrationBindings ¶
func (e *Engine) CheckPreparedOrchestrationBindings(ctx context.Context, p *PreparedOrchestration) error
CheckPreparedOrchestrationBindings checks current host-declared model and tool revisions for the complete frozen roster, including auxiliary agents. It uses CheckPreparedBindings without refreshing stored sources or invoking providers. This point-in-time observation is separate from the atomic source check and does not grant execution authority or authenticate remote implementations.
func (*Engine) CheckPreparedOrchestrationSources ¶
func (e *Engine) CheckPreparedOrchestrationSources(ctx context.Context, p *PreparedOrchestration) (*PreparedSourceCheck, error)
CheckPreparedOrchestrationSources compares the original configuration and every participant's stored read set in one read-only snapshot. Derived edits retain their source identity. SourceCount includes the configuration and each participant's read set, including shared sources read for several participants. This observation grants no execution authority and performs no provider, tool or publication calls. Missing snapshot capabilities never fall back to reads.
func (*Engine) CheckPreparedSources ¶
func (e *Engine) CheckPreparedSources(ctx context.Context, p *PreparedAgent) (*PreparedSourceCheck, error)
CheckPreparedSources compares a frozen source read set with current records in one read-only store snapshot. Derived prompt edits do not change that read set. Missing sources or changed digests return ErrPreparationConflict. Stores must support PreparationSnapshotter; there is no fallback to independent reads. This point-in-time check performs no model, scanner, tool, or execution calls.
func (*Engine) ClaimRecoveryStatus ¶
func (e *Engine) ClaimRecoveryStatus() (coordination.TaskServiceStatus, bool)
ClaimRecoveryStatus reports local counters and whether recovery was configured.
func (*Engine) ClearConversation ¶
func (*Engine) CloneAgent ¶
CloneAgent creates an independent copy of an existing agent in the caller's scope.
func (*Engine) ClonePersona ¶
func (e *Engine) ClonePersona(ctx context.Context, sourceName, newName string) (*persona.Persona, error)
ClonePersona creates an independent copy of an existing persona in the caller's scope.
func (*Engine) Config ¶
Config returns the engine configuration. RunConcurrency is the cap the engine applies (WithRunConcurrency), zero for none.
func (*Engine) ContinueRun ¶ added in v1.10.0
ContinueRun runs a ready or reclaimable run in the caller's goroutine under the run's original principal.
It is the job half of DecideCheckpoint and ProvideResults. It reads the run, runs the pre-claim checks a resume runs, restores the run's principal, claims the run, and then executes the recorded decision or results and the rest of the loop, exactly as Resume would. ctx must carry the run's own scope, which is the scope on the RunReady hook's ctx.
Anything refused before the claim for now leaves the run ready for the next attempt, including a principal that cannot be decoded right now. A principal that is revoked fails the run, and so does a check no later attempt can pass (its stored answer does not fit the pause, say), which also closes its checkpoint.
A reclaimable run, or a running run whose lease has lapsed (which this call marks reclaimable itself), continues from its last saved step: see claimReclaimed. It fails with cortex.ErrReclaimLimit once reclaimed more often than WithReclaimLimit, with cortex.ErrRunNotRecoverable when it left nothing to continue from, and stops with an error matching cortex.ErrEffectUncertain when a call it had handed to a tool that is not retry-safe has no recorded outcome. A run claimed for a cancel or an expiry whose write was lost is ended that way instead, and comes back with cortex.ErrRunAlreadyDone or the expiry's error.
A run in any other state is not continued. ErrRunNotContinuable covers every such refusal, and the error also matches the specific case: cortex.ErrRunLeased for a running run under a live lease, and cortex.ErrRunAlreadyDone, returned with the run, for one that has ended. Two callers continuing the same run: one runs it, the other is refused.
A store without run.ContinuationStore returns cortex.ErrContinuationUnavailable.
func (*Engine) ContinueRunStream ¶ added in v1.10.0
func (e *Engine) ContinueRunStream(ctx context.Context, runID id.AgentRunID, events chan<- StreamEvent) (err error)
ContinueRunStream is ContinueRun over the streaming loop. It closes events when execution completes, like ResumeStream, and the first event is run_started with resumed set.
func (*Engine) CoordinationEventStatus ¶
func (e *Engine) CoordinationEventStatus() (coordination.TaskServiceStatus, bool)
CoordinationEventStatus reports local delivery counters and configuration.
func (*Engine) CountAgents ¶
func (*Engine) CountBehaviors ¶
func (*Engine) CountOrchestrationRuns ¶
func (e *Engine) CountOrchestrationRuns(ctx context.Context, filter *orchestration.RunListFilter) (int64, error)
CountOrchestrationRuns counts orchestration run records.
func (*Engine) CountOrchestrations ¶
func (e *Engine) CountOrchestrations(ctx context.Context, filter *orchestration.ConfigListFilter) (int64, error)
CountOrchestrations counts orchestration configs.
func (*Engine) CountPendingCheckpoints ¶
func (e *Engine) CountPendingCheckpoints(ctx context.Context, filter *checkpoint.ListFilter) (int64, error)
func (*Engine) CountPersonas ¶
func (*Engine) CountSkills ¶
func (*Engine) CountTraits ¶
func (*Engine) CreateAgent ¶
func (*Engine) CreateBehavior ¶
func (*Engine) CreateOrchestration ¶
CreateOrchestration stores a new orchestration config.
func (*Engine) CreatePersona ¶
func (*Engine) CreateRun ¶
CreateRun creates a run record directly (for external use). A run that carries no principal bytes gets the context's, encoded the same way the engine's own runs are.
func (*Engine) CreateSkill ¶
func (*Engine) CreateTrait ¶
func (*Engine) DecideCheckpoint ¶ added in v1.10.0
func (e *Engine) DecideCheckpoint(ctx context.Context, checkpointID id.CheckpointID, d checkpoint.Decision) error
DecideCheckpoint records d and, for an approval, marks the run ready. It never calls the model.
It is the half of ResolveCheckpoint a request handler can afford: it returns once the decision is written, and the run waits in run.StateReady for ContinueRun, which a host usually calls from a background job on any replica after plugin.RunReady fires.
For a checkpoint the loop opened, an approval runs every check a synchronous resume would run before anything moves, then marks the run ready with an instruction to execute each pending call, records the decision, and fires CheckpointResolved and RunReady. The run is marked ready before the decision is recorded, so the ready state never points at a decision nobody can see; if recording fails, repeating the same decision finishes the job and the run continues once. A suspension past its deadline is refused with cortex.ErrSuspensionExpired and the run is left for the expiry sweep.
A rejection fails the run with the decider's reason, as it always has. With WithRejectionsReturnToModel it is handled like an approval instead: each pending call is answered "rejected by <DecidedBy>: <Reason>", and the run is marked ready to carry that back to the model.
A checkpoint a host wrote itself is only recorded. A checkpoint that is no longer pending is cortex.ErrInvalidState. ErrInvalidState also means "already being acted on": a decider who repeats its own approval in the moment between a job claiming the run and that job recording the decision is refused with it too, though the approval stands and the run is carrying it out. Read the checkpoint to see the record. A store without run.ContinuationStore returns cortex.ErrContinuationUnavailable; use ResolveCheckpoint there.
func (*Engine) DeleteAgent ¶
func (*Engine) DeleteBehavior ¶
func (*Engine) DeleteOrchestration ¶
DeleteOrchestration removes an orchestration config.
func (*Engine) DeletePersona ¶
func (*Engine) DeleteSkill ¶
func (*Engine) DeleteTrait ¶
func (*Engine) Dispatch ¶
Dispatch executes a registered or built-in tool by name and returns its approved result string. It is the same path the ReAct loop uses (executeTool), exposed for hosts and tests that drive tools directly. The subject carries whatever scope and principal are on ctx — a direct Dispatch call has no agent or run of its own, so an authorizer keyed on those will see them zero-valued.
func (*Engine) EffectContinuationStatus ¶
func (e *Engine) EffectContinuationStatus() (coordination.TaskServiceStatus, bool)
EffectContinuationStatus returns local counters and whether recovery is configured.
func (*Engine) EffectRecoveryStatus ¶
func (e *Engine) EffectRecoveryStatus() (coordination.TaskServiceStatus, bool)
EffectRecoveryStatus returns local counters and whether recovery is configured.
func (*Engine) Extensions ¶
Extensions returns the plugin registry.
func (*Engine) GetAgentByName ¶
func (*Engine) GetBehavior ¶
func (*Engine) GetBehaviorByName ¶
func (*Engine) GetCheckpoint ¶
func (e *Engine) GetCheckpoint(ctx context.Context, cpID id.CheckpointID) (*checkpoint.Checkpoint, error)
func (*Engine) GetConversation ¶
func (e *Engine) GetConversation(ctx context.Context, convID id.ConversationID) (*a2a.Conversation, error)
GetConversation returns one conversation in the caller's scope.
func (*Engine) GetOrchestration ¶
func (e *Engine) GetOrchestration(ctx context.Context, orchID id.OrchestrationConfigID) (*orchestration.Config, error)
GetOrchestration returns an orchestration config by ID.
func (*Engine) GetOrchestrationByName ¶
func (e *Engine) GetOrchestrationByName(ctx context.Context, name string) (*orchestration.Config, error)
GetOrchestrationByName returns an orchestration config by scoped name.
func (*Engine) GetOrchestrationRun ¶
func (e *Engine) GetOrchestrationRun(ctx context.Context, runID id.OrchestrationID) (*orchestration.Run, error)
GetOrchestrationRun returns an orchestration run record by ID.
func (*Engine) GetPersona ¶
func (*Engine) GetPersonaByName ¶
func (*Engine) GetSkillByName ¶
func (*Engine) GetTraitByName ¶
func (*Engine) HasToolAuthorizer ¶
HasToolAuthorizer distinguishes host policy from the permissive default.
func (*Engine) InterveneReflection ¶
func (e *Engine) InterveneReflection(ctx context.Context, runID id.AgentRunID, source cognitive.ContextSource) (cognitive.ReflectionReceipt, error)
InterveneReflection retains a user correction under the current authority fence. It supersedes pending controller action without resuming a run, changing its prepared input or resetting consumed attempts. Resume still uses its own existing checks and a terminal run requires a new explicitly prepared run.
func (*Engine) Knowledge ¶
Knowledge returns the configured knowledge provider, or nil if none is set.
func (*Engine) ListAgents ¶
func (*Engine) ListBehaviors ¶
func (*Engine) ListConversations ¶
func (e *Engine) ListConversations(ctx context.Context, filter *a2a.ConversationListFilter) ([]*a2a.Conversation, error)
ListConversations returns messaging conversations in the caller's scope.
func (*Engine) ListMessages ¶
func (e *Engine) ListMessages(ctx context.Context, filter *a2a.MessageListFilter) ([]*a2a.Envelope, error)
ListMessages returns messages, optionally narrowed to one conversation.
func (*Engine) ListOrchestrationRuns ¶
func (e *Engine) ListOrchestrationRuns(ctx context.Context, filter *orchestration.RunListFilter) ([]*orchestration.Run, error)
ListOrchestrationRuns lists orchestration run records.
func (*Engine) ListOrchestrations ¶
func (e *Engine) ListOrchestrations(ctx context.Context, filter *orchestration.ConfigListFilter) ([]*orchestration.Config, error)
ListOrchestrations lists orchestration configs.
func (*Engine) ListPendingCheckpoints ¶
func (e *Engine) ListPendingCheckpoints(ctx context.Context, filter *checkpoint.ListFilter) ([]*checkpoint.Checkpoint, error)
func (*Engine) ListPersonas ¶
func (*Engine) ListSkills ¶
func (*Engine) ListToolCalls ¶
func (*Engine) ListTraits ¶
func (*Engine) LoadConversation ¶
func (*Engine) NewPlanReplanRuntime ¶
func (e *Engine) NewPlanReplanRuntime(source PlanReplanInputSource) (coordination.PlanReplanRuntime, error)
NewPlanReplanRuntime adapts admitted proposals to the engine's normal prepared ReAct loop. Use it only inside PlanReplanner's current host execution fence. Existing or ambiguous RunID creation is never retried as model dispatch.
func (*Engine) NewResumeCloser ¶
func (e *Engine) NewResumeCloser(fence suspension.ResumeClosureFence, authorizer suspension.ResumeClosureAuthorizer) (suspension.ResumeCloser, error)
NewResumeCloser uses durable engine storage to close uncertain resumed runs as incomplete. The host must authenticate permanent worker/tool quiescence and hold current authority. This API grants no retry or successful completion. Durable terminal events are atomic; background recovery skips terminal runs. Claims, effects and budget settlement stay separate.
func (*Engine) NewRunCallSealer ¶
func (e *Engine) NewRunCallSealer(fence execution.RunCallSealFence, authorizer execution.RunCallSealAuthorizer) (execution.RunCallSealer, error)
NewRunCallSealer uses the engine's journal store with explicit host authority ports. Sealing prevents new task calls while preserving late observations. It does not stop previously admitted calls or change claim and budget state.
func (*Engine) NewTaskReviewRuntime ¶
func (e *Engine) NewTaskReviewRuntime(c TaskReviewRuntimeConfig) (coordination.TaskCompletionReviewer, error)
NewTaskReviewRuntime reuses the prepared ReAct engine for independently reserved reviewers. It never reserves work itself or retries an uncertain start. Reviewer purpose is evaluation, so ordinary learning hooks must exclude its output.
func (*Engine) NewTaskWorker ¶
func (e *Engine) NewTaskWorker(config TaskWorkerConfig) (coordination.ClaimedTaskWorker, error)
NewTaskWorker creates an adapter for coordination.TaskScheduler. Configure the engine's TaskRunAdmitter and TaskCallGuard first. The adapter requires fresh dispatch and child creation, then reuses RunPreparedTask for execution, publication and verification. It does not accept task outputs, settle shared usage or infer permission to retry an uncertain call. A scheduler configured for renewal receives activation only after confirmed fresh child creation.
func (*Engine) ObservePreparedRecipient ¶
func (e *Engine) ObservePreparedRecipient(ctx context.Context, req a2a.RecipientRequest, authorize func(context.Context, id.OrchestrationID, id.AgentRunID) error) (a2a.RecipientObservation, error)
ObservePreparedRecipient reads an existing child's outcome from the original prepared team. The host must authorize this exact team and run before private reads and before returning output. No child is reserved, executed or resumed. Required verification must pass before success. Recovered verified output also requires configured result-content authority and current publication checks.
func (*Engine) OrchestrationExpiryStatus ¶
func (e *Engine) OrchestrationExpiryStatus() (coordination.TaskServiceStatus, bool)
OrchestrationExpiryStatus reports whether cleanup was configured and its local counters. Stopping means owned callbacks have not yet drained.
func (*Engine) OrchestrationRecoveryStatus ¶
func (e *Engine) OrchestrationRecoveryStatus() (coordination.TaskServiceStatus, bool)
OrchestrationRecoveryStatus reports configuration and local lifecycle counters.
func (*Engine) PendingVerificationTools ¶
func (e *Engine) PendingVerificationTools(ctx context.Context, runID id.AgentRunID) ([]suspension.PendingCall, error)
PendingVerificationTools returns private pending calls only after current host authorization. Ordinary run responses and events omit these arguments and IDs. Reading does not claim a suspension or authorize executing a tool. Raw Store access remains a trusted host capability outside this authorization boundary.
func (*Engine) PlanReplanningStatus ¶
func (e *Engine) PlanReplanningStatus() (coordination.TaskServiceStatus, bool)
PlanReplanningStatus reports bounded local counters and configuration presence.
func (*Engine) PrepareAgent ¶
func (e *Engine) PrepareAgent(ctx context.Context, agentID id.AgentID, overrides *RunOverrides) (*PreparedAgent, error)
PrepareAgent resolves an agent and freezes its effective configuration and sources under the caller's exact scope. Tool authorization remains live.
func (*Engine) PrepareOrchestration ¶
func (e *Engine) PrepareOrchestration(ctx context.Context, key id.OrchestrationConfigID) (*PreparedOrchestration, error)
PrepareOrchestration captures config and all named participants in one store snapshot. It requires OrchestrationPreparationSources; independent reads are never substituted. Publication checks run after the transaction closes. Preparation grants no approval and invokes no strategy, model or tools.
func (*Engine) PrepareOrchestrationWithBudgets ¶
func (e *Engine) PrepareOrchestrationWithBudgets(ctx context.Context, key id.OrchestrationConfigID, budgets map[string]execution.Budget) (*PreparedOrchestration, error)
PrepareOrchestrationWithBudgets freezes explicit per-invocation ceilings in every participant, including auxiliary agents. Steps, tokens and deadline are required. A zero tool limit is allowed only when the captured tool list is empty. Budgets must match the complete execution roster. Shared team capacity still needs its own durable reservation policy before dispatch.
func (*Engine) PrepareTaskRun ¶
func (e *Engine) PrepareTaskRun(ctx context.Context, p *PreparedAgent, input string, opts PreparedTaskRunOptions) (coordination.TaskRunRequest, error)
PrepareTaskRun scans input and history and persists the exact private execution inputs for a reserved child. It returns a detached creation request, but does not create a run, register its capture intent, emit lifecycle events or invoke generation/evaluation. Preserve this request for idempotent creation retries. Session resolution and authorized input-evidence storage may write records.
func (*Engine) ProvideResults ¶ added in v1.10.0
func (e *Engine) ProvideResults(ctx context.Context, runID id.AgentRunID, in ResumeInput) error
ProvideResults answers an external-tool pause and marks the run ready. It never calls the model.
The results are checked against the pause before anything is written: one per pending call, or cortex.ErrResultsMismatch. A run paused for approval is cortex.ErrRequiresApproval, and one waiting on another agent is ErrNotAgentReplyResumable, exactly as Resume refuses them. Every refusal leaves the run paused. Once the run is ready, RunReady fires and ContinueRun continues it.
A store without run.ContinuationStore returns cortex.ErrContinuationUnavailable; use Resume there.
func (*Engine) ProviderRecoveryStatus ¶
func (e *Engine) ProviderRecoveryStatus() (coordination.TaskServiceStatus, bool)
ProviderRecoveryStatus returns local counters and whether recovery is configured.
func (*Engine) PublicEventReplayAvailable ¶
PublicEventReplayAvailable reports whether current-authority replay is configured.
func (*Engine) ReadPublicEvents ¶
func (e *Engine) ReadPublicEvents(ctx context.Context, request event.ReadRequest) (event.Page, error)
ReadPublicEvents reauthorizes one bounded page, including retention gaps. Consumers deduplicate by event ID and resume with Page.Next after disconnection.
func (*Engine) ReadResultContent ¶
func (e *Engine) ReadResultContent(ctx context.Context, request verification.ResultContentRequest) (verification.PublishedResult, error)
ReadResultContent returns a freshly screened projection with minimal metadata. A redacted projection is marked ContentChanged; verification describes the original candidate. This read does not regenerate, reevaluate or persist output.
func (*Engine) RecoverAgentReply ¶
func (e *Engine) RecoverAgentReply(ctx context.Context, runID id.AgentRunID, key id.SuspensionID, authorize func(context.Context, id.AgentRunID) error) (*run.Run, error)
RecoverAgentReply continues an admitted resume that has no execution start. The host callback checks current authority before reads, before starting and before every provider/tool call. An existing or ambiguous start cannot be replayed; ErrResumeAlreadyStarted requires inspection and reconciliation. This host API is not exposed as a tool or an unauthenticated transport route.
The callback reads the principal on the context it is handed, and that changes once. The checks before the resume reads the run back run under ctx's principal, the recoverer's. The engine then restores the run's own principal, just before it admits or starts the resume, and every later check, including the one before each provider and tool call, runs under the run's principal.
func (*Engine) RecoverVerificationPage ¶
func (e *Engine) RecoverVerificationPage(ctx context.Context, request VerificationRecoveryRequest) (VerificationRecoveryPage, error)
RecoverVerificationPage discovers captured work and reuses VerifyRun to resume checks. It never generates, dispatches tools or invents a result identity. Jobs without a saved capture intent remain managed through explicit VerifyRun calls. The host authorizes exact-scope discovery before calling this trusted API; each job also passes the configured current binding authorizer before work.
func (*Engine) ResolveCheckpoint ¶
func (e *Engine) ResolveCheckpoint(ctx context.Context, cpID id.CheckpointID, decision checkpoint.Decision) error
ResolveCheckpoint records a human decision, and, when the checkpoint belongs to a run the loop paused, carries that decision to the run: an approval continues it, a rejection ends it with the reason the decider gave (or, with WithRejectionsReturnToModel, continues it with the rejection as each call's result).
It is DecideCheckpoint followed by ContinueRun on the caller's goroutine, so the caller waits for the run rather than getting a receipt for one, same as RunAgent.
A decision that continues a run (an approval, or a rejection that goes back to the model) is admitted first, like any run: while Stop drains it returns cortex.ErrEngineStopping, and under a full WithRunConcurrency cap it waits for a slot until ctx ends. Either refusal records nothing, so the checkpoint stays pending and the caller can decide again here or on another replica. The admission is held through the continuation.
After that, the decision is recorded before the run continues, because the ready state between the two is durable: a continuation that fails leaves the decision recorded and the run either failed (a failure after the claim) or still ready for ContinueRun (a check that failed for now before the claim, such as a principal the codec could not decode). In the second case the error says so: the decision is recorded and ContinueRun finishes the run, which a host that continues RunReady runs does on its own. Repeating the decision then is cortex.ErrInvalidState and never runs the approved action again.
A checkpoint a host wrote itself resolves exactly as it always has, with nothing else touched. Only the loop knows how to pause a run, so only a checkpoint the loop opened has a run waiting behind it, and treating every checkpoint as though it did would break every caller that has been writing its own rows since before suspension existed. openedASuspendedRun is what tells the two apart.
Two operators deciding the same checkpoint at once both pass the pending guard. MarkReady lets one of them move the run and the store keeps the first record of a decision, so the other is told cortex.ErrInvalidState, fires no hook and continues nothing. Deciding a checkpoint whose pause the run has already left is cortex.ErrInvalidState too, so it never approves the run's next pause; when the run is waiting on a different pause, the stale checkpoint is closed as superseded.
RunReady fires between the two halves. A host that continues ready runs from that hook should decide with DecideCheckpoint: with ResolveCheckpoint one of the two continuations is refused with cortex.ErrRunNotContinuable.
A store without run.ContinuationStore keeps the older order, acting on the decision before recording it; see resolveInPlace.
func (*Engine) ResultContentAvailable ¶
ResultContentAvailable reports whether current-authority content reads are configured.
func (*Engine) Resume ¶
func (e *Engine) Resume(ctx context.Context, runID id.AgentRunID, in ResumeInput) (*run.Run, error)
Resume continues a suspended run synchronously once every pending call has a result.
It answers an external-tool pause. A run paused for approval is not resumable this way: it is waiting on a decision, and the decision is what ResolveCheckpoint carries. Resuming one here is cortex.ErrRequiresApproval and the run stays paused.
It re-derives authority from the STORED scope rather than the caller's, re-enters the loop at the step the suspension recorded, and restores the history boundary and the session from the continuation instead of recomputing either. Resuming with a different scope, a fresh session, or a rebuilt message list are three different ways to corrupt a run that looked fine at the call site and went wrong several turns later.
func (*Engine) ResumePreparedOrchestration ¶
func (e *Engine) ResumePreparedOrchestration(ctx context.Context, team id.OrchestrationID) (rec *orchestration.Run, err error)
ResumePreparedOrchestration continues a waiting team or claims an expired coordinator from its original snapshot. Unleased running parents are refused. Resume paused children through their existing authorized resume APIs first. This call never restarts a child with a retained invocation identity.
func (*Engine) ResumeStream ¶
func (e *Engine) ResumeStream(ctx context.Context, runID id.AgentRunID, in ResumeInput, events chan<- StreamEvent) (err error)
ResumeStream is Resume over the streaming loop. The channel is closed when execution completes, same as StreamAgent's, and the run's admission slot is held until then.
func (*Engine) RunAgent ¶
func (e *Engine) RunAgent(ctx context.Context, agentName, input string, overrides *RunOverrides) (r *run.Run, err error)
RunAgent executes an agent synchronously. When an LLM client is configured, it uses the ReAct reasoning loop. Otherwise, it falls back to mock/echo mode.
The run is traced as one run agent span covering the whole call.
func (*Engine) RunConcurrency ¶ added in v1.10.0
RunConcurrency returns how many runs may execute at once, or zero when there is no limit. See WithRunConcurrency.
func (*Engine) RunOrchestration ¶
func (e *Engine) RunOrchestration(ctx context.Context, name, input string) (*orchestration.Run, error)
RunOrchestration loads a stored orchestration config by name and executes it, persisting a Run and firing orchestration lifecycle hooks.
It runs under a run orchestration span, and every participant's run agent span nests under it, parallel workers included.
func (*Engine) RunPrepared ¶
func (e *Engine) RunPrepared(ctx context.Context, p *PreparedAgent, input string, opts PreparedRunOptions) (r *run.Run, err error)
RunPrepared executes a frozen configuration through the normal ReAct loop. A failure after acknowledged creation returns the run alongside the error. PreparedStartError also identifies uncertain creation attempts.
func (*Engine) RunPreparedOrchestration ¶
func (e *Engine) RunPreparedOrchestration(ctx context.Context, p *PreparedOrchestration, input string, opts PreparedRunOptions) (rec *orchestration.Run, err error)
RunPreparedOrchestration executes frozen participants under explicit shared capacity. Each child gets a fresh nondefault session. Token-only accounts are supported; billing settlement remains host-owned. Messaging tools require WithPreparedTeamMessaging and use the captured team's private routing partition.
func (*Engine) RunPreparedTask ¶
func (e *Engine) RunPreparedTask(ctx context.Context, p *PreparedAgent, request coordination.TaskRunRequest) (r *run.Run, err error)
RunPreparedTask admits and executes the exact request from PrepareTaskRun. It loads authorized captured inputs, never current conversation history. Both a TaskRunAdmitter and TaskCallGuard are required. An ambiguous or historical start returns ErrTaskRunReconciliationRequired without invoking a provider.
func (*Engine) RunVerificationRecovery ¶
func (e *Engine) RunVerificationRecovery(ctx context.Context, config VerificationRecoveryLoop) error
RunVerificationRecovery runs immediate and periodic bounded scans until cancellation or a discovery failure. It retains the cursor between pages and wraps after reaching the end. Restart starts from the supplied cursor; durable job leases and call IDs prevent repeating paid evaluation after uncertainty. Callback lease renewal follows the worker configuration. This loop does not renew idle leases, publish history or replay completion hooks.
func (*Engine) RuntimeCapabilities ¶
func (e *Engine) RuntimeCapabilities() RuntimeCapabilities
RuntimeCapabilities returns immutable process capabilities. Scanner health and effectiveness are evaluated by the configured provider for each request.
func (*Engine) SendMessage ¶
func (e *Engine) SendMessage(ctx context.Context, params a2a.SendParams) (*a2a.SendResult, error)
SendMessage injects a message from outside a run: an operator answering an agent, an HTTP handler carrying one in, or (later) a remote peer.
It is the same path an agent's own agent_send takes, so a message from outside is delivered, hop-counted and correlated exactly like one from inside. A reply carrying in_reply_to therefore resumes a waiting run here too, which is what lets a human answer an agent that asked.
Example ¶
ExampleEngine_SendMessage answers an agent that asked a question.
This is the path behind POST /v1/agents/:name/messages: the reply carries the waiting ask's reply-with token, so posting it resumes the run behind it exactly as a peer's answer would have.
package main
import (
"context"
"log"
"github.com/xraph/cortex/a2a"
"github.com/xraph/cortex/engine"
)
func main() {
var (
eng *engine.Engine
ctx context.Context
replyWith string // read from the pending ask, or from the ask message
)
_, err := eng.SendMessage(ctx, a2a.SendParams{
Sender: a2a.Address{Agent: "on-call-human"},
Receivers: []a2a.Address{{Agent: "planner"}},
Performative: a2a.Inform,
Content: "Yes, the migration window is approved for 02:00 UTC.",
InReplyTo: replyWith,
})
if err != nil {
log.Fatal(err)
}
}
Output:
func (*Engine) Start ¶
Start initializes the engine for operation.
Background services own their lifetimes and are stopped by Stop. Optional task scheduling and recovery preserve context values for host identity, without using the startup request cancellation as the service lifetime.
func (*Engine) Stop ¶
Stop gracefully shuts down the engine.
It first drains: from the moment Stop starts, RunAgent, StreamAgent, RunPrepared, StreamPrepared, Resume, ResumeStream and a ResolveCheckpoint that would continue a run return cortex.ErrEngineStopping before they write anything, and Stop waits for the runs already executing to finish. A run started from inside one of those (a tool calling RunAgent on the ctx it was given) is still let through, because its parent is one of the runs being waited for. Start admits runs again.
With leasing off, the default, every admitted run runs to its end while Stop drains, as it always has, and nothing is handed off.
A leased run (WithRunLease) does not run to the end while Stop drains. At its next boundary, before a model call or a tool dispatch, it saves its progress, becomes reclaimable under this worker's lease, fires RunReclaimable with HandOff set, and returns cortex.ErrRunInterrupted; another replica continues it. A run that finishes before reaching a boundary simply finishes.
The message bus is under the same admission: while Stop drains it claims no new delivery or ask, leaving them queued for another worker, and a delivery it was already carrying finishes, resume included.
A run started from inside another run's call (a tool calling RunAgent on its ctx) is not handed off because of the drain: it ends with the call that started it.
If ctx ends before the last run finishes, Stop cancels the leased runs still executing with cause cortex.ErrEngineStopping, still signals task services and returns ctx's error, but leaves the sweeper and the message bus running and announces no shutdown. Each cancelled run hands itself off as above, on its own goroutine: Stop does not wait for those writes, so a process that exits at once may leave some of those runs to lapse and be reclaimed by the sweep instead. A tool result that arrives after the cancellation is discarded, so a call that is not retry-safe stays recorded as started. Runs without a lease keep executing and write their own outcome when they finish. Call Stop again to complete the shutdown before disposing stores.
The sweeper is joined, not merely signalled, and it is joined before the shutdown hook fires: a subscriber told the engine has stopped while a sweep is still failing runs has been told something untrue. Optional task scheduling and recovery receive cancellation before any service is drained. If a stop deadline expires, Stop returns an error without emitting shutdown; call Stop again before disposing stores. Lifecycle calls are serialized through shutdown notification, with cancellation-aware waits for another caller.
func (*Engine) StreamAgent ¶
func (e *Engine) StreamAgent(ctx context.Context, agentName, input string, overrides *RunOverrides, events chan<- StreamEvent) (err error)
StreamAgent executes an agent and sends streaming events to the channel. The channel is closed when execution completes. When an LLM client is configured, it uses the ReAct reasoning loop with streaming. Otherwise, it falls back to mock/echo mode.
The run agent span, and the run's admission slot, last until the stream's goroutine finishes, not until this call returns.
func (*Engine) StreamPrepared ¶
func (e *Engine) StreamPrepared(ctx context.Context, p *PreparedAgent, input string, opts PreparedRunOptions, events chan<- StreamEvent) (err error)
StreamPrepared streams the same prepared execution used by RunPrepared. The run's admission slot is held until the stream's goroutine closes events.
func (*Engine) StreamPreparedTask ¶
func (e *Engine) StreamPreparedTask(ctx context.Context, p *PreparedAgent, request coordination.TaskRunRequest, events chan<- StreamEvent) (err error)
StreamPreparedTask streams the same admitted execution as RunPreparedTask. It closes events on admission failure and owns the channel after success.
func (*Engine) TaskAdoptionStatus ¶
func (e *Engine) TaskAdoptionStatus() (coordination.TaskServiceStatus, bool)
TaskAdoptionStatus reports local counters and whether adoption is configured.
func (*Engine) TaskCompletionStatus ¶
func (e *Engine) TaskCompletionStatus() (coordination.TaskServiceStatus, bool)
TaskCompletionStatus reports bounded local counters and configuration presence.
func (*Engine) TaskRetirementStatus ¶
func (e *Engine) TaskRetirementStatus() (coordination.TaskServiceStatus, bool)
TaskRetirementStatus reports local counters and whether retirement is configured.
func (*Engine) TaskSchedulingStatus ¶
func (e *Engine) TaskSchedulingStatus() (coordination.TaskServiceStatus, bool)
TaskSchedulingStatus returns bounded lifecycle counters and whether scheduling was configured. A stopping service has not released its owned callbacks.
func (*Engine) TaskSettlementStatus ¶
func (e *Engine) TaskSettlementStatus() (coordination.TaskServiceStatus, bool)
TaskSettlementStatus reports local counters and whether accounting is configured.
func (*Engine) ToolRetrySafe ¶ added in v1.10.0
ToolRetrySafe reports whether a tool was marked safe to run again.
func (*Engine) Tools ¶ added in v1.10.0
Tools lists every tool in dispatch order: the builtins enabled for this external tools. A name is listed once, at the first definition dispatch reaches.
func (*Engine) UpdateAgent ¶
func (*Engine) UpdateBehavior ¶
func (*Engine) UpdateConfig ¶
UpdateConfig applies partial runtime configuration updates. Only non-zero fields in the update are applied. Changes are in-memory only.
func (*Engine) UpdateOrchestration ¶
UpdateOrchestration updates an existing orchestration config.
func (*Engine) UpdatePersona ¶
func (*Engine) UpdateSkill ¶
func (*Engine) UpdateTrait ¶
func (*Engine) VerificationRecoveryStatus ¶
func (e *Engine) VerificationRecoveryStatus() (coordination.TaskServiceStatus, bool)
VerificationRecoveryStatus reports configuration and local lifecycle counters.
func (*Engine) VerifyRun ¶
func (e *Engine) VerifyRun(ctx context.Context, request VerifyRunRequest) (VerificationRunResult, error)
VerifyRun enqueues, claims, evaluates and commits a saved candidate. It never invokes generation or tools. Groups run in contract order until required checks settle; optional groups after readiness are skipped. Configured renewal keeps evaluator callbacks owned; claim and commit still enforce stored lease expiry. An error may follow durable work: retry the same identities to reconcile it. Normal sync, stream and resume publication is unaffected by this explicit API.
func (*Engine) VisibleTools ¶
VisibleTools returns the same scoped definitions a run may advertise. Reading the registry alone would omit builtin/external tools and bypass the host's visibility policy. The caller must already be authorized to read the agent.
type ExternalToolOption ¶ added in v1.10.0
type ExternalToolOption func(*registeredExternal)
ExternalToolOption configures one WithExternalTool registration.
func ExternalTTL ¶ added in v1.10.0
func ExternalTTL(d time.Duration) ExternalToolOption
ExternalTTL sets how long a run paused on this tool waits for its result before the sweeper fails it, in place of the engine's suspension TTL. Zero keeps the engine's. A negative duration is refused, for the same reason WithSuspensionTTL refuses one.
type OperationalAwarenessConfig ¶
type OperationalAwarenessConfig struct {
Calibration OperationalCalibrationProvider
Policy cognitive.CalibrationPolicy
}
OperationalAwarenessConfig optionally connects authenticated evaluation cohorts. Policy controls minimum resolved trials and maximum observation age. With no adapter, the capability tool reports unknown reliability.
type OperationalCalibrationObservation ¶
type OperationalCalibrationObservation struct {
Binding cognitive.CalibrationBinding
Observation *cognitive.CalibrationObservation
}
OperationalCalibrationObservation adds host-owned configuration pins and an authenticated measurement. An absent cohort keeps reliability unknown.
type OperationalCalibrationProvider ¶
type OperationalCalibrationProvider interface {
ObserveCalibration(context.Context, OperationalCalibrationRequest) (OperationalCalibrationObservation, error)
}
OperationalCalibrationProvider reads current evidence under the caller's scope. You must authenticate the evaluation producer, verify retained evidence bytes, check revocation and contamination, and authorize disclosure to this run before returning. Never derive authority, task class or host revisions from model text. The callback must honor cancellation. Cortex applies a five-second timeout and checks its own runtime pins; it cannot authenticate your external evaluator.
type OperationalCalibrationRequest ¶
type OperationalCalibrationRequest struct {
RunID id.AgentRunID
AgentID id.AgentID
Scope cortex.Scope
PreparedDigest string
Model string
ModelRevision string
PromptDigest string
PolicyDigest string
AcceptanceDigest string
Deadline time.Time
Tools []cognitive.CalibrationTool
}
OperationalCalibrationRequest contains detached identity and immutable runtime pins. PromptDigest identifies the effective system prompt without disclosing it. PolicyDigest covers the frozen configuration except its absolute deadline. The host must check comparable wall-time constraints and bind its task class, provider, controller and environment revisions to this exact run.
type Option ¶
Option configures the Engine.
func WithA2A ¶
WithA2A turns on agent-to-agent messaging.
The three tools (agent_send, agent_ask, agent_inbox) appear in an agent's tool list only when this is set, so a host that does not configure it sees no new tools, no new behaviour, and no rows in the four a2a tables.
Messaging needs a store: the ask that suspends a run is durable, and a pending ask nobody can read back is a run nothing could ever resume.
Example ¶
ExampleWithA2A wires two agents that can talk to each other.
There is no Output comment, so this compiles with the package and is never executed: it needs a real model behind it to do anything. What it is here for is to stop the wiring in the docs from drifting away from the wiring the code actually accepts.
package main
import (
"context"
"log"
"time"
"github.com/xraph/grove"
"github.com/xraph/grove/drivers/sqlitedriver"
"github.com/xraph/cortex"
"github.com/xraph/cortex/a2a"
"github.com/xraph/cortex/agent"
"github.com/xraph/cortex/engine"
sqlitestore "github.com/xraph/cortex/store/sqlite"
)
func main() {
ctx := cortex.WithScope(context.Background(), cortex.Scope{
Levels: []cortex.Level{{Key: "tenant", Value: "acme"}},
})
drv := sqlitedriver.New()
if err := drv.Open(ctx, "cortex.db"); err != nil {
log.Fatal(err)
}
db, err := grove.Open(drv)
if err != nil {
log.Fatal(err)
}
st := sqlitestore.New(db)
if migrateErr := st.Migrate(ctx); migrateErr != nil {
log.Fatal(migrateErr)
}
eng, err := engine.New(
engine.WithStore(st),
// Messaging is opt-in. Without this, the three tools below never
// appear in any agent's tool list.
engine.WithA2A(a2a.Options{
HopCeiling: 8,
Workers: 4,
DefaultReplyBy: 5 * time.Minute,
}),
)
if err != nil {
log.Fatal(err)
}
// Start brings the dispatcher up: it carries queued messages, runs the
// agents they are addressed to, and resumes whoever was waiting. It
// also redrives anything a previous process queued and never carried.
if startErr := eng.Start(ctx); startErr != nil {
log.Fatal(startErr)
}
defer func() { _ = eng.Stop(ctx) }()
for _, cfg := range []*agent.Config{
{
Name: "planner",
Model: "gpt-4o",
SystemPrompt: "You plan work and delegate. When you need something you cannot " +
"determine yourself, use agent_ask to ask the specialist who can.",
MaxSteps: 10,
},
{
Name: "db-expert",
Model: "gpt-4o",
SystemPrompt: "You answer questions about the production database.",
MaxSteps: 10,
},
} {
if createErr := eng.CreateAgent(ctx, cfg); createErr != nil {
log.Fatal(createErr)
}
}
// The planner's model can now call agent_ask("db-expert", ...). That
// run suspends on a row in the database rather than a goroutine, the
// db-expert runs, and its answer comes back as the planner's tool
// result. If this process dies in the middle, the next one redrives it.
r, err := eng.RunAgent(ctx, "planner", "Is the orders table safe to migrate tonight?", nil)
if err != nil {
log.Fatal(err)
}
log.Println(r.State, r.Output)
}
Output:
func WithA2AHandoffHandler ¶
func WithA2AHandoffHandler(handler a2a.HandoffHandler) Option
WithA2AHandoffHandler installs explicit structured assignment admission. Use WithA2A as well; this option never enables messaging or effect tools by itself.
func WithAgentReplyGrace ¶ added in v1.10.0
WithAgentReplyGrace sets how long past an ask's reply-by a run waiting on another agent's answer stays paused before the sweeper fails it. It defaults to defaultAgentReplyGrace.
The grace exists because the ask has a deadline of its own, and the message bus answers it first: at reply-by the ask sweep resumes the asking run with a timeout the model can read and react to. The engine's deadline comes later, so its sweep only fails a run the ask sweep never reached, a bus that was down or a resume that failed. Zero puts the two deadlines on one instant, and which sweep wins is then down to timing. A negative duration is refused.
func WithAgentReplyRecovery ¶
func WithAgentReplyRecovery(config AgentReplyRecoveryConfig) Option
WithAgentReplyRecovery installs optional bounded background reply recovery. Discovery must include interrupted answer seals and admissions. Existing start receipts remain reconciliation errors; polling never grants replay authority.
func WithArtifactPublication ¶
func WithArtifactPublication(config coordination.ArtifactPublicationConfig) Option
WithArtifactPublication installs bounded publication of accepted task outputs. Conflicts remain durable until an explicitly authorized ArtifactBoard resolution. The host resolves current source bindings and supplies publication authority.
func WithAtomicPreparation ¶
func WithAtomicPreparation() Option
WithAtomicPreparation requires a consistent store snapshot for each new preparation. Unsupported stores and external knowledge references fail closed. Default preparation continues to use diagnostic read-set checks.
func WithClaimRecovery ¶
func WithClaimRecovery(config coordination.ClaimRecoveryConfig) Option
WithClaimRecovery installs authorized discovery and claim expiry before Start. The service owns no provider or tool execution capability. Discovery must also include cancelled and completed plans that still retain outstanding claims. Supply a store capability explicitly; this option never broadens store scope.
func WithConfig ¶
WithConfig sets the engine configuration.
func WithContextBudget ¶
func WithContextBudget(config ContextBudgetConfig) Option
WithContextBudget freezes a finite context policy into newly prepared agents. Current-turn messages remain pinned; only initial history can be omitted.
func WithCoordinationEvents ¶
func WithCoordinationEvents(config coordination.EventServiceConfig) Option
WithCoordinationEvents installs bounded private transition delivery. The host supplies current source and sink grants and an authenticated idempotent sink. Event sequences order index materialization, not historical source occurrence.
func WithEffectContinuation ¶
func WithEffectContinuation(config coordination.EffectContinuationServiceConfig) Option
WithEffectContinuation installs bounded retries and explicit compensation for sealed recovering tasks. The host must authenticate provider dispositions and current grants. Results remain private evidence for a new verified preparation; this service never accepts the original task or dispatches its replacement.
func WithEffectRecovery ¶
func WithEffectRecovery(config coordination.EffectRecoveryServiceConfig) Option
WithEffectRecovery installs optional discovery of sealed recovering runs. The host supplies authorized discovery, the durable recovery store and every effect authority port. This service never closes journals, dispatches effects, accepts tasks, releases claims or refunds shared reservations.
func WithExtension ¶
WithExtension registers an extension with the engine.
func WithExternalTool ¶
func WithExternalTool(def llm.Tool, opts ...ExternalToolOption) Option
WithExternalTool registers a tool the engine advertises but never executes. When the model calls one, the run suspends and waits for the caller to run it and hand the result back.
The definition is advertised exactly like a WithTool registration (resolveTools), and the authorizer gates a call to it exactly like any other (executeTool). The only difference is what happens at dispatch: there is no handler to run, so the call becomes pending and the loop stops.
Pass ExternalTTL to give a pause on this tool its own deadline.
func WithKnowledge ¶
WithKnowledge sets the knowledge provider for RAG-based knowledge retrieval. When set, skills with KnowledgeRef entries can inject relevant context into agent system prompts and agents gain access to a knowledge_search tool.
func WithLLM ¶
WithLLM sets the LLM client for real model execution. When set, RunAgent and StreamAgent use this client instead of mock/echo mode.
func WithMetrics ¶
WithMetrics records the engine's metrics on m: runs, steps, tool calls, publication checks, suspensions and orchestrations, plus the message bus's deliveries when WithA2A is set. Every label is a bounded enum. In a Forge app pass app.Metrics(); the cortex Forge extension does it for you, and the scrape shows each name with a forge_ prefix. A nil m, the default, records nothing.
Spans need no option: the engine traces through the global OpenTelemetry tracer provider, which Forge installs.
func WithModelRevision ¶
WithModelRevision pins a host-resolved model version behind a model selector.
func WithOperationalAwareness ¶
func WithOperationalAwareness(config ...OperationalAwarenessConfig) Option
WithOperationalAwareness registers a read-only tool for observing this run's current tools and remaining limits. Include ToolOperationalCapabilities in explicit tool allowlists. The normal authorizer, accounting, publication and transcript paths apply; registration does not enable adaptive execution.
func WithOrchestrationExpiry ¶
func WithOrchestrationExpiry(config coordination.OrchestrationExpiryConfig) Option
WithOrchestrationExpiry installs deadline cleanup before Start. Supply an explicit authorized source and an expirer backed by the durable budget store. The service has no agent execution or reservation settlement capability.
func WithOrchestrationRecovery ¶
func WithOrchestrationRecovery(config OrchestrationRecoveryConfig) Option
WithOrchestrationRecovery enables explicit bounded background recovery before Start. Waiting teams are revisited when children resolve; expired running owners are reclaimed through the same guarded API as explicit recovery.
func WithPlanReplanning ¶
func WithPlanReplanning(config coordination.PlanReplanServiceConfig) Option
WithPlanReplanning installs bounded, guarded plan proposal and recovery work. The host supplies current authority and durable discovery. Shutdown joins all callbacks before the engine releases its extensions.
func WithPreparedTeamMessaging ¶
func WithPreparedTeamMessaging(config PreparedTeamMessagingConfig) Option
WithPreparedTeamMessaging enables captured-roster messaging under coordinator ownership. No background dispatcher receives a coordinator's execution rights.
func WithPrincipalCodec ¶ added in v1.10.0
func WithPrincipalCodec(c cortex.PrincipalCodec) Option
WithPrincipalCodec installs the codec that carries a run's principal across a pause. The engine encodes cortex.PrincipalFromContext when it creates a run and stores the bytes with it; every resume decodes them and continues under that principal, not the resumer's. ResolveCheckpoint also encodes the decider's principal into Decision.DecidedByPrincipal.
A host that installs a tool authorizer must install one, or New returns cortex.ErrPrincipalCodecRequired: without it, an authorizer would see every resumed run as nobody. Without a codec a resumed run has a nil principal.
func WithProviderRecovery ¶
func WithProviderRecovery(config coordination.ProviderRecoveryServiceConfig) Option
WithProviderRecovery installs optional discovery of sealed recovering runs. The host supplies authorized discovery, the durable recovery store and every provider authority port. This service never closes journals, invokes models or tools, accepts tasks, releases claims or refunds shared reservations.
func WithPublicEventRecording ¶
func WithPublicEventRecording() Option
WithPublicEventRecording requires atomic terminal state and metadata persistence for ordinary runs. Required-verification results use their guarded transaction. It does not grant replay access; configure WithPublicEventReplay separately.
func WithPublicEventReplay ¶
func WithPublicEventReplay(authorizer event.Authorizer) Option
WithPublicEventReplay enables metadata replay with current subscriber authority. This does not start a poller or publish candidate text, history or completion hooks.
func WithPublicationGate ¶
func WithPublicationGate(gate safety.PublicationGate) Option
WithPublicationGate installs a host checker. It takes precedence over the scanner adapter, and must advertise IncrementalGate for checked segments.
func WithPublicationPolicy ¶
WithPublicationPolicy configures the host's publication boundary.
func WithReadyRenotify ¶ added in v1.10.0
WithReadyRenotify sets how long a ready or reclaimable run may wait before the sweeper tells the host again. A host that missed RunReady or RunReclaimable (its process died between the state change and its enqueue, say) hears it again with Renotified set, at most once per d for each run. The default is 5 minutes. Zero turns re-notification off; a negative d fails New.
func WithReclaimLimit ¶ added in v1.10.0
WithReclaimLimit sets how often a run may be reclaimed after its worker's lease lapsed. A run reclaimed more than n times is failed with cortex.ErrReclaimLimit when it is next continued, without another model call: a run that takes its worker down every time it runs stops there instead of taking the next replica down too. A hand-off at shutdown is not a reclaim and does not count. The default is 3; a negative n fails New.
func WithReflection ¶
func WithReflection(config ReflectionConfig) Option
WithReflection validates opt-in strategy support without changing legacy persona behavior. Decisions and phase transitions require durable storage.
func WithRejectionsReturnToModel ¶ added in v1.10.0
func WithRejectionsReturnToModel() Option
WithRejectionsReturnToModel makes a rejected approval an error result the model reads, and the run continues. Each pending call is answered with "rejected by <DecidedBy>: <Reason>" and recorded as denied; none of them is dispatched. DecideCheckpoint marks the run ready, exactly as an approval does, and ResolveCheckpoint continues it before returning.
Without it, the default, a rejection fails the run with the decider's reason.
func WithRequiredVerification ¶
func WithRequiredVerification(config RequiredVerificationConfig) Option
WithRequiredVerification enables fail-closed candidate publication. It also requires WithVerificationWorker, a real LLM and durable capture capabilities. Required runs keep conversation history private even after result commit; historical delivery and history publication need a separate authorized path.
func WithResultContent ¶
func WithResultContent(config ResultContentConfig) Option
WithResultContent enables screened reads of committed verified results. A current publication gate, enabled publication policy and snapshot-capable store are required.
func WithRunConcurrency ¶ added in v1.10.0
WithRunConcurrency caps how many runs execute at once. A run that finds every slot taken waits for one, or for its ctx to end, in which case it returns an error matching ctx.Err() and leaves no run row. Zero, the default, is unlimited; a negative n is an error.
It covers RunAgent, StreamAgent, RunPrepared, StreamPrepared, Resume, ResumeStream, ResolveCheckpoint and the resumes the message bus and agent-reply recovery start. A stream holds its slot until its channel closes. A run started from inside an admitted run, on the ctx it was given, shares its parent's slot, so a tool that runs another agent cannot deadlock on a limit of one. Runs started by the experimental task workers, prepared orchestrations and plan replanning are not counted.
cortex.Config.RunConcurrency is not read by the engine; the Forge extension applies its run_concurrency setting through this option.
func WithRunLease ¶ added in v1.10.0
WithRunLease turns on run leases and sets how long a worker's lease on a running run lasts before another replica may reclaim the run. The engine renews it every ttl/3 while the run executes and saves the run's progress at each step boundary, so a run whose worker dies or drains is left reclaimable rather than stuck running. A negative ttl fails New.
Leasing is off by default (ttl zero): Stop lets admitted runs finish, nothing is handed off and no run becomes reclaimable. Turn it on only when the host continues runs itself. A handed-off or reclaimed run waits in reclaimable until something calls ContinueRun, and nothing in the engine does: subscribe plugin.RunReady and plugin.RunReclaimable and queue a job that calls ContinueRun on the hook's ctx. With leasing on, Stop hands every leased run off at its next model call or tool dispatch and its RunAgent or StreamAgent caller gets cortex.ErrRunInterrupted. A sixty-second ttl suits most hosts.
Leasing needs a store that implements both run.ContinuationStore and suspension.ProgressStore. Runs under required verification or a task claim are never leased: coordination owns their recovery.
Every engine that shares a store must use the same setting. A worker renewing a lease takes over a running run that has no lease owner, so an engine with leases off sharing runs with one that leases them would have its runs taken from under it.
func WithSafety ¶
WithSafety sets the safety scanner for content scanning. When set, RunAgent and StreamAgent scan input before LLM calls and scan output after LLM responses.
func WithSuspensionSweepInterval ¶
WithSuspensionSweepInterval sets how often the expiry sweeper looks for suspensions past their deadline. It defaults to defaultSweepInterval.
The interval is the granularity of expiry, not its accuracy: a run whose deadline passes just after a sweep waits up to one more interval to be failed. Setting it far below the TTL buys nothing but load, since a deadline measured in hours does not need checking every second.
func WithSuspensionSweepLimit ¶
WithSuspensionSweepLimit caps how many expired suspensions one sweep takes on. A sweep that tried to drain an unbounded backlog would hold the store for as long as the backlog was long; the leftovers are picked up by the next tick.
func WithSuspensionTTL ¶
WithSuspensionTTL sets the default deadline for a suspended run: how long it waits for the outside world before the expiry sweeper fails it. It defaults to defaultSuspensionTTL.
It is a default, not the only deadline. An approval can carry its own (cortex.ApprovalRequired.TTL), an external tool can (ExternalTTL), and a run waiting on another agent follows that ask's reply-by. A suspension expires at the earliest deadline among its pending calls.
A TTL of zero means no default deadline: a pending call with no TTL of its own is written with none and never expires. That is the right setting for a host whose pauses are answered by a person on their own schedule and who would rather have a run sit paused for a week than have it failed out from under them. The sweeper still runs, because a call that does carry its own deadline still has to be failed when it passes. Zero is not the default, because the failure it prevents is visible and recoverable while the one it allows (a run paused forever on a browser tab somebody closed) is neither.
A negative duration is refused rather than clamped. It reads as an already-passed deadline, so accepting it would have every suspension swept on the next tick, which is the opposite of what anyone typing a negative number means.
func WithTaskAdoption ¶
func WithTaskAdoption(config coordination.TaskAdoptionServiceConfig) Option
WithTaskAdoption installs optional guarded adoption of sealed recovering runs. The host supplies durable storage, authorized discovery and snapshot access, proof resolution, authentication and fencing. This service can complete a recovered claim; it never invokes tasks or settles shared reservations.
func WithTaskCallGuard ¶
func WithTaskCallGuard(guard TaskCallGuard) Option
WithTaskCallGuard installs current-authority leases for task-bound executions. Runs with TaskClaimID fail closed when this port is absent, including resumes.
func WithTaskCompletion ¶
func WithTaskCompletion(config coordination.TaskCompletionServiceConfig) Option
WithTaskCompletion installs bounded, guarded review and task acceptance work. The host supplies current authority and durable discovery. Shutdown joins all callbacks before the engine releases its extensions.
func WithTaskRetirement ¶
func WithTaskRetirement(config coordination.TaskRetirementServiceConfig) Option
WithTaskRetirement installs guarded retirement of unsuccessful task ownership. The host supplies authorized discovery, exact retained accounting and permanent worker/tool quiescence proof. Replacement work still requires separate scheduler admission. Shutdown joins all discovery, proof and storage callbacks.
func WithTaskRunAdmitter ¶
func WithTaskRunAdmitter(admitter coordination.TaskRunAdmitter) Option
WithTaskRunAdmitter installs guarded, atomic child creation for prepared tasks. Use coordination.NewTaskRunAdmitter with the same durable store as the engine. A confirmed fresh receipt is required to begin execution. Historical or ambiguous creation must be reconciled, never retried as provider invocation.
func WithTaskScheduling ¶
func WithTaskScheduling(config TaskSchedulingConfig) Option
WithTaskScheduling installs optional lifecycle scheduling before Start. The engine requires TaskRunAdmitter and TaskCallGuard after all options are applied, so option ordering does not change authorization requirements. Startup context values carry the host service identity; its cancellation is not the lifetime.
func WithTaskSettlement ¶
func WithTaskSettlement(config coordination.TaskSettlementServiceConfig) Option
WithTaskSettlement installs optional accounting for accepted task runs. The host supplies authorized discovery and reads, closure authority, billing resolution and settlement fencing. Separate optional call-seal ports close ordinary completed journals. This service never invokes task work.
func WithTool ¶
func WithTool(def llm.Tool, h ToolHandler) Option
WithTool registers an externally-provided executable tool. The def is advertised to the LLM (resolveTools); the handler runs when the model calls it (executeTool). Registering tools with the same name appends both; the first match wins at dispatch.
func WithToolAuthorizer ¶
func WithToolAuthorizer(a cortex.ToolAuthorizer) Option
WithToolAuthorizer installs the host's authorization decisions. A nil authorizer, or none at all, allows every tool and every call. A non-nil one needs WithPrincipalCodec as well, so a resumed run reaches it under the principal that started the run.
func WithToolRetrySafe ¶ added in v1.10.0
WithToolRetrySafe marks registered tools as safe to run again after a crash: they only read, or they are idempotent through the effect journal. Every name must be registered with WithTool by the time New returns, or New fails.
func WithToolRevision ¶
WithToolRevision records the host's immutable implementation revision. It is checked on prepared execution and resume; definition hashes are stored too.
func WithVerificationRecovery ¶
func WithVerificationRecovery(config VerificationRecoveryConfig) Option
WithVerificationRecovery installs automatic recovery of captured jobs through the existing worker. It never generates candidates, repeats tools or publishes history. Jobs without durable capture intent remain explicit host work.
func WithVerificationWorker ¶
func WithVerificationWorker(config VerificationWorkerConfig) Option
WithVerificationWorker installs an explicit saved-candidate worker. All ports and durable store capabilities are mandatory, regardless of option order.
func WithWorkerID ¶ added in v1.10.0
WithWorkerID names this engine as a lease owner. Leases, progress snapshots and hand-offs carry it, so it must be unique among the replicas sharing a store and stable for the life of the process. The default is "<hostname>-<pid>-<6 random hex digits>". An empty id fails New.
type OrchestrationRecoveryConfig ¶
type OrchestrationRecoveryConfig struct {
Service coordination.OrchestrationRecoveryConfig
Authorize func(context.Context, id.OrchestrationID) error
}
OrchestrationRecoveryConfig installs the engine's guarded continuation runner. Leave Service.Recoverer unset. Authorize must check the current host service identity for this exact team before recovery and each provider or tool call.
type PlanReplanInputSource ¶
type PlanReplanInputSource interface {
ResolvePlanReplanInput(context.Context, coordination.PlanReplanRequest) (*PreparedAgent, string, error)
}
PlanReplanInputSource resolves the exact prepared proposal configuration and input retained by host identity. It must honor cancellation. The adapter checks both hashes, the agent, explicit tool denial and reserved runtime ceilings.
type PreparedAgent ¶
type PreparedAgent struct {
// contains filtered or unexported fields
}
PreparedAgent holds an immutable, versioned execution snapshot. MarshalJSON returns a copy; no accessor exposes mutable prompt or tool data.
func (*PreparedAgent) Derive ¶
func (p *PreparedAgent) Derive(edits PreparedEdits) (*PreparedAgent, error)
Derive changes only existing unlocked bodies, tool guidance/subsets and temperature in [0,2]. Identity, scope, model, budgets, schema and host implementation pins cannot change. It performs no store or provider reads.
func (*PreparedAgent) Digest ¶
func (p *PreparedAgent) Digest() string
Digest is the SHA-256 identity of the immutable snapshot.
func (*PreparedAgent) Inspect ¶
func (p *PreparedAgent) Inspect() (PreparedView, error)
Inspect returns independently decoded metadata and content.
func (PreparedAgent) MarshalJSON ¶
func (p PreparedAgent) MarshalJSON() ([]byte, error)
MarshalJSON serializes the frozen snapshot with its integrity digest.
func (*PreparedAgent) UnmarshalJSON ¶
func (p *PreparedAgent) UnmarshalJSON(data []byte) error
UnmarshalJSON rejects unsupported versions and payloads whose digest changed.
type PreparedConfig ¶
type PreparedConfig resolvedConfig
PreparedConfig describes frozen settings. Inspection returns detached data.
type PreparedEdits ¶
type PreparedEdits struct {
SectionBodies map[string]string
ToolDescriptions map[string]string
Tools *[]string
Temperature *float64
}
PreparedEdits allows host-approved changes without resolving live sources. Nil Tools keeps the baseline list; a pointer to an empty list denies all. The host must enforce its edit policy and any narrower sampling bounds.
type PreparedOrchestration ¶
type PreparedOrchestration struct {
// contains filtered or unexported fields
}
PreparedOrchestration freezes a strategy and every agent it can invoke. Its digest establishes content integrity, not approval or execution authority.
func (*PreparedOrchestration) Derive ¶
func (p *PreparedOrchestration) Derive(edits map[string]PreparedEdits) (*PreparedOrchestration, error)
Derive applies host-approved edits to existing participants without reading live sources. Each edit uses PreparedAgent.Derive, retaining its authority bounds. Strategy, roster, scope, model, budgets and source snapshot remain frozen. Tool edits may narrow the existing set; they cannot introduce a capability. The host still enforces its participant and section edit policy.
func (*PreparedOrchestration) Digest ¶
func (p *PreparedOrchestration) Digest() string
Digest identifies the frozen team.
func (*PreparedOrchestration) Inspect ¶
func (p *PreparedOrchestration) Inspect() (PreparedOrchestrationView, error)
Inspect returns independently decoded configuration and participant snapshots.
func (PreparedOrchestration) MarshalJSON ¶
func (p PreparedOrchestration) MarshalJSON() ([]byte, error)
MarshalJSON serializes the complete frozen team with its integrity digest.
func (*PreparedOrchestration) UnmarshalJSON ¶
func (p *PreparedOrchestration) UnmarshalJSON(data []byte) error
UnmarshalJSON validates bounded content, participant membership and scope.
type PreparedOrchestrationView ¶
type PreparedOrchestrationView struct {
Config orchestration.Config `json:"config"`
Participants map[string]*PreparedAgent `json:"participants"`
Snapshot run.SourceSnapshot `json:"snapshot"`
}
PreparedOrchestrationView is detached from the originating artifact. Snapshot covers stored sources, not external retrieval or model/tool implementations.
type PreparedRunOptions ¶
type PreparedRunOptions struct {
// OrchestrationBudget applies only to RunPreparedOrchestration. Individual
// execution rejects this field; child allowances remain frozen in artifacts.
OrchestrationBudget *orchestration.BudgetPolicy
SessionID id.SessionID
Purpose run.ExecutionPurpose
Provenance run.ExecutionProvenance
AcceptanceRef string
// RunID pre-assigns the run's id. A run with this id that already
// exists returns cortex.ErrAlreadyExists and nothing runs. Zero lets
// the engine pick one.
RunID id.AgentRunID
// contains filtered or unexported fields
}
PreparedRunOptions contains trusted per-execution identity. It cannot replace the frozen prompt, model, tool allowlist or budget.
type PreparedSourceCheck ¶
type PreparedSourceCheck struct {
PreparedDigest string `json:"prepared_digest"`
SourceCount int `json:"source_count"`
Snapshot run.SourceSnapshot `json:"snapshot"`
}
PreparedSourceCheck binds matching source records to a new atomic observation. It covers only the stored read set, not model/tool implementations, external knowledge, host policy or authorization. It grants no execution authority.
type PreparedStartError ¶
type PreparedStartError struct {
// contains filtered or unexported fields
}
PreparedStartError retains an attempted run identity after startup fails. Creation may have committed despite an error. Inspect durable state before recovery; this error never authorizes retry or proves a terminal state. Error omits private failure details; errors.Is and errors.As retain the cause.
func (*PreparedStartError) Error ¶
func (*PreparedStartError) Error() string
Error returns a public message without storage or captured-content details.
func (*PreparedStartError) RunIdentity ¶
func (e *PreparedStartError) RunIdentity() id.AgentRunID
RunIdentity returns the identity used for the attempted creation.
func (*PreparedStartError) Unwrap ¶
func (e *PreparedStartError) Unwrap() error
Unwrap preserves startup and persistence failures for host-side handling.
type PreparedTaskRunOptions ¶
type PreparedTaskRunOptions struct {
Claim coordination.ClaimToken
DispatchDigest string
Assignment coordination.Assignment
ParentRunRevision int64
RunID id.AgentRunID
SessionID id.SessionID
Dependencies []coordination.AcceptedDependency
Reason string
}
PreparedTaskRunOptions supplies current dispatched ownership and a reserved child identity. These references do not grant authority. The host must use TaskRunAdmitter before creating the child and guard subsequent external calls.
type PreparedTeamMessagingConfig ¶
type PreparedTeamMessagingConfig struct {
AuthorizeTeam func(context.Context, id.OrchestrationID) error
AuthorizeRun func(context.Context, id.OrchestrationID, id.AgentRunID) error
}
PreparedTeamMessagingConfig supplies current host authority for private teams. Callbacks receive exact scope and must honor cancellation. WithA2A supplies the tool definitions; this option permits those tools inside prepared teams. AuthorizeRun also checks assigned child IDs before their run rows are created.
type PreparedView ¶
type PreparedView struct {
AgentID id.AgentID
Scope cortex.Scope
Config PreparedConfig
Sections []prompt.Section
Tools []llm.Tool
Provenance run.ExecutionProvenance
}
PreparedView is a detached view for trusted host inspection and edit policy. Changing it cannot alter its originating snapshot. Tool schema numbers use json.Number to preserve integers beyond float64 precision.
type ReflectionAuthorizer ¶
type ReflectionAuthorizer interface {
AuthorizeReflectionRead(context.Context, cognitive.ReflectionBinding) error
AuthorizeReflection(context.Context, cognitive.ReflectionRequest) error
}
ReflectionAuthorizer checks current caller grants before reads and decisions, including evidence disclosure and the meaning of trusted progress observations.
type ReflectionConfig ¶
type ReflectionConfig struct {
Policy cognitive.ReflectionPolicy
Observer ReflectionObserver
Fence ReflectionFence
Authorizer ReflectionAuthorizer
Replanner *coordination.PlanReplanner
ReplanSource ReflectionReplanSource
Timeout time.Duration
}
ReflectionConfig enables deterministic reflection for normal prepared runs. Proposal runs keep evaluation purpose and never recursively reflect. The optional replan path uses the existing shared-budget prepared runtime.
type ReflectionFence ¶
type ReflectionFence interface {
WithReflectionFence(context.Context, cognitive.ReflectionBinding, func(cognitive.ReflectionBinding) error) error
}
ReflectionFence excludes concurrent user correction and authority revocation until its single synchronous callback returns. All host mutation paths must share this fence. It is not a substitute for normal tool or model authorization.
type ReflectionObservationInput ¶
type ReflectionObservationInput struct {
Binding cognitive.ReflectionBinding
Step int
Usage execution.Usage
}
ReflectionObservationInput exposes execution identity and cumulative usage, never prompts or private reasoning. Its binding cannot be replaced by a model.
type ReflectionObserver ¶
type ReflectionObserver interface {
ObserveReflection(context.Context, ReflectionObservationInput) (cognitive.ReflectionSnapshot, error)
}
ReflectionObserver resolves authenticated progress and retained evidence. No model or side-effect work may run here. Missing observations fail closed.
type ReflectionReplanSource ¶
type ReflectionReplanSource interface {
ResolveReflectionReplan(context.Context, cognitive.ReflectionReceipt) (*coordination.PlanReplanRequest, error)
}
ReflectionReplanSource supplies immutable proposal input from the retained decision. It must not dispatch work. The shared plan must match current task ownership; PlanReplanner still admits budget and rechecks all live authority.
type ReflectionReview ¶
type ReflectionReview struct {
Version int64 `json:"version"`
At time.Time `json:"at"`
Step int `json:"step"`
Decision cognitive.ReflectionDecision `json:"decision"`
State cognitive.ReflectionState `json:"state"`
Assumptions []cognitive.Assumption `json:"assumptions"`
Services []cognitive.ServiceObservation `json:"services"`
EvidenceAvailable bool `json:"evidence_available"`
}
ReflectionReview excludes prompts, private reasoning and intervention text. Assumptions are historical claims; EvidenceAvailable does not certify truth.
type RequiredVerificationConfig ¶
type RequiredVerificationConfig struct {
HandoffAuthorizer ToolHandoffAuthorizer
Revision string
ContractID id.ID
EvaluationBudget verification.EvaluationBudget
Builder VerificationIntentBuilder
CaptureAuthorizer evidence.Authorizer
WorkerOwner string
LeaseDuration time.Duration
}
RequiredVerificationConfig gates prepared, sync, stream and resumed runs. Evaluator tokens are reserved from the total run token budget at preparation. Money limits cover evaluation only. The builder owns context provenance; the capture authorizer checks artifact creation before generation and capture, and input-evidence reads on resume. Tools require both a ToolAuthorizer and HandoffAuthorizer. Checked-segment publication remains unsupported. Other ports and worker settings are required.
type ResultContentConfig ¶
type ResultContentConfig struct {
Authorizer verification.ResultContentAuthorizer
Fence verification.CommitFence
Clock verification.Clock
}
ResultContentConfig supplies current content grants and resource/policy fencing. It is independent of metadata replay permission and verification worker authority. The fence must cover current agent safety-profile changes as policy mutations.
type ResumeInput ¶
type ResumeInput struct {
ToolResults []ToolResult `json:"tool_results"`
// contains filtered or unexported fields
}
ResumeInput is everything a caller supplies to continue a suspended run. One result per pending call, no more and no fewer.
type RunOverrides ¶
type RunOverrides struct {
Model string
Temperature *float64
MaxSteps int
MaxTokens int
ReasoningLoop string
SystemPrompt string
PersonaRef string
InlineSkills []string
InlineTraits []string
InlineBehaviors []string
Tools []string
ToolsRestricted bool
Budget *execution.Budget
SessionID id.SessionID
// RunID pre-assigns the new run's id, which must be an "arun" id, so
// a host that retries a start cannot run the same work twice: a run
// with this id that already exists returns cortex.ErrAlreadyExists and
// nothing runs. Zero lets the engine pick one.
RunID id.AgentRunID
// contains filtered or unexported fields
}
RunOverrides allows overriding agent configuration for a single run.
type RuntimeCapabilities ¶
type RuntimeCapabilities struct {
PreparedExecution bool `json:"prepared_execution"`
AtomicSourceSnapshot bool `json:"atomic_source_snapshot"`
ContextualVerification bool `json:"contextual_verification"`
PublicationGateInstalled bool `json:"publication_gate_installed"`
PublicationMode safety.Mode `json:"publication_mode"`
PublicationRequired bool `json:"publication_required"`
IncrementalGateInstalled bool `json:"incremental_gate_installed"`
VerificationWorker bool `json:"verification_worker"`
VerificationRecovery bool `json:"verification_recovery"`
EffectContinuation bool `json:"effect_continuation"`
BoundedReflection bool `json:"bounded_reflection"`
GovernedContextSummary bool `json:"governed_context_summary"`
CalibrationProvider bool `json:"calibration_provider"`
}
RuntimeCapabilities reports installed mechanisms, not a provider qualification or a guarantee that a particular execution will pass its checks.
type StreamEvent ¶
type StreamEvent struct {
Type StreamEventType `json:"event"`
Data map[string]any `json:"data"`
}
StreamEvent is a single event emitted during streaming execution.
type StreamEventType ¶
type StreamEventType string
StreamEventType identifies the kind of SSE event.
const ( EventRunStarted StreamEventType = "run_started" EventStep StreamEventType = "step" EventToolCall StreamEventType = "tool_call" EventToken StreamEventType = "token" EventCheckpoint StreamEventType = "checkpoint" EventSafetyBlock StreamEventType = "safety_block" EventIncomplete StreamEventType = "incomplete" EventDone StreamEventType = "done" EventError StreamEventType = "error" // EventSuspended is the terminal event of a run that paused instead // of finishing. Its data carries the run id, the reason and the // pending calls the caller has to answer before the run can resume. EventSuspended StreamEventType = "suspended" )
type TaskCallGuard ¶
type TaskCallGuard interface {
AcquireTaskCall(context.Context, TaskCallRequest) (TaskCallLease, error)
}
TaskCallGuard authenticates the context principal and resolves the current child, claim, assignment, parent, prerequisites, grants and shared capacity. AcquireTaskCall must fence every relevant writer, including other processes, through the returned lease. Do not hold database transactions across calls. External services require conditional operations or a declared observation window. Context cancellation is cooperative, not process isolation.
type TaskCallKind ¶
type TaskCallKind string
TaskCallKind identifies the operation covered by one execution lease.
const ( TaskCallComplete TaskCallKind = "complete" TaskCallStream TaskCallKind = "stream" TaskCallTool TaskCallKind = "tool" )
type TaskCallLease ¶
type TaskCallLease struct {
RequestDigest string
ExpiresAt time.Time
Revoked <-chan struct{}
Release func() error
}
TaskCallLease holds current authority until Release. ExpiresAt must not exceed the live claim, parent, grant, prerequisite or request deadline. Close Revoked when authority is withdrawn. Release must be safe once and must not dispatch work. Its failure makes an already invoked operation uncertain.
type TaskCallRequest ¶
type TaskCallRequest struct {
SchemaVersion int `json:"schema_version"`
ID id.ID `json:"id"`
Scope cortex.Scope `json:"scope"`
ClaimID id.ID `json:"claim_id"`
RunID id.AgentRunID `json:"run_id"`
AgentID id.AgentID `json:"agent_id"`
ParentRunID id.AgentRunID `json:"parent_run_id"`
AssignmentDigest string `json:"assignment_digest"`
PreparedDigest string `json:"prepared_digest"`
OperationDigest string `json:"operation_digest"`
Kind TaskCallKind `json:"kind"`
Payload json.RawMessage `json:"payload"`
Deadline time.Time `json:"deadline"`
}
TaskCallRequest binds one private invocation to its durable task identity. Payload contains the exact LLM request or tool call and must not be logged. References identify records to resolve; they are not credentials.
func (TaskCallRequest) Freeze ¶
func (r TaskCallRequest) Freeze() (TaskCallRequest, string, error)
Freeze detaches a bounded invocation and returns its complete binding digest.
type TaskReviewAction ¶
type TaskReviewAction string
TaskReviewAction separates billable execution from retained observation.
const ( // TaskReviewExecute creates the reserved reviewer run once. TaskReviewExecute TaskReviewAction = "execute" // TaskReviewObserve reads a retained reviewer result without dispatch. TaskReviewObserve TaskReviewAction = "observe" )
type TaskReviewAuthorizer ¶
type TaskReviewAuthorizer interface {
AuthorizeTaskReview(context.Context, TaskReviewAction, coordination.TaskCompletion) error
}
TaskReviewAuthorizer authenticates the current actor and independent reviewer under the fence. It must check current plan, producer/reviewer assignments, grants, budget ownership and the requested action, including historical reads.
type TaskReviewFence ¶
type TaskReviewFence interface {
WithTaskReviewFence(context.Context, TaskReviewAction, coordination.TaskCompletion, func(coordination.TaskCompletion) error) error
}
TaskReviewFence holds current plan, assignment, grants and execution authority through one synchronous callback. Execution must permanently exclude any other worker for the reserved RunID, including delayed requests and expired leases. Observe needs current private run/evidence read authority. Never infer authority from stored references or the Fresh field alone.
type TaskReviewRuntimeConfig ¶
type TaskReviewRuntimeConfig struct {
// ExecutionTimeout bounds one dispatch. Zero uses 30 seconds; the maximum
// is 30 minutes. The handoff and caller deadlines can only shorten it.
ExecutionTimeout time.Duration
Resolver TaskReviewWorkResolver
Fence TaskReviewFence
Authorizer TaskReviewAuthorizer
EvidenceAuthorizer evidence.Authorizer
}
TaskReviewRuntimeConfig connects private resolution and explicit current authority. EvidenceAuthorizer separately covers reads of captured private review output.
type TaskReviewWork ¶
type TaskReviewWork struct {
Prepared *PreparedAgent
Input string
Contract verification.Contract
}
TaskReviewWork resolves the exact privately retained reviewer input. Prepared must have no tools and a budget within the reserved handoff allowance.
type TaskReviewWorkResolver ¶
type TaskReviewWorkResolver interface {
ResolveTaskReview(context.Context, coordination.TaskCompletion) (TaskReviewWork, error)
}
TaskReviewWorkResolver reads immutable prepared input without executing work. Honor cancellation. Resolution does not authenticate grants or reserve capacity.
type TaskSchedulingConfig ¶
type TaskSchedulingConfig struct {
Service coordination.TaskServiceConfig
Worker TaskWorkerConfig
}
TaskSchedulingConfig installs host discovery and the engine's prepared task worker. Leave Service.Scheduler.Worker unset; Worker supplies guarded dispatch and work resolution. All other scheduler and lifecycle limits remain explicit.
type TaskWork ¶
type TaskWork struct {
Prepared *PreparedAgent
Dispatch coordination.TaskDispatchRequest
Input string
SessionID id.SessionID
Reason string
}
TaskWork binds a prepared agent and private input to a reserved dispatch. The host resolves an accepted assignment, active parent and current authority. Prepared is an immutable snapshot; these fields do not themselves authorize dispatch, child creation, provider calls or publication.
type TaskWorkResolver ¶
type TaskWorkResolver interface {
ResolveTaskWork(context.Context, coordination.ReadyTaskClaimRequest, coordination.ReadyTaskClaim) (TaskWork, error)
}
TaskWorkResolver supplies the exact private work for one freshly claimed task. Retain stable assignment and child identities before returning. A failure can follow a durable write, so recovery must reconcile those identities. Resolve current grants through the dispatch admitter, never from these stored refs. Resolve definitions only; do not invoke an agent, provider or tool here.
type TaskWorkerConfig ¶
type TaskWorkerConfig struct {
Resolver TaskWorkResolver
Dispatch coordination.TaskDispatchAdmitter
}
TaskWorkerConfig connects scheduler admissions to the prepared engine runtime. Dispatch must use the same durable store as the engine, with current host guards.
type ToolHandler ¶
ToolHandler executes a registered tool. The Invocation carries the scope, the host's principal and the call itself, so a handler never has to reach into the context for them.
func NewEffectToolHandler ¶
func NewEffectToolHandler(executor *execution.EffectExecutor, resolve EffectRequestResolver) (ToolHandler, error)
NewEffectToolHandler adapts the durable executor to WithTool. Register the handler's immutable revision with WithToolRevision and keep the model-facing definition consistent with the executor's host registration. Ordinary tools retain their existing behavior; this helper never wraps arbitrary handlers with a guessed reconciliation or idempotency contract.
The result contains provider outcome and external identity/version. Private evidence references and internal authority bindings stay in the journal. Any unresolved, unavailable or malformed operation stops the engine with ErrEffectUncertain before another tool or model call. A terminal not_applied receipt is returned explicitly; neither outcome proves task correctness.
type ToolHandoffAuthorizer ¶
type ToolHandoffAuthorizer interface {
AuthorizeToolHandoff(context.Context, cortex.Subject) error
}
ToolHandoffAuthorizer checks current access to private pending calls and permission to supply their outcomes. It is separate from tool dispatch policy. The host must check the context principal and exact run scope on every call.
type ToolKind ¶ added in v1.10.0
type ToolKind string
ToolKind says where a tool in the catalog comes from.
const ( // ToolBuiltin is a tool the engine implements itself. ToolBuiltin ToolKind = "builtin" // ToolRegistered is a host tool added with WithTool. ToolRegistered ToolKind = "registered" // ToolExternal is advertised to the model but run by the host, added // with WithExternalTool. ToolExternal ToolKind = "external" )
type ToolResult ¶
type ToolResult struct {
// ToolCallID is the pending call's id, verbatim.
ToolCallID string `json:"tool_call_id"`
// Content is what the tool returned. It goes back to the model as
// the tool message for this call.
Content string `json:"content,omitempty"`
// Error, when non-empty, means the call did not produce a result.
// The model is told so in the same error payload shape an
// engine-side tool failure produces, and Content is ignored.
Error string `json:"error,omitempty"`
// Execute says the call was never run and the engine should run it
// now. It is what an approval produces: a call the authorizer
// escalated was stopped before dispatch, so a human granting it hands
// back permission, not a result, and somebody still has to execute
// the tool.
//
// It exists so approval keeps the one-result-per-pending-call rule
// rather than bending it. Content and Error are ignored when it is
// set. Current authorization is checked again before dispatch; a fresh
// denial still overrides the earlier approval.
//
// Only a tool the engine can run can be executed this way. An
// external tool is answered by supplying its result, since the engine
// is not the thing that runs it.
Execute bool `json:"execute,omitempty"`
}
ToolResult is one pending call's outcome, reported by whoever executed it while the run was paused.
Error exists so a caller whose own execution failed can say so instead of dressing the failure up as a result. That is what keeps the one-terminal-event-per-call rule true across a pause: a resumed call emits ToolCompleted or ToolFailed, never both and never neither.
type VerificationIntentBuilder ¶
type VerificationIntentBuilder interface {
BuildVerificationIntent(context.Context, VerificationIntentInput) (verification.CaptureIntent, error)
}
VerificationIntentBuilder binds host context, evidence retention and stable job/result identities. Building an intent must not dispatch billable work. Cortex validates the returned sealed intent against its frozen requirement.
type VerificationIntentInput ¶
type VerificationIntentInput struct {
Inputs verification.ExecutionInputs
RunID id.AgentRunID
Scope cortex.Scope
PreparedDigest string
Deadline time.Time
}
VerificationIntentInput supplies trusted identity before generation. Deadline includes the caller's narrower deadline. Inputs and Scope are detached. The builder must reference Inputs.Encode() in Context.ExecutionInputs and Binding.Evidence. Cortex authorizes and persists those exact bytes.
type VerificationRecoveryConfig ¶
type VerificationRecoveryConfig struct {
Service coordination.VerificationRecoveryConfig
Authorize func(context.Context, id.ID) error
Owner string
LeaseDuration time.Duration
}
VerificationRecoveryConfig installs current job access and bounded recovery. Leave Service.Recoverer unset. Discovery grants and job grants are independent.
type VerificationRecoveryItem ¶
type VerificationRecoveryItem struct {
JobID id.ID `json:"job_id"`
RunID id.AgentRunID `json:"run_id"`
ResultID id.ID `json:"result_id,omitempty"`
State verification.JobState `json:"state"`
Status VerificationRecoveryStatus `json:"status"`
}
VerificationRecoveryItem contains metadata only. State is the latest validated snapshot observed by this pass; an unavailable operation may have committed.
type VerificationRecoveryLoop ¶
type VerificationRecoveryLoop struct {
Request VerificationRecoveryRequest
Interval time.Duration
Observe func(VerificationRecoveryPage)
}
VerificationRecoveryLoop runs one sequential page per interval. Observe is an optional synchronous host callback for metadata; it must return promptly. Cancellation is joined through the caller rather than a detached goroutine.
type VerificationRecoveryPage ¶
type VerificationRecoveryPage struct {
Items []VerificationRecoveryItem `json:"items"`
NextAfter id.ID `json:"next_after,omitempty"`
}
VerificationRecoveryPage advances past every inspected job, including busy or denied jobs. A zero NextAfter starts the next full scan, avoiding starvation behind old terminal records without requiring an unbounded in-memory queue.
type VerificationRecoveryRequest ¶
type VerificationRecoveryRequest struct {
Owner string
LeaseDuration time.Duration
After id.ID
Limit int
}
VerificationRecoveryRequest bounds one exact-scope scan. Owner identifies this worker; live leases are respected even when their owner string matches.
type VerificationRecoveryStatus ¶
type VerificationRecoveryStatus string
VerificationRecoveryStatus describes recovery work, not public delivery rights.
const ( RecoveryCommitted VerificationRecoveryStatus = "committed" RecoveryTerminal VerificationRecoveryStatus = "terminal" RecoveryBusy VerificationRecoveryStatus = "busy" RecoveryUnmanaged VerificationRecoveryStatus = "unmanaged" RecoveryExpired VerificationRecoveryStatus = "expired" RecoveryUncertain VerificationRecoveryStatus = "uncertain" )
type VerificationRunResult ¶
type VerificationRunResult struct {
Job verification.Job
Receipt *verification.CommitReceipt
}
VerificationRunResult contains the saved job and, only after guarded commit, its historical receipt. Failed, inconclusive and cancelled jobs have no receipt. A receipt is not permission for later public delivery; reauthorize that access.
type VerificationWorkerConfig ¶
type VerificationWorkerConfig struct {
LeaseRenewal *verification.LeaseRenewalPolicy
Adapter verification.EvaluationAdapter
Authorizer verification.BindingAuthorizer
Fence verification.CommitFence
Clock verification.Clock
}
VerificationWorkerConfig supplies trusted services for explicit verification of saved candidates. The host reserves the job budget and captures evidence before calling VerifyRun. This does not gate ordinary run publication.
type VerifyRunRequest ¶
type VerifyRunRequest struct {
Job verification.JobRequest
Claim verification.JobClaim
ResultID id.ID
}
VerifyRunRequest pins an already captured candidate and a stable result ID. Retry uncertain work with the same request. After lease expiry, a new ClaimID may take over the same job; keep ResultID unchanged when recovering a commit.
Source Files
¶
- a2a_crud.go
- a2a_resolution_resume.go
- a2a_tools.go
- a2a_wiring.go
- adaptive_review.go
- admission.go
- agent_reply_recovery_lifecycle.go
- artifact_board_lifecycle.go
- atomic_preparation.go
- calibration.go
- capabilities.go
- clone.go
- cognitive.go
- context_budget.go
- context_summary.go
- continue.go
- conversation_provenance.go
- coordination_event_lifecycle.go
- dashboard.go
- dispatch.go
- effect_continuation_lifecycle.go
- effect_handler.go
- effect_recovery_lifecycle.go
- effects.go
- engine.go
- execution.go
- execution_context.go
- finalize.go
- held_question_recovery.go
- knowledge_provenance.go
- lease.go
- lifecycle.go
- logging.go
- options.go
- orchestration.go
- orchestration_crud.go
- orchestration_expiry_lifecycle.go
- orchestration_recovery_lifecycle.go
- plan_replan_lifecycle.go
- plan_replan_runtime.go
- preparation_capture.go
- prepared.go
- prepared_bindings.go
- prepared_derive.go
- prepared_messaging.go
- prepared_messaging_readiness.go
- prepared_orchestration.go
- prepared_orchestration_binding.go
- prepared_orchestration_compatibility.go
- prepared_orchestration_continuation.go
- prepared_orchestration_derive.go
- prepared_orchestration_runtime.go
- prepared_recipient.go
- prepared_resume.go
- prepared_run.go
- prepared_sources.go
- prepared_start.go
- prepared_task.go
- prepared_task_runtime.go
- prepared_verification_result.go
- principal.go
- progress.go
- prompt.go
- provider_recovery_lifecycle.go
- public_events.go
- publication.go
- publication_stream.go
- react.go
- reclaim.go
- recovery_lifecycle.go
- reflection.go
- reply_route.go
- required_handoff.go
- required_inputs.go
- required_verification.go
- result_content.go
- resume.go
- resume_admission.go
- resume_closure.go
- resume_recovery.go
- run_call_seal.go
- session.go
- source_collection.go
- suspend.go
- sweeper.go
- task_adoption_lifecycle.go
- task_call.go
- task_call_journal.go
- task_completion_lifecycle.go
- task_lifecycle.go
- task_retirement_lifecycle.go
- task_review_runtime.go
- task_settlement_lifecycle.go
- task_worker.go
- telemetry.go
- tool_catalog.go
- tool_publication.go
- tools.go
- verification_recovery.go
- verification_recovery_lifecycle.go
- verification_worker.go