Documentation
¶
Overview ¶
Package cortex provides a human-emulating AI agent orchestration system.
Agents are composed from Skills, Traits, Behaviors, and Personas — just as humans are products of personality, learned skills, and thinking patterns. Host-scoped, plugin-extensible, Forge-native.
Index ¶
- Constants
- Variables
- func IsOrchestrationWaiting(err error) bool
- func PrincipalFromContext(ctx context.Context) any
- func RootTenant(_ context.Context, s Scope) (string, error)
- func ValidateRescopedScope(s Scope) error
- func ValidateScope(s Scope) error
- func WithPrincipal(ctx context.Context, principal any) context.Context
- func WithScope(ctx context.Context, s Scope) context.Context
- type AgentResult
- type AgentRunner
- type ApprovalRequired
- type Config
- type Entity
- type ID
- type Invocation
- type Level
- type MigrateOption
- type MigrateOptions
- type Prefix
- type PrincipalCodec
- type Rescoper
- type ReservedAgentRunner
- type ReservedInvocation
- type RunOpts
- type Scope
- type Subject
- type TenantFunc
- type ToolAuthorizer
Constants ¶
const Version = "1.9.0"
Version is the semantic version of the Cortex module.
Variables ¶
var ( // Store errors. ErrNoStore = errors.New("cortex: no store configured") ErrStoreClosed = errors.New("cortex: store closed") ErrMigrationFailed = errors.New("cortex: migration failed") ErrConversationUnavailable = errors.New("cortex: conversation history unavailable") ErrContextUnavailable = errors.New("cortex: context policy unavailable") // Not found errors. ErrAgentNotFound = errors.New("cortex: agent not found") ErrRunConflict = errors.New("cortex: run revision conflict") ErrRunNotFound = errors.New("cortex: run not found") ErrStepNotFound = errors.New("cortex: step not found") ErrToolCallNotFound = errors.New("cortex: tool call not found") ErrSkillNotFound = errors.New("cortex: skill not found") ErrTraitNotFound = errors.New("cortex: trait not found") ErrBehaviorNotFound = errors.New("cortex: behavior not found") ErrPersonaNotFound = errors.New("cortex: persona not found") ErrSessionNotFound = errors.New("cortex: session not found") ErrCheckpointNotFound = errors.New("cortex: checkpoint not found") ErrOrchestrationNotFound = errors.New("cortex: orchestration not found") ErrOrchestrationRunNotFound = errors.New("cortex: orchestration run not found") ErrOrchestrationRunConflict = errors.New("cortex: orchestration run revision conflict") ErrOrchestrationRunClosed = errors.New("cortex: orchestration run is closed") ErrOrchestrationCoordinatorNotFound = errors.New("cortex: orchestration coordinator not found") ErrOrchestrationInvocationNotFound = errors.New("cortex: orchestration invocation not found") ErrWorkingMemoryNotFound = errors.New("cortex: working memory not found") ErrOverlayNotFound = errors.New("cortex: prompt overlay not found") // Continuation errors. ErrOrchestrationWaiting = errors.New("cortex: orchestration is waiting for a child") // Conflict errors. ErrAlreadyExists = errors.New("cortex: resource already exists") ErrPreparationUnavailable = errors.New("cortex: atomic preparation unavailable") // ErrPreparationConflict requires fresh preparation after an observed source change. ErrPreparationConflict = errors.New("cortex: preparation source changed or unavailable") // Task call errors. ErrTaskRunReconciliationRequired = errors.New("cortex: task run start requires reconciliation") ErrTaskCallUncertain = errors.New("cortex: task call outcome uncertain") ErrInvalidRunCall = errors.New("cortex: invalid run call") ErrRunCallConflict = errors.New("cortex: run call conflict") ErrRunCallNotFound = errors.New("cortex: run call not found") ErrProviderCallUncertain = errors.New("cortex: provider call uncertain") ErrRunCallsSealed = errors.New("cortex: run calls sealed") // Scheduler errors. ErrInvalidScheduler = errors.New("cortex: invalid scheduler configuration or snapshot") ErrSchedulerFull = errors.New("cortex: scheduler queue full") ErrSchedulerStopped = errors.New("cortex: scheduler stopped") ErrSchedulerReconciliationRequired = errors.New("cortex: scheduler admission requires reconciliation") // State errors. ErrInvalidState = errors.New("cortex: invalid state transition") ErrRunCancelled = errors.New("cortex: run cancelled") ErrInvalidPrepared = errors.New("cortex: invalid prepared execution") ErrNoLLM = errors.New("cortex: no model provider configured") ErrRunIncomplete = errors.New("cortex: run incomplete") ErrRunAlreadyDone = errors.New("cortex: run already completed") ErrBudgetExhausted = errors.New("cortex: budget exhausted") ErrMaxStepsReached = errors.New("cortex: maximum steps reached") ErrMaxTokensReached = errors.New("cortex: maximum tokens reached") // ErrEngineStopping refuses a run that would start while Stop drains the // engine. Nothing was written for it; retry on another worker, or after // Start. ErrEngineStopping = errors.New("cortex: engine is stopping") // ErrInvalidDelegationPlan rejects a manager plan before worker dispatch. ErrInvalidDelegationPlan = errors.New("cortex: invalid delegation plan") // Suspension errors. // // ErrNotSuspended is returned by ClaimSuspension to the losing side of // a double resume: the run was not paused (or another caller already // claimed it) when the claim ran. ErrNotSuspended = errors.New("cortex: run not suspended") // ErrSuspensionExpired is returned when a resume targets a suspension // past its ExpiresAt. The suspension row still exists for the expiry // sweep to find and clean up; it is simply no longer resumable. ErrSuspensionExpired = errors.New("cortex: suspension expired") // ErrResultsMismatch is returned when the results a caller supplies to // resume an external-tool suspension do not correspond to the pending // calls it was waiting on. ErrResultsMismatch = errors.New("cortex: suspension results do not match pending calls") // ErrInvalidContinuation is returned when a suspension carries a // continuation the loop cannot run: today that means a zero Config, // which a resume would otherwise read as a step budget of nothing. // // It is its own sentinel rather than ErrMaxStepsReached, which is what // a zero budget looks like from inside the loop. That error is a // matched-on contract meaning "this run used up its steps", and it // sends an operator to raise the budget for a run whose real problem // is a continuation nothing could have resumed. ErrInvalidContinuation = errors.New("cortex: suspension continuation is unusable") // Principal errors. // // ErrPrincipalRevoked is what a PrincipalCodec wraps when a run's // identity is permanently gone: the member was removed, the key // revoked. A resume that meets it fails the run with the codec's // reason rather than continuing under nobody or under the resumer. ErrPrincipalRevoked = errors.New("cortex: principal no longer valid") // decoded right now. A run is not created without its principal, and a // paused run whose principal cannot be decoded stays paused for the // next resume to try again. ErrPrincipalUnavailable = errors.New("cortex: principal unavailable") // ErrPrincipalCodecRequired is returned by engine.New when a tool // authorizer is installed without a principal codec. Without one, // every resumed run would reach the authorizer as nobody. ErrPrincipalCodecRequired = errors.New("cortex: a tool authorizer needs a principal codec so resumed runs keep their principal") // Run continuation errors. // // ErrRunNotContinuable is returned when a continuation targets a run // that is not ready or reclaimable: another replica already continued // it, or it never got that far. ErrRunNotContinuable = errors.New("cortex: run is not ready to continue") // ErrRunLeaseLost is returned to a worker whose lease on a running run // is gone: another worker holds it, or the run left running. The // worker must stop writing the run. ErrRunLeaseLost = errors.New("cortex: run lease lost") // ErrRunLeased is returned when a run's lease has not lapsed yet, so // the run still belongs to the worker holding it. ErrRunLeased = errors.New("cortex: run lease is still held") // run ready or continue one when the store does not implement // run.ContinuationStore. ErrContinuationUnavailable = errors.New("cortex: store cannot hold ready runs") // ErrProgressNotFound is returned when a run has no saved progress // snapshot at the caller's scope. ErrProgressNotFound = errors.New("cortex: run progress not found") // ErrRunInterrupted is returned by a run that its worker handed off // while shutting down. The run is reclaimable, not ended: another // replica continues it from its last saved progress. ErrRunInterrupted = errors.New("cortex: run handed off before it finished") // ErrReclaimLimit fails a run that was reclaimed more often than // engine.WithReclaimLimit allows. A run that takes its worker down every // time it runs is stopped here instead of being handed to the next one. ErrReclaimLimit = errors.New("cortex: run reclaimed too many times") // ErrRunNotRecoverable fails a reclaimed run that left nothing to // continue from: no progress snapshot and no pause it was claimed from. ErrRunNotRecoverable = errors.New("cortex: run has no saved progress to continue from") )
var ( ErrInvalidEvidence = errors.New("cortex: invalid evidence") ErrEvidenceDigestMismatch = errors.New("cortex: evidence digest mismatch") ErrEvidenceAccessDenied = errors.New("cortex: evidence access denied") ErrEvidenceTooLarge = errors.New("cortex: evidence exceeds size limit") ErrEvidenceNotFound = errors.New("cortex: evidence not found") ErrEvidenceDeleted = errors.New("cortex: evidence deleted") ErrEvidenceConflict = errors.New("cortex: immutable evidence conflict") ErrInvalidVerification = errors.New("cortex: invalid verification record") ErrVerificationConflict = errors.New("cortex: immutable verification conflict") ErrVerificationNotFound = errors.New("cortex: verification record not found") ErrVerificationJobNotFound = errors.New("cortex: verification job not found") ErrVerificationJobConflict = errors.New("cortex: verification job ownership conflict") ErrVerificationJobExpired = errors.New("cortex: verification job deadline or attempts exhausted") ErrVerificationJobBudget = errors.New("cortex: verification job budget exhausted") ErrVerificationCallUncertain = errors.New("cortex: verification call already dispatched; reconcile its outcome") ErrRunUnverified = errors.New("cortex: run did not pass required verification") ErrResultAccessDenied = errors.New("cortex: result content access denied") ErrSandboxInputsIncomplete = errors.New("cortex: sandbox input staging is incomplete") ErrSandboxInputsConflict = errors.New("cortex: sandbox input staging identity conflict") )
Evidence and verification errors remain independent of execution outcomes.
var ( ErrInvalidPublicEvent = errors.New("cortex: invalid public event") ErrPublicEventConflict = errors.New("cortex: public event identity or sequence conflict") ErrPublicEventCursorGap = errors.New("cortex: public event cursor expired") ErrPublicEventAccessDenied = errors.New("cortex: public event replay denied") )
Public replay errors distinguish unsupported requests, gaps and unavailable storage.
var ( ErrEffectConflict = errors.New("cortex: effect operation conflicts with retained request") ErrEffectNotFound = errors.New("cortex: effect operation not found") ErrEffectUncertain = errors.New("cortex: effect outcome requires reconciliation") )
Effect errors distinguish a conflicting request from an unresolved external action.
var ( ErrInvalidHandoff = errors.New("cortex: invalid task handoff") )
Handoff errors distinguish invalid proposals from unavailable host admission.
var ( ErrInvalidReservation = errors.New("cortex: invalid budget reservation") ErrReservationConflict = errors.New("cortex: budget reservation conflict") ErrReservationNotFound = errors.New("cortex: budget reservation not found") ErrInvalidTaskAcceptance = errors.New("cortex: invalid task acceptance") ErrInvalidTaskUsage = errors.New("cortex: invalid task usage") ErrTaskUsageConflict = errors.New("cortex: task usage conflict") ErrTaskUsageClosed = errors.New("cortex: task usage admission closed") ErrInvalidTaskSettlement = errors.New("cortex: invalid task usage settlement") ErrTaskSettlementConflict = errors.New("cortex: task usage settlement conflict") ErrTaskAcceptanceConflict = errors.New("cortex: task acceptance conflict") ErrTaskAcceptanceNotFound = errors.New("cortex: task acceptance not found") ErrInvalidClaim = errors.New("cortex: invalid task claim") ErrClaimConflict = errors.New("cortex: task claim conflict") ErrClaimNotFound = errors.New("cortex: task claim not found") ErrInvalidReview = errors.New("cortex: invalid assignment review") ErrReviewConflict = errors.New("cortex: assignment review conflict") ErrReviewNotFound = errors.New("cortex: assignment review not found") ErrInvalidAssignment = errors.New("cortex: invalid assignment") ErrAssignmentConflict = errors.New("cortex: assignment conflict") ErrAssignmentNotFound = errors.New("cortex: assignment not found") )
Assignment errors describe durable progress journal failures.
var ( // ErrInvalidScope identifies an ambiguous or unsupported scope identity. ErrInvalidScope = errors.New("cortex: invalid scope") // ErrUnsupportedScopeDepth means storage cannot enforce every level. ErrUnsupportedScopeDepth = errors.New("cortex: scope exceeds three supported levels") )
var ErrNoRescoper = errors.New("cortex: unscoped rows present and no rescoper supplied")
ErrNoRescoper is returned when a migration finds rows carrying no scope and no Rescoper was supplied. Cortex cannot know what a host's app and tenant strings meant, so it refuses to guess and aborts instead.
var ErrNoScope = errors.New("cortex: no scope on context")
ErrNoScope is returned when an operation that requires a scope receives a zero one. A zero scope means the thread broke somewhere upstream, so failing here is preferable to querying across every host-defined level.
var ErrRequiresApproval = errors.New("cortex: tool call requires approval")
ErrRequiresApproval is the authorizer's third answer. Returning it from Authorize suspends the run and opens a checkpoint rather than denying the call, so a human can decide and the run can carry on afterwards.
It was held back in v1.10.0 on purpose: with nowhere to suspend into, returning it would have read as an ordinary denial and quietly turned "ask someone" into "no".
Functions ¶
func IsOrchestrationWaiting ¶
IsOrchestrationWaiting reports whether every nonnil leaf of an error tree is ErrOrchestrationWaiting. A mixed failure must never be treated as suspension.
func PrincipalFromContext ¶
PrincipalFromContext extracts the caller identity WithPrincipal attached. A missing principal returns nil, mirroring ScopeFromContext's zero-value-on-absence shape rather than panicking.
func RootTenant ¶ added in v1.10.0
RootTenant is the TenantFunc adapters use by default: the value of the scope's first level, which for most hosts is the organization or workspace. It returns ErrNoScope for a zero scope.
func ValidateRescopedScope ¶
ValidateRescopedScope applies shared validation to an operator's legacy mapping.
func ValidateScope ¶
ValidateScope checks the identity the built-in stores can enforce. Keys are unique and ordered. Keys and values must be valid UTF-8; no Unicode normalization is applied. The canonical codec reserves slash and equals.
func WithPrincipal ¶
WithPrincipal attaches the host's caller identity to ctx. Cortex never interprets this value — it only carries it from wherever a host authenticates a request through to Subject.Principal, for a ToolAuthorizer to interpret however its host defines identity.
It travels on the context, alongside Scope, rather than through RunOverrides: both are ambient request identity with the same lifetime, and RunOverrides mirrors a JSON wire type that either can't carry an uninterpreted any or would force cortex to start interpreting it. Dispatch also has no overrides parameter, so a struct field would leave direct dispatch permanently principal-less.
Types ¶
type AgentResult ¶
type AgentResult struct {
AgentName string `json:"agent_name"`
RunID id.AgentRunID `json:"run_id,omitempty"`
Output string `json:"output"`
Err error `json:"-"`
}
AgentResult is the caller-facing view of an agent run. A waiting result retains its identity without a terminal answer; callers must inspect both error values.
type AgentRunner ¶
type AgentRunner interface {
RunAgent(ctx context.Context, agentName, input string, opts *RunOpts) (*AgentResult, error)
}
AgentRunner is the one host capability the coordination packages depend on: run a named agent and hand back its result. The engine satisfies it through a thin adapter, which is what keeps orchestration and a2a from importing the engine.
type ApprovalRequired ¶ added in v1.10.0
type ApprovalRequired struct {
// Reason is shown to the decider and on the checkpoint.
Reason string
// TTL is how long the decision may take. Zero uses the engine's
// suspension TTL. A negative TTL is refused, and the call is denied
// rather than paused with a deadline that has already passed.
TTL time.Duration
}
ApprovalRequired is ErrRequiresApproval with something to say: why the call needs a person, and how long that person has. Return it from Authorize, bare or wrapped, and the run pauses exactly as it does for the sentinel, because errors.Is matches it against ErrRequiresApproval.
The TTL is per call because one engine-wide deadline does not fit every decision. A production deploy can reasonably wait days for the right person, while a routine check that nobody answers within the hour is better failed than left in the queue.
The name breaks the XxxError convention on purpose: it reads as the authorizer's answer, alongside ErrRequiresApproval, at the call site that returns it.
func (ApprovalRequired) Error ¶ added in v1.10.0
func (a ApprovalRequired) Error() string
Error says the call needs approval, and why.
func (ApprovalRequired) Is ¶ added in v1.10.0
func (a ApprovalRequired) Is(target error) bool
Is reports a match for ErrRequiresApproval, so code that only knows the sentinel still recognizes an approval.
type Config ¶
type Config struct {
// DefaultModel is the LLM model used when an agent does not specify one.
DefaultModel string
// DefaultMaxSteps is the maximum reasoning steps per run.
DefaultMaxSteps int
// DefaultMaxTokens is the maximum output tokens per LLM call.
DefaultMaxTokens int
// DefaultTemperature is the LLM sampling temperature.
DefaultTemperature float64
// DefaultReasoningLoop is the reasoning strategy when none is set.
DefaultReasoningLoop string
// ShutdownTimeout is the maximum time to wait for graceful shutdown.
// The Forge extension applies it, bounding Engine.Stop from its own
// Stop; engine.New alone does not read it.
ShutdownTimeout time.Duration
// RunConcurrency is the maximum number of agent runs executing at once,
// zero for no limit (the default). The Forge extension applies it with
// engine.WithRunConcurrency; engine.New alone does not read it.
RunConcurrency int
}
Config holds configuration for the Cortex engine.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
type Entity ¶
type Entity struct {
CreatedAt time.Time `json:"created_at" bun:"created_at,notnull,default:current_timestamp"`
UpdatedAt time.Time `json:"updated_at" bun:"updated_at,notnull,default:current_timestamp"`
}
Entity is the base type embedded by all cortex domain objects.
type Invocation ¶
Invocation is one tool call about to be dispatched. It embeds Subject so a handler receives scope and principal explicitly.
The alternative is leaving handlers to pull those off the context. That works and is idiomatic Go, and it is also the exact pattern that let a tenant identifier sit available and unread until every tenant shared one conversation bucket. An explicit Invocation means a handler that ignores scope has visibly ignored it.
type Level ¶
Level is one rung of a host-defined scope hierarchy. Cortex never interprets Key; it only matches on it.
type MigrateOption ¶
type MigrateOption func(*MigrateOptions)
MigrateOption configures a migration run.
func WithRescoper ¶
func WithRescoper(r Rescoper) MigrateOption
WithRescoper supplies the mapping from legacy identifiers to a Scope.
type MigrateOptions ¶
type MigrateOptions struct {
Rescoper Rescoper
}
MigrateOptions carries everything Migrate needs beyond a context.
func ApplyMigrateOptions ¶
func ApplyMigrateOptions(opts ...MigrateOption) MigrateOptions
ApplyMigrateOptions folds the variadic options into a value. A zero MigrateOptions is valid: a fresh install has no unscoped rows and so never calls the rescoper.
type PrincipalCodec ¶ added in v1.10.0
type PrincipalCodec interface {
EncodePrincipal(ctx context.Context, principal any) ([]byte, error)
// DecodePrincipal restores a run's principal. Return an error wrapping ErrPrincipalRevoked when
// the identity is permanently gone; any other error is treated as transient.
DecodePrincipal(ctx context.Context, data []byte) (any, error)
}
PrincipalCodec carries a run's principal across a pause. A principal lives on the context, and a context does not survive a suspension: the run is stored, and whoever resumes it brings a context of their own. So the engine encodes the principal when it creates a run, stores the bytes with it, and decodes them on every resume, putting the original caller back where the resumer's would otherwise be.
The bytes are the host's own. Cortex stores them and hands them back, and never reads them. A codec can write the whole identity, or only a reference it looks up again on decode, which is also the moment to find out the identity is gone.
func JSONPrincipalCodec ¶ added in v1.10.0
func JSONPrincipalCodec[T any]() PrincipalCodec
JSONPrincipalCodec encodes a principal of type T with json.Marshal and decodes it with json.Unmarshal into a T value, so an authorizer that asserts principal.(T) on a fresh run sees the same type on a resumed one. A principal of any other type is refused rather than written, because it would come back as a T the host never put on the context.
Stored bytes that no longer decode into a T, because they are not JSON or because T changed shape since the run was created, are reported as ErrPrincipalRevoked: retrying cannot change them, so the run is failed rather than left paused. Any other decode error stays transient.
It has no other way to tell a revoked identity from a live one. A host that needs that check writes its own codec, or wraps this one.
type Rescoper ¶
Rescoper maps a row's legacy identifiers onto a Scope during the v1.8.0 upgrade. It is called once per distinct (appID, tenantID) pair, not once per row, so an expensive implementation is fine.
type ReservedAgentRunner ¶
type ReservedAgentRunner interface {
ReserveAgent(context.Context, id.OrchestrationID, string, string, *RunOpts) (*ReservedInvocation, error)
}
ReservedAgentRunner reserves capacity and identity without executing tools or calling a provider. Return the invocation with an error when its identity needs reconciliation. Callers must persist the identity before execution and must never execute an invocation returned with an error.
type ReservedInvocation ¶
type ReservedInvocation struct {
RunID id.AgentRunID
Execute func(context.Context) (*AgentResult, error)
}
ReservedInvocation identifies a child before execution. Execute must start that exact run at most once. Unused allocations remain reserved until the host can prove that releasing them is safe.
type RunOpts ¶
RunOpts is the subset of run overrides a caller needs when invoking an agent through AgentRunner. The engine maps it to its own RunOverrides.
type Scope ¶
type Scope struct {
Levels []Level `json:"levels"`
}
Scope is an ordered hierarchy the host defines. TwinOS uses workspace then project; another host might use org, team, environment. Order is significant: it determines which indexed column each level lands in, so a host must keep its ordering stable across releases.
func DecodeStoredScope ¶
DecodeStoredScope checks that canonical and indexed identity agree. Overflow rows must be inventoried and migrated by an operator, never truncated on read.
func ParseCanonical ¶
ParseCanonical parses a Canonical() string back into a Scope, preserving level order. It is the inverse of Canonical: stores that persist only the canonical string (or the flattened scope_l0/l1/l2 columns plus a scope_canon column) use this to reconstruct Scope on read. An empty string parses to the zero Scope.
A segment that doesn't contain "=" is an error rather than something to skip: silently dropping it would reconstruct a scope NARROWER than what was actually stored, which a caller comparing it against the row's own scope_l0/l1/l2 columns (or using it to authorize a write) would never notice. Callers should treat a non-nil error here as a corrupt row — the same as any other scan failure — rather than falling back to whatever levels did parse.
func RequireScope ¶
RequireScope returns detached, validated request identity. Invalid attached scopes mask their parent and retain a typed error for boundary adapters.
func ScopeFromContext ¶
ScopeFromContext returns detached valid identity, or zero for missing or invalid scope. Use RequireScope at boundaries to preserve the typed error.
func (Scope) Canonical ¶
Canonical renders the scope as "key=value/key=value", preserving order. It is stored alongside the indexed columns so an exact-match lookup does not need to compare three columns separately.
func (Scope) Covers ¶
Covers reports whether s is other, or an ancestor of it: every level s carries appears in other at the same position, with the same key and value. A scope covers itself.
This asks "is s somewhere in other's own ancestry", which is a different question from the prefix matching the stores do on a list. Prefix matching widens DOWNWARD, so a workspace filter reaches every project inside it. Covers reads UPWARD, which is what a project-level run needs when it wants to know what its workspace configured.
type Subject ¶
Subject is who is asking. Principal is host-defined and cortex never interprets it: a host puts whatever its own authorization layer needs there, and gets it back unchanged.
type TenantFunc ¶ added in v1.10.0
TenantFunc names the tenant an external service (a model gateway, a safety engine, a knowledge store) should bill and isolate a call under, given the scope the call runs in. Adapters that talk to such a service take one, so a host can map its own scope to the service's tenant IDs. It returns ErrNoScope, or an error wrapping it, when the scope names no tenant.
type ToolAuthorizer ¶
type ToolAuthorizer interface {
// Visible filters the tool list before it reaches the model. Called
// once per step.
Visible(ctx context.Context, s Subject, tools []llm.Tool) []llm.Tool
// Authorize gates one dispatch. Returning nil allows the call; any
// error denies it, and the error's text is fed back to the model as
// the tool result so it can react rather than silently retrying.
//
// The one exception is ErrRequiresApproval, which is not a denial:
// nothing goes back to the model, the run pauses, and a checkpoint
// carries the call to whoever decides. Wrap it if you want to say
// why (fmt.Errorf("...: %w", cortex.ErrRequiresApproval)); it is
// matched with errors.Is. Return ApprovalRequired instead to put the
// reason on the checkpoint and give the decision its own deadline.
Authorize(ctx context.Context, s Subject, call llm.ToolCall) error
}
ToolAuthorizer decides what the model may see and what it may call. It is consulted at two points because they are different questions: a model can name a tool it was never shown, so filtering the list is not a substitute for gating the call.
A nil authorizer allows everything, so a host that sets none sees no change.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package a2a gives cortex agents direct, addressable communication: FIPA-ACL messages, durable conversations, mailboxes, and an ask that suspends the sender's run until a peer answers.
|
Package a2a gives cortex agents direct, addressable communication: FIPA-ACL messages, durable conversations, mailboxes, and an ask that suspends the sender's run until a peer answers. |
|
Package agent defines the agent configuration entity and its store interface.
|
Package agent defines the agent configuration entity and its store interface. |
|
api
module
|
|
|
Package audithook bridges Cortex lifecycle events to an audit trail backend.
|
Package audithook bridges Cortex lifecycle events to an audit trail backend. |
|
Package behavior defines the Behavior entity — what an agent does.
|
Package behavior defines the Behavior entity — what an agent does. |
|
Package checkpoint defines the Checkpoint entity for human-in-the-loop control.
|
Package checkpoint defines the Checkpoint entity for human-in-the-loop control. |
|
Package cognitive defines persona cognitive settings and trusted operational observations.
|
Package cognitive defines persona cognitive settings and trusted operational observations. |
|
Package communication defines the CommunicationStyle value object — how an agent talks.
|
Package communication defines the CommunicationStyle value object — how an agent talks. |
|
Package coordination defines accountable assignments around Cortex execution.
|
Package coordination defines accountable assignments around Cortex execution. |
|
dashboard
module
|
|
|
Package engine provides the central Cortex agent orchestration coordinator.
|
Package engine provides the central Cortex agent orchestration coordinator. |
|
Package event defines bounded, metadata-only public execution replay.
|
Package event defines bounded, metadata-only public execution replay. |
|
Package evidence defines immutable, scoped artifacts used by result checks.
|
Package evidence defines immutable, scoped artifacts used by result checks. |
|
Package execution defines cumulative execution limits and accounting.
|
Package execution defines cumulative execution limits and accounting. |
|
extension
module
|
|
|
Package id defines TypeID-based identity types for all Cortex entities.
|
Package id defines TypeID-based identity types for all Cortex entities. |
|
integrations
|
|
|
fabriq
module
|
|
|
sandbox
module
|
|
|
internal
|
|
|
hostport
Package hostport validates trusted host interfaces and bounds callback lifetimes.
|
Package hostport validates trusted host interfaces and bounds callback lifetimes. |
|
resulttest
Package resulttest supplies committed-result fixtures for transport tests.
|
Package resulttest supplies committed-result fixtures for transport tests. |
|
streamhttp
Package streamhttp shares HTTP streaming behavior across transport adapters.
|
Package streamhttp shares HTTP streaming behavior across transport adapters. |
|
telemetry
Package telemetry holds the tracing and metrics helpers the engine and the message bus share.
|
Package telemetry holds the tracing and metrics helpers the engine and the message bus share. |
|
telemetry/telemetrytest
Package telemetrytest is a recording metrics sink for cortex's own tests.
|
Package telemetrytest is a recording metrics sink for cortex's own tests. |
|
Package knowledge defines the abstraction for knowledge retrieval providers.
|
Package knowledge defines the abstraction for knowledge retrieval providers. |
|
weave
Package weave adapts the Weave RAG engine to the cortex knowledge.Provider interface.
|
Package weave adapts the Weave RAG engine to the cortex knowledge.Provider interface. |
|
Package learning defines lessons accepted from governed evidence.
|
Package learning defines lessons accepted from governed evidence. |
|
Package llm defines a provider-agnostic LLM client interface for the Cortex engine.
|
Package llm defines a provider-agnostic LLM client interface for the Cortex engine. |
|
nexus
Package nexus adapts the Nexus LLM gateway to the cortex llm.Client interface.
|
Package nexus adapts the Nexus LLM gateway to the cortex llm.Client interface. |
|
mcpbridge
module
|
|
|
Package memory defines the Message entity and memory store interface.
|
Package memory defines the Message entity and memory store interface. |
|
Package observability used to hold Cortex's metrics plugin.
|
Package observability used to hold Cortex's metrics plugin. |
|
optimization
module
|
|
|
Package orchestration coordinates multiple Cortex agents working together, in sequence, in parallel, hierarchically, via a router, or in a debate.
|
Package orchestration coordinates multiple Cortex agents working together, in sequence, in parallel, hierarchically, via a router, or in a debate. |
|
Package perception defines the Perception value object — how an agent sees.
|
Package perception defines the Perception value object — how an agent sees. |
|
Package persona defines the Persona entity — the whole person.
|
Package persona defines the Persona entity — the whole person. |
|
Package planning validates immutable task graphs before a host schedules work.
|
Package planning validates immutable task graphs before a host schedules work. |
|
Package plugin defines the extension system for Cortex.
|
Package plugin defines the extension system for Cortex. |
|
Package prompt models a system prompt as an ordered set of addressable sections rather than one opaque string.
|
Package prompt models a system prompt as an ordered set of addressable sections rather than one opaque string. |
|
Package run defines the Run, Step, and ToolCall entities for agent execution.
|
Package run defines the Run, Step, and ToolCall entities for agent execution. |
|
Package safety defines the interface for content safety scanning in the Cortex agent engine.
|
Package safety defines the interface for content safety scanning in the Cortex agent engine. |
|
rules
Package rules screens bounded text against explicit host-owned regular expressions.
|
Package rules screens bounded text against explicit host-owned regular expressions. |
|
shield
Package shield bridges the Shield safety engine to Cortex: content scans through safety.Scanner and safety.PublicationGate, streamed model output a segment at a time through safety.IncrementalGate, and tool-call scans layered under the host's cortex.ToolAuthorizer (see NewToolAuthorizer).
|
Package shield bridges the Shield safety engine to Cortex: content scans through safety.Scanner and safety.PublicationGate, streamed model output a segment at a time through safety.IncrementalGate, and tool-call scans layered under the host's cortex.ToolAuthorizer (see NewToolAuthorizer). |
|
Package sandbox defines bounded evaluation jobs without importing a runtime.
|
Package sandbox defines bounded evaluation jobs without importing a runtime. |
|
sentinel
module
|
|
|
Package session defines the Session entity and its store interface.
|
Package session defines the Session entity and its store interface. |
|
Package skill defines the Skill entity — what an agent can do.
|
Package skill defines the Skill entity — what an agent can do. |
|
Package store defines the composite store interface for Cortex.
|
Package store defines the composite store interface for Cortex. |
|
internal/assurance
Package assurance shares immutable evidence and report persistence rules.
|
Package assurance shares immutable evidence and report persistence rules. |
|
internal/orchestrationstate
Package orchestrationstate shares atomic child retention across store backends.
|
Package orchestrationstate shares atomic child retention across store backends. |
|
internal/preparation
Package preparation binds snapshot readers to a scope and callback lifetime.
|
Package preparation binds snapshot readers to a scope and callback lifetime. |
|
internal/recipientdiscovery
Package recipientdiscovery validates bounded delivery identity projections.
|
Package recipientdiscovery validates bounded delivery identity projections. |
|
internal/replydiscovery
Package replydiscovery validates bounded suspension identity projections.
|
Package replydiscovery validates bounded suspension identity projections. |
|
internal/runstate
Package runstate encodes storage states that fence unsupported workers.
|
Package runstate encodes storage states that fence unsupported workers. |
|
internal/scopeaudit
Package scopeaudit implements read-only stored-scope inventory shared by adapters.
|
Package scopeaudit implements read-only stored-scope inventory shared by adapters. |
|
mongo
Package mongo provides a MongoDB implementation of the Cortex composite store using Grove ORM with the mongodriver backend.
|
Package mongo provides a MongoDB implementation of the Cortex composite store using Grove ORM with the mongodriver backend. |
|
postgres
Package postgres provides a PostgreSQL implementation of the Cortex composite store using grove ORM with programmatic migrations.
|
Package postgres provides a PostgreSQL implementation of the Cortex composite store using grove ORM with programmatic migrations. |
|
scopespy
Package scopespy provides a recording store double for asserting that every store call made by the engine carries a non-zero scope.
|
Package scopespy provides a recording store double for asserting that every store call made by the engine carries a non-zero scope. |
|
sqlite
Package sqlite provides a SQLite implementation of the Cortex composite store using grove ORM with programmatic migrations.
|
Package sqlite provides a SQLite implementation of the Cortex composite store using grove ORM with programmatic migrations. |
|
storetest
Package storetest is a backend-agnostic conformance suite for store.Store implementations.
|
Package storetest is a backend-agnostic conformance suite for store.Store implementations. |
|
Package suspension defines a paused run and everything needed to continue it.
|
Package suspension defines a paused run and everything needed to continue it. |
|
Package tool builds engine tools from typed Go handlers.
|
Package tool builds engine tools from typed Go handlers. |
|
Package trait defines the Trait entity — who an agent is.
|
Package trait defines the Trait entity — who an agent is. |
|
Package verification defines result assurance independently of execution state.
|
Package verification defines result assurance independently of execution state. |