agentruntime

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: Apache-2.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ToolMemoryRead   = "memory.read"
	ToolMemoryWrite  = "memory.write"
	ToolMemorySearch = "memory.search"
	ToolMemoryList   = "memory.list"
	ToolMemoryIngest = "memory.ingest"
)
View Source
const (
	AuthorizeVerdictAllow            = "allow"
	AuthorizeVerdictDeny             = "deny"
	AuthorizeVerdictApprovalRequired = "approval_required"
)
View Source
const (
	ToolContractVersionV1 = "v1"
	ToolOperationInvoke   = "invoke"
)
View Source
const (
	ToolExecutionStatusOK     = "ok"
	ToolExecutionStatusError  = ToolStatusError
	ToolExecutionStatusDenied = ToolStatusDenied
)
View Source
const (
	ToolStatusError  = "error"
	ToolStatusDenied = "denied"
)
View Source
const (
	ToolCodeInvalidInput         = "invalid_input"
	ToolCodeUnsupportedTool      = "unsupported_tool"
	ToolCodeRuntimePolicyInvalid = "runtime_policy_invalid"
	ToolCodeIsolationUnavailable = "isolation_unavailable"
	ToolCodePermissionDenied     = "permission_denied"
	ToolCodeSecretResolution     = "secret_resolution_failed"
	ToolCodeTimeout              = "timeout"
	ToolCodeCanceled             = "canceled"
	ToolCodeExecutionFailed      = "execution_failed"
	ToolCodeAuthExpired          = "auth_expired"
	ToolCodeAuthInvalid          = "auth_invalid"
	ToolCodeAuthForbidden        = "auth_forbidden"
	ToolCodeApprovalPending      = "approval_pending"
	ToolCodeApprovalDenied       = "approval_denied"
	ToolCodeApprovalTimeout      = "approval_timeout"
)
View Source
const (
	ToolReasonInvalidInput           = "tool_invalid_input"
	ToolReasonToolUnsupported        = "tool_unsupported"
	ToolReasonRuntimePolicyInvalid   = "tool_runtime_policy_invalid"
	ToolReasonIsolationUnavailable   = "tool_isolation_unavailable"
	ToolReasonPermissionDenied       = "tool_permission_denied"
	ToolReasonSecretResolution       = "tool_secret_resolution_failed"
	ToolReasonExecutionTimeout       = "tool_execution_timeout"
	ToolReasonExecutionCanceled      = "tool_execution_canceled"
	ToolReasonBackendFailure         = "tool_backend_failure"
	ToolReasonAuthExpired            = "tool_auth_expired"
	ToolReasonAuthInvalid            = "tool_auth_invalid"
	ToolReasonAuthForbidden          = "tool_auth_forbidden"
	ToolReasonApprovalPending        = "tool_approval_pending"
	ToolReasonApprovalDenied         = "tool_approval_denied"
	ToolReasonApprovalTimeout        = "tool_approval_timeout"
	ToolReasonAgentContractViolation = "agent_contract_violation"
)
View Source
const WASMToolModuleContractVersionV1 = "v1"

Variables

View Source
var (
	ErrUnsupportedTool          = errors.New("unsupported tool")
	ErrToolIsolationUnavailable = errors.New("tool isolation runtime unavailable")
	ErrInvalidToolRuntimePolicy = errors.New("invalid tool runtime policy")
	ErrToolPermissionDenied     = errors.New("tool permission denied")
	ErrToolApprovalRequired     = errors.New("tool approval required")
)
View Source
var ErrModelGatewayConfiguration = errors.New("model gateway configuration error")
View Source
var ErrToolSecretNotFound = errors.New("tool secret not found")
View Source
var ErrToolSecretResolution = errors.New("tool secret resolution failed")

Functions

func BuiltinMemoryToolNames

func BuiltinMemoryToolNames() []string

BuiltinMemoryToolNames returns the sorted list of built-in memory tool names.

func ConfigureMcpRuntime

func ConfigureMcpRuntime(rt ToolRuntime, sessionManager *McpSessionManager, mcpServerStore McpServerLookup, namespace string)

ConfigureMcpRuntime builds and attaches an MCP runtime using the given session manager and server store. The runtime is scoped to the governed runtime's registry and the provided namespace.

func IsApprovalRequiredError

func IsApprovalRequiredError(err error) bool

func IsBuiltinMemoryTool

func IsBuiltinMemoryTool(name string) bool

IsBuiltinMemoryTool returns true if the tool name is a built-in memory tool.

func IsToolDeniedError

func IsToolDeniedError(err error) bool

func IsWASMToolModuleContractError

func IsWASMToolModuleContractError(err error) bool

func NewToolDeniedError

func NewToolDeniedError(message string, details map[string]string, cause error) error

func NewToolError

func NewToolError(
	status string,
	code string,
	reason string,
	retryable bool,
	message string,
	cause error,
	details map[string]string,
) error

func RedactSensitive

func RedactSensitive(s string) string

RedactSensitive replaces known sensitive patterns (auth headers, API keys, tokens) in s with a redacted placeholder. This is applied as defense-in-depth before including process output (stderr, error messages) in logs or traces.

func RegisterModelProvider

func RegisterModelProvider(plugin ModelProviderPlugin) error

RegisterModelProvider registers a plugin globally for model gateway and router usage.

func RegisterToolIsolationBackend

func RegisterToolIsolationBackend(mode string, factory ToolIsolationBackendFactory) error

func RetryAfter

func RetryAfter(delay time.Duration, cause error) error

RetryAfter builds a handler error that asks the bus to requeue this delivery after delay.

func ToolApprovalScopedStoreKey

func ToolApprovalScopedStoreKey(taskKey, messageID string) string

ToolApprovalScopedStoreKey returns the same lookup key used for ToolApproval resources created by pauseTaskForToolApproval (namespace/name).

func ToolErrorMeta

func ToolErrorMeta(err error) (code string, reason string, retryable bool, ok bool)

func ValidateEndpointURL

func ValidateEndpointURL(rawURL string, allowPrivate bool) error

ValidateEndpointURL checks that a URL is safe for outbound requests from tool and MCP runtimes. It blocks dangerous URL schemes and, when the host is a literal IP address, rejects loopback, link-local, cloud metadata, and (optionally) private addresses.

When the host is a hostname (not a literal IP), scheme validation still applies but IP-level checks are deferred to the transport layer.

Pass allowPrivate=true to skip the private/internal address checks (e.g. for development or explicitly trusted internal services).

Types

type AgentExecutionResult

type AgentExecutionResult struct {
	Agent           string
	Model           string
	Steps           int
	ToolCalls       int
	MemoryWrites    int
	EstimatedTokens int
	TokensUsed      int
	TokenSource     string
	Duration        time.Duration
	Output          string
	LastEvent       string
	Events          []string
	StepEvents      []AgentStepEvent
}

AgentExecutionResult captures task-time execution details for one agent.

type AgentMessage

type AgentMessage struct {
	MessageID      string `json:"message_id,omitempty"`
	IdempotencyKey string `json:"idempotency_key,omitempty"`
	TaskID         string `json:"task_id,omitempty"`
	Attempt        int    `json:"attempt,omitempty"`
	System         string `json:"system,omitempty"`
	Namespace      string `json:"namespace,omitempty"`
	FromAgent      string `json:"from_agent,omitempty"`
	ToAgent        string `json:"to_agent,omitempty"`
	BranchID       string `json:"branch_id,omitempty"`
	ParentBranchID string `json:"parent_branch_id,omitempty"`
	Type           string `json:"type,omitempty"`
	Payload        string `json:"payload,omitempty"`
	Timestamp      string `json:"timestamp,omitempty"`
	TraceID        string `json:"trace_id,omitempty"`
	ParentID       string `json:"parent_id,omitempty"`
}

AgentMessage is the runtime envelope exchanged between agents.

type AgentMessageBus

type AgentMessageBus interface {
	Publish(context.Context, AgentMessage) (AgentMessage, error)
	Consume(context.Context, AgentMessageSubscription, AgentMessageHandler) error
	Close() error
}

AgentMessageBus is the runtime data-plane contract for agent messaging.

type AgentMessageConsumerManager

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

AgentMessageConsumerManager watches agents and consumes runtime inbox messages per agent.

func (*AgentMessageConsumerManager) Start

type AgentMessageConsumerOptions

type AgentMessageConsumerOptions struct {
	WorkerID            string
	Namespace           string
	RefreshEvery        time.Duration
	DedupeWindow        time.Duration
	ConsumerDelay       time.Duration
	LeaseExtendDuration time.Duration
	Executor            *TaskExecutor
	Tools               ToolResourceLookup
	Roles               AgentRoleLookup
	ToolPermissions     ToolPermissionLookup
	IsolatedToolRuntime ToolRuntime
	McpSessionManager   *McpSessionManager
	McpServerStore      McpServerLookup
	Extensions          Extensions
	Memories            MemoryResourceLookup
	MemoryBackends      *PersistentMemoryBackendRegistry
	ModelEndpoints      resources.ModelEndpointLookup
	ToolApprovals       ToolApprovalUpserter
}

AgentMessageConsumerOptions configures inbox consumers in a worker.

type AgentMessageDelivery

type AgentMessageDelivery interface {
	Message() AgentMessage
	Ack(context.Context) error
	Nack(context.Context, bool) error
	NackWithDelay(context.Context, time.Duration) error
	ExtendLease(context.Context, time.Duration) error
}

AgentMessageDelivery represents one delivery instance with ack semantics.

type AgentMessageHandler

type AgentMessageHandler func(context.Context, AgentMessageDelivery) error

AgentMessageHandler processes one message delivery.

type AgentMessageSubscription

type AgentMessageSubscription struct {
	Namespace string
	Agent     string
	Durable   string
}

AgentMessageSubscription identifies a consumer input stream.

type AgentRegistry

type AgentRegistry interface {
	List(ctx context.Context) ([]resources.Agent, error)
	Get(ctx context.Context, name string) (resources.Agent, bool, error)
}

AgentRegistry lists and resolves declared agents for message consumer subscriptions/execution.

type AgentRoleLookup

type AgentRoleLookup interface {
	Get(ctx context.Context, name string) (resources.AgentRole, bool, error)
}

type AgentStepEvent

type AgentStepEvent struct {
	Timestamp           string
	Type                string
	Step                int
	Tool                string
	Message             string
	ErrorCode           string
	ErrorReason         string
	Retryable           *bool
	ToolContractVersion string
	ToolRequestID       string
	ToolAttempt         int
	LatencyMS           int64
	Tokens              int
	InputTokens         int
	OutputTokens        int
	UsageSource         string
	ToolAuthProfile     string
	ToolAuthSecretRef   string
}

AgentStepEvent is one structured runtime event emitted during agent execution.

type AgentSystemRegistry

type AgentSystemRegistry interface {
	Get(ctx context.Context, name string) (resources.AgentSystem, bool, error)
}

AgentSystemRegistry resolves AgentSystem resources for next-hop routing.

type AgentToolAuthorizer

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

func NewAgentToolAuthorizer

func NewAgentToolAuthorizer(
	ctx context.Context,
	namespace string,
	agent resources.Agent,
	roleLookup AgentRoleLookup,
	permissionLookup ToolPermissionLookup,
) *AgentToolAuthorizer

func (*AgentToolAuthorizer) Authorize

func (a *AgentToolAuthorizer) Authorize(tool string, spec resources.ToolSpec) (*AuthorizeResult, error)

type AgentWorker

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

AgentWorker runs the core execution loop for one agent.

func NewAgentWorker

func NewAgentWorker(agent resources.Agent, toolRuntime ToolRuntime, memory MemoryStore, onEvent func(string)) *AgentWorker

func NewAgentWorkerWithInterval

func NewAgentWorkerWithInterval(agent resources.Agent, toolRuntime ToolRuntime, memory MemoryStore, onEvent func(string), stepEvery time.Duration) *AgentWorker

func NewAgentWorkerWithIntervalAndGateway

func NewAgentWorkerWithIntervalAndGateway(
	agent resources.Agent,
	toolRuntime ToolRuntime,
	memory MemoryStore,
	modelGateway ModelGateway,
	onEvent func(string),
	stepEvery time.Duration,
) *AgentWorker

func NewAgentWorkerWithIntervalAndGatewayAndInput

func NewAgentWorkerWithIntervalAndGatewayAndInput(
	agent resources.Agent,
	toolRuntime ToolRuntime,
	memory MemoryStore,
	modelGateway ModelGateway,
	input map[string]string,
	onEvent func(string),
	stepEvery time.Duration,
) *AgentWorker

func (*AgentWorker) Run

func (w *AgentWorker) Run(ctx context.Context)

func (*AgentWorker) SetToolSchemas

func (w *AgentWorker) SetToolSchemas(schemas map[string]ToolSchemaInfo)

SetToolSchemas attaches per-tool description and JSON Schema metadata. Model gateways use these to provide rich tool definitions to the LLM instead of the generic {input: string} fallback.

type AnthropicModelGateway

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

AnthropicModelGateway calls the Anthropic Messages API.

func (*AnthropicModelGateway) Complete

type AnthropicModelGatewayConfig

type AnthropicModelGatewayConfig struct {
	APIKey           string
	BaseURL          string
	DefaultModel     string
	AnthropicVersion string
	MaxTokens        int
	Timeout          time.Duration
	HTTPClient       *http.Client
}

AnthropicModelGatewayConfig defines Anthropic Messages API settings.

func DefaultAnthropicModelGatewayConfig

func DefaultAnthropicModelGatewayConfig() AnthropicModelGatewayConfig

DefaultAnthropicModelGatewayConfig returns Anthropic gateway defaults.

type AuditEvent

type AuditEvent struct {
	Timestamp    string            `json:"timestamp"`
	Component    string            `json:"component,omitempty"`
	Action       string            `json:"action"`
	Outcome      string            `json:"outcome"`
	Namespace    string            `json:"namespace,omitempty"`
	ResourceKind string            `json:"resource_kind,omitempty"`
	ResourceName string            `json:"resource_name,omitempty"`
	Principal    string            `json:"principal,omitempty"`
	Message      string            `json:"message,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

AuditEvent captures one normalized audit event for optional external audit sinks.

type AuditSink

type AuditSink interface {
	RecordAudit(ctx context.Context, event AuditEvent)
}

AuditSink receives audit events. Implementations should be non-blocking and resilient.

type AuthInjector

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

AuthInjector centralizes auth resolution for all tool runtime backends. It resolves Tool.spec.auth into concrete headers/env based on the auth profile.

func NewAuthInjector

func NewAuthInjector(secrets SecretResolver, tokenCache *OAuth2TokenCache) *AuthInjector

func (*AuthInjector) EvictOAuth2Token

func (a *AuthInjector) EvictOAuth2Token(tokenURL, clientID string)

EvictOAuth2Token removes a cached OAuth2 token, used on 401 responses.

func (*AuthInjector) Resolve

func (a *AuthInjector) Resolve(ctx context.Context, toolName string, auth resources.ToolAuth) (AuthResult, error)

Resolve produces an AuthResult for the given tool auth config. Returns an empty AuthResult (no error) when no auth is configured.

type AuthResult

type AuthResult struct {
	Headers map[string]string
	EnvVars map[string]string
	Profile string
}

AuthResult holds resolved authentication artifacts for tool backends. Headers are used by HTTP-based backends; EnvVars are used by the container backend.

type AuthorizeResult

type AuthorizeResult struct {
	Verdict string
	Reason  string
	Details map[string]string
}

type AzureOpenAIModelGateway

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

AzureOpenAIModelGateway calls Azure OpenAI chat completions API.

func (*AzureOpenAIModelGateway) Complete

type AzureOpenAIModelGatewayConfig

type AzureOpenAIModelGatewayConfig struct {
	APIKey            string
	BaseURL           string
	DefaultDeployment string
	APIVersion        string
	Timeout           time.Duration
	HTTPClient        *http.Client
}

AzureOpenAIModelGatewayConfig defines Azure OpenAI chat completion settings.

func DefaultAzureOpenAIModelGatewayConfig

func DefaultAzureOpenAIModelGatewayConfig() AzureOpenAIModelGatewayConfig

DefaultAzureOpenAIModelGatewayConfig returns Azure OpenAI gateway defaults.

type Capability

type Capability struct {
	ID          string `json:"id"`
	Enabled     bool   `json:"enabled"`
	Description string `json:"description,omitempty"`
	Source      string `json:"source,omitempty"`
}

Capability describes one discoverable feature exposed by the current runtime.

type CapabilityProvider

type CapabilityProvider interface {
	Capabilities(ctx context.Context) CapabilitySnapshot
}

CapabilityProvider returns deployment capabilities for API/UI/CLI feature discovery.

type CapabilitySnapshot

type CapabilitySnapshot struct {
	GeneratedAt  string       `json:"generated_at"`
	Capabilities []Capability `json:"capabilities"`
}

CapabilitySnapshot returns the effective capability set for this deployment.

type ChainSecretResolver

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

func NewChainSecretResolver

func NewChainSecretResolver(resolvers ...SecretResolver) *ChainSecretResolver

func (*ChainSecretResolver) Resolve

func (r *ChainSecretResolver) Resolve(ctx context.Context, secretRef string) (string, error)

func (*ChainSecretResolver) WithNamespace

func (r *ChainSecretResolver) WithNamespace(namespace string) SecretResolver

type ChatMessage

type ChatMessage struct {
	Role       string // "system", "user", "assistant", "tool"
	Content    string
	ToolCallID string         // role="tool": the ID of the tool call this result answers
	ToolCalls  []ChatToolCall // role="assistant": tool calls the model made this turn
}

ChatMessage represents one message in a multi-turn conversation.

type ChatToolCall

type ChatToolCall struct {
	ID    string
	Name  string
	Input string
}

ChatToolCall captures one tool invocation from an assistant message.

type Chunk

type Chunk struct {
	Index  int    `json:"index"`
	Text   string `json:"text"`
	Offset int    `json:"offset"`
}

Chunk represents one segment of a chunked document.

func ChunkText

func ChunkText(text string, chunkSize, overlap int) []Chunk

ChunkText splits text into overlapping windows of chunkSize characters. overlap controls how many characters from the end of the previous chunk are repeated at the start of the next. Zero or negative values are replaced with sensible defaults (1000 / 200).

type ContainerCommandRunner

type ContainerCommandRunner interface {
	Run(ctx context.Context, binary string, args []string, stdin string, env map[string]string) (stdout string, stderr string, err error)
}

ContainerCommandRunner executes container runtime commands.

type ContainerToolRuntime

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

ContainerToolRuntime executes tools inside a containerized sandbox.

func NewContainerToolRuntimeWithRunnerAndSecrets

func NewContainerToolRuntimeWithRunnerAndSecrets(
	registry ToolCapabilityRegistry,
	config ContainerToolRuntimeConfig,
	runner ContainerCommandRunner,
	secrets SecretResolver,
) *ContainerToolRuntime

func (*ContainerToolRuntime) Call

func (r *ContainerToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*ContainerToolRuntime) WithNamespace

func (r *ContainerToolRuntime) WithNamespace(namespace string) ToolRuntime

func (*ContainerToolRuntime) WithRegistry

func (r *ContainerToolRuntime) WithRegistry(registry ToolCapabilityRegistry) ToolRuntime

type ContainerToolRuntimeConfig

type ContainerToolRuntimeConfig struct {
	RuntimeBinary string
	Image         string
	Network       string
	Memory        string
	CPUs          string
	PidsLimit     int
	User          string
	Shell         string
}

ContainerToolRuntimeConfig defines isolated tool execution in a locked-down container.

func DefaultContainerToolRuntimeConfig

func DefaultContainerToolRuntimeConfig() ContainerToolRuntimeConfig

func SandboxedContainerDefaults

func SandboxedContainerDefaults() ContainerToolRuntimeConfig

SandboxedContainerDefaults returns secure-by-default container settings for tools running in sandboxed isolation mode. These enforce:

  • network=none (no network access)
  • memory=128m (128 MB ceiling)
  • cpus=0.50 (half a core)
  • pids_limit=64 (process limit)
  • user=65532:65532 (non-root nobody user)
  • read-only filesystem (via containerRunArgs --read-only)
  • no Linux capabilities (via --cap-drop=ALL)
  • no privilege escalation (via --security-opt no-new-privileges)

These defaults match DefaultContainerToolRuntimeConfig but are preserved as an explicit contract so callers can distinguish between default and sandboxed modes.

type EmbeddingProvider

type EmbeddingProvider interface {
	Embed(ctx context.Context, texts []string) ([][]float32, error)
	Dimensions() int
}

EmbeddingProvider generates vector embeddings from text. Implementations are used by vector-database memory backends (e.g. pgvector) to embed values on write and queries on search.

type EnvSecretResolver

type EnvSecretResolver struct {
	Prefix string
}

EnvSecretResolver resolves secret refs from worker environment variables.

func NewEnvSecretResolver

func NewEnvSecretResolver(prefix string) *EnvSecretResolver

func (*EnvSecretResolver) Resolve

func (r *EnvSecretResolver) Resolve(_ context.Context, secretRef string) (string, error)

func (*EnvSecretResolver) WithNamespace

func (r *EnvSecretResolver) WithNamespace(_ string) SecretResolver

type ExecutionEngine

type ExecutionEngine interface {
	Execute(ctx context.Context, agent resources.Agent, input map[string]string) (AgentExecutionResult, error)
}

ExecutionEngine orchestrates one agent execution loop.

type Extensions

type Extensions struct {
	Metering     MeteringSink
	Audit        AuditSink
	Capabilities CapabilityProvider
}

Extensions groups optional runtime hooks for add-on integrations.

func DefaultExtensions

func DefaultExtensions() Extensions

DefaultExtensions returns OSS-safe defaults for all extension hooks.

func NormalizeExtensions

func NormalizeExtensions(ext Extensions) Extensions

NormalizeExtensions applies safe defaults so callers can omit all optional hooks.

type ExternalToolRuntime

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

ExternalToolRuntime delegates tool execution to an external HTTP service. Tools with spec.type=external have their ToolExecutionRequest forwarded to spec.endpoint and the ToolExecutionResponse parsed from the reply.

func NewExternalToolRuntime

func NewExternalToolRuntime(registry ToolCapabilityRegistry, secrets SecretResolver, client HTTPDoer) *ExternalToolRuntime

func (*ExternalToolRuntime) Call

func (r *ExternalToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*ExternalToolRuntime) WithNamespace

func (r *ExternalToolRuntime) WithNamespace(namespace string) ToolRuntime

func (*ExternalToolRuntime) WithRegistry

func (r *ExternalToolRuntime) WithRegistry(registry ToolCapabilityRegistry) ToolRuntime

type GRPCDialer

type GRPCDialer interface {
	DialContext(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error)
}

GRPCDialer abstracts gRPC connection establishment for testing.

type GRPCToolRuntime

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

GRPCToolRuntime executes tools via a unary gRPC call to an external service. The service must implement orloj.tool.v1.ToolService/Execute accepting ToolExecutionRequest and returning ToolExecutionResponse as JSON payloads.

func NewGRPCToolRuntime

func NewGRPCToolRuntime(registry ToolCapabilityRegistry, secrets SecretResolver, dialer GRPCDialer) *GRPCToolRuntime

func (*GRPCToolRuntime) Call

func (r *GRPCToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*GRPCToolRuntime) SetAllowInsecure

func (r *GRPCToolRuntime) SetAllowInsecure(allow bool)

SetAllowInsecure enables plaintext gRPC connections. This should only be used in development or when the transport is otherwise secured (e.g. service mesh with mTLS). Callers must explicitly opt in.

func (*GRPCToolRuntime) WithNamespace

func (r *GRPCToolRuntime) WithNamespace(namespace string) ToolRuntime

func (*GRPCToolRuntime) WithRegistry

func (r *GRPCToolRuntime) WithRegistry(registry ToolCapabilityRegistry) ToolRuntime

type GovernedToolApprovalContext

type GovernedToolApprovalContext struct {
	Getter    func(key string) (resources.ToolApproval, bool, error)
	TaskKey   string
	MessageID string
}

GovernedToolApprovalContext optionally lets the governed tool runtime treat an existing Approved ToolApproval (same key as pauseTaskForToolApproval) as a grant to invoke the tool, so resuming a message after approval does not loop on approval_required for every fresh agent worker run.

type GovernedToolRuntime

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

GovernedToolRuntime enforces per-tool policy (timeout/retry/isolation) using Tool CRD runtime metadata.

func NewGovernedToolRuntime

func NewGovernedToolRuntime(
	baseRuntime ToolRuntime,
	isolatedRuntime ToolRuntime,
	registry ToolCapabilityRegistry,
	strict bool,
) *GovernedToolRuntime

func NewGovernedToolRuntimeWithAuthorizer

func NewGovernedToolRuntimeWithAuthorizer(
	baseRuntime ToolRuntime,
	isolatedRuntime ToolRuntime,
	registry ToolCapabilityRegistry,
	authorizer ToolCallAuthorizer,
	strict bool,
) *GovernedToolRuntime

func (*GovernedToolRuntime) Call

func (r *GovernedToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*GovernedToolRuntime) ResolveToolSchemas

func (r *GovernedToolRuntime) ResolveToolSchemas(toolNames []string) map[string]ToolSchemaInfo

ResolveToolSchemas returns description and input schema metadata for the given tool names, sourced from the underlying ToolCapabilityRegistry.

func (*GovernedToolRuntime) SetMcpRuntime

func (r *GovernedToolRuntime) SetMcpRuntime(mcpRuntime ToolRuntime)

SetMcpRuntime configures the MCP tool runtime used for type=mcp tools.

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer abstracts HTTP request execution for testing.

type HTTPMemoryBackend

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

HTTPMemoryBackend implements PersistentMemoryBackend by delegating to an external HTTP service that speaks the Orloj memory provider contract. See docs/pages/concepts/memory.md for the contract specification.

func NewHTTPMemoryBackend

func NewHTTPMemoryBackend(endpoint, authToken string) *HTTPMemoryBackend

func (*HTTPMemoryBackend) Get

func (b *HTTPMemoryBackend) Get(ctx context.Context, key string) (string, bool, error)

func (*HTTPMemoryBackend) List

func (b *HTTPMemoryBackend) List(ctx context.Context, prefix string) ([]MemorySearchResult, error)

func (*HTTPMemoryBackend) Ping

func (b *HTTPMemoryBackend) Ping(ctx context.Context) error

func (*HTTPMemoryBackend) Put

func (b *HTTPMemoryBackend) Put(ctx context.Context, key, value string) error

func (*HTTPMemoryBackend) Search

func (b *HTTPMemoryBackend) Search(ctx context.Context, query string, topK int) ([]MemorySearchResult, error)

type HTTPToolClient

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

HTTPToolClient executes tools via HTTP POST against Tool.spec.endpoint. It replaces MockToolClient as the base runtime for isolation_mode=none.

func NewHTTPToolClient

func NewHTTPToolClient(registry ToolCapabilityRegistry, secrets SecretResolver, client HTTPDoer) *HTTPToolClient

func NewHTTPToolClientWithAuth

func NewHTTPToolClientWithAuth(registry ToolCapabilityRegistry, injector *AuthInjector, client HTTPDoer) *HTTPToolClient

func (*HTTPToolClient) Call

func (r *HTTPToolClient) Call(ctx context.Context, tool string, input string) (string, error)

func (*HTTPToolClient) SetAllowPrivateEndpoints

func (r *HTTPToolClient) SetAllowPrivateEndpoints(allow bool)

SetAllowPrivateEndpoints permits HTTP tool calls to private/internal IP ranges (RFC 1918). Loopback and cloud metadata addresses are always blocked.

func (*HTTPToolClient) WithNamespace

func (r *HTTPToolClient) WithNamespace(namespace string) ToolRuntime

func (*HTTPToolClient) WithRegistry

func (r *HTTPToolClient) WithRegistry(registry ToolCapabilityRegistry) ToolRuntime

type InMemoryBackend

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

InMemoryBackend is a PersistentMemoryBackend backed by an in-process map. Useful for testing and single-instance deployments.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

func (*InMemoryBackend) Get

func (b *InMemoryBackend) Get(_ context.Context, key string) (string, bool, error)

func (*InMemoryBackend) List

func (*InMemoryBackend) Ping

func (b *InMemoryBackend) Ping(_ context.Context) error

func (*InMemoryBackend) Put

func (b *InMemoryBackend) Put(_ context.Context, key, value string) error

func (*InMemoryBackend) Search

func (b *InMemoryBackend) Search(_ context.Context, query string, topK int) ([]MemorySearchResult, error)

type MCPToolRuntime

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

MCPToolRuntime executes tool calls against MCP servers. It resolves the mcp_server_ref from the tool's ToolSpec, retrieves the session from the McpSessionManager, and delegates to tools/call.

func NewMCPToolRuntime

func NewMCPToolRuntime(
	registry ToolCapabilityRegistry,
	sessionManager *McpSessionManager,
	mcpServerStore McpServerLookup,
) *MCPToolRuntime

func (*MCPToolRuntime) Call

func (r *MCPToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*MCPToolRuntime) WithNamespace

func (r *MCPToolRuntime) WithNamespace(namespace string) ToolRuntime

func (*MCPToolRuntime) WithRegistry

func (r *MCPToolRuntime) WithRegistry(registry ToolCapabilityRegistry) ToolRuntime

type Manager

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

Manager tracks and reconciles running workers.

func NewManager

func NewManager(logger *log.Logger) *Manager

func (*Manager) EnsureRunning

func (m *Manager) EnsureRunning(agent resources.Agent)

func (*Manager) IsRunning

func (m *Manager) IsRunning(name string) bool

func (*Manager) Logs

func (m *Manager) Logs(name string) []string

func (*Manager) RunningAgents

func (m *Manager) RunningAgents() []string

func (*Manager) Stop

func (m *Manager) Stop(name string)

type McpCapabilities

type McpCapabilities struct {
	Tools *McpToolCapability `json:"tools,omitempty"`
}

type McpContent

type McpContent struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

McpContent is one content block in a tool result.

type McpInitResult

type McpInitResult struct {
	ProtocolVersion string          `json:"protocolVersion"`
	ServerInfo      McpServerInfo   `json:"serverInfo"`
	Capabilities    McpCapabilities `json:"capabilities"`
}

McpInitResult captures the server's response to the initialize handshake.

type McpServerInfo

type McpServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`
}

type McpServerLookup

type McpServerLookup interface {
	Get(ctx context.Context, name string) (resources.McpServer, bool, error)
}

McpServerLookup resolves McpServer resources by scoped name.

type McpSession

type McpSession struct {
	Transport  McpTransport
	InitResult *McpInitResult
	ServerName string
}

McpSession wraps one active connection to an MCP server.

type McpSessionManager

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

McpSessionManager maintains one session per McpServer, handling connection pooling, initialization, and graceful shutdown.

func NewMcpSessionManager

func NewMcpSessionManager(secretResolver SecretResolver) *McpSessionManager

func (*McpSessionManager) Close

func (m *McpSessionManager) Close()

Close shuts down all active sessions.

func (*McpSessionManager) GetOrCreate

func (m *McpSessionManager) GetOrCreate(ctx context.Context, server resources.McpServer) (*McpSession, error)

GetOrCreate returns an existing session or creates a new one for the given McpServer spec. Sessions are keyed by namespace/name.

func (*McpSessionManager) Remove

func (m *McpSessionManager) Remove(server resources.McpServer)

Remove closes and removes the session for the given server.

func (*McpSessionManager) SetAllowedCommands

func (m *McpSessionManager) SetAllowedCommands(cmds []string)

SetAllowedCommands restricts the binaries that stdio MCP transports may execute. An empty list means "no restriction" (backwards-compatible). When set, only the basename (or full path) of spec.command must appear in the list for the transport to start.

type McpToolCapability

type McpToolCapability struct {
	ListChanged bool `json:"listChanged,omitempty"`
}

type McpToolDefinition

type McpToolDefinition struct {
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema,omitempty"`
}

McpToolDefinition describes one tool exposed by an MCP server via tools/list.

type McpToolResult

type McpToolResult struct {
	Content []McpContent `json:"content"`
	IsError bool         `json:"isError,omitempty"`
}

McpToolResult captures the response from a tools/call invocation.

func (*McpToolResult) McpTextResult

func (r *McpToolResult) McpTextResult() string

McpTextResult returns the concatenated text content of a tool result.

type McpTransport

type McpTransport interface {
	Initialize(ctx context.Context) (*McpInitResult, error)
	ListTools(ctx context.Context) ([]McpToolDefinition, error)
	CallTool(ctx context.Context, name string, arguments map[string]any) (*McpToolResult, error)
	Close() error
}

McpTransport abstracts the MCP JSON-RPC 2.0 communication layer. Implementations handle stdio (child process) and Streamable HTTP transports.

type MemoryAgentMessageBus

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

MemoryAgentMessageBus is an in-process runtime message bus for local dev/test.

func NewMemoryAgentMessageBus

func NewMemoryAgentMessageBus(subjectPrefix string, historyMax int, dedupeWindow time.Duration) *MemoryAgentMessageBus

func (*MemoryAgentMessageBus) Close

func (b *MemoryAgentMessageBus) Close() error

func (*MemoryAgentMessageBus) Consume

func (*MemoryAgentMessageBus) Publish

type MemoryManager

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

MemoryManager stores short-lived runtime memory for an agent worker.

func NewMemoryManager

func NewMemoryManager() *MemoryManager

func (*MemoryManager) Get

func (m *MemoryManager) Get(key string) (string, bool)

func (*MemoryManager) Put

func (m *MemoryManager) Put(key, value string)

func (*MemoryManager) Snapshot

func (m *MemoryManager) Snapshot() map[string]string

type MemoryProviderConfig

type MemoryProviderConfig struct {
	Type           string
	Provider       string
	EmbeddingModel string
	Endpoint       string
	AuthToken      string
	Options        map[string]string
	Embedder       EmbeddingProvider
}

MemoryProviderConfig holds the fields from a Memory CRD spec that a provider factory needs to construct a backend.

type MemoryProviderFactory

type MemoryProviderFactory func(cfg MemoryProviderConfig) (PersistentMemoryBackend, error)

MemoryProviderFactory creates a PersistentMemoryBackend from CRD config. Implementations should validate their own config and return a descriptive error if required fields are missing.

type MemoryProviderRegistry

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

MemoryProviderRegistry is a global registry of provider factories keyed by provider name (e.g. "pgvector", "qdrant", "weaviate"). Thread-safe.

func DefaultMemoryProviderRegistry

func DefaultMemoryProviderRegistry() *MemoryProviderRegistry

DefaultMemoryProviderRegistry returns the global provider registry. Use this to register custom vector database providers at startup.

func (*MemoryProviderRegistry) Create

Create looks up the factory for the given provider name and calls it. An empty provider name falls back to "in-memory".

func (*MemoryProviderRegistry) Providers

func (r *MemoryProviderRegistry) Providers() []string

Providers returns the sorted list of registered provider names.

func (*MemoryProviderRegistry) Register

func (r *MemoryProviderRegistry) Register(name string, factory MemoryProviderFactory)

Register adds a provider factory under the given name. Names are case-insensitive and trimmed. Registering the same name twice replaces the previous factory.

type MemoryResourceLookup

type MemoryResourceLookup interface {
	Get(ctx context.Context, name string) (resources.Memory, bool, error)
}

MemoryResourceLookup resolves Memory CRDs by name.

type MemorySearchResult

type MemorySearchResult struct {
	Key   string  `json:"key"`
	Value string  `json:"value"`
	Score float64 `json:"score,omitempty"`
}

MemorySearchResult is one entry returned by search or list.

type MemoryStore

type MemoryStore interface {
	Put(key, value string)
	Get(key string) (string, bool)
	Snapshot() map[string]string
}

MemoryStore stores short-lived agent working memory.

type MemoryToolRuntime

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

MemoryToolRuntime wraps a ToolRuntime and intercepts built-in memory tool calls. When a persistent backend is set, it takes priority over the ephemeral shared store.

func NewMemoryToolRuntime

func NewMemoryToolRuntime(delegate ToolRuntime, memory *SharedMemoryStore) *MemoryToolRuntime

func (*MemoryToolRuntime) Call

func (r *MemoryToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*MemoryToolRuntime) WithPersistentBackend

func (r *MemoryToolRuntime) WithPersistentBackend(backend PersistentMemoryBackend) *MemoryToolRuntime

WithPersistentBackend returns a copy that delegates to the persistent backend.

type MeteringEvent

type MeteringEvent struct {
	Timestamp       string            `json:"timestamp"`
	Component       string            `json:"component,omitempty"`
	Type            string            `json:"type"`
	Namespace       string            `json:"namespace,omitempty"`
	Task            string            `json:"task,omitempty"`
	System          string            `json:"system,omitempty"`
	Agent           string            `json:"agent,omitempty"`
	Worker          string            `json:"worker,omitempty"`
	Attempt         int               `json:"attempt,omitempty"`
	MessageID       string            `json:"message_id,omitempty"`
	Status          string            `json:"status,omitempty"`
	TokensUsed      int               `json:"tokens_used,omitempty"`
	TokensEstimated int               `json:"tokens_estimated,omitempty"`
	ToolCalls       int               `json:"tool_calls,omitempty"`
	Metadata        map[string]string `json:"metadata,omitempty"`
}

MeteringEvent captures one normalized usage event for optional billing/usage sinks.

type MeteringSink

type MeteringSink interface {
	RecordMetering(ctx context.Context, event MeteringEvent)
}

MeteringSink receives metering events. Implementations should be non-blocking and resilient.

type MockModelGateway

type MockModelGateway struct{}

MockModelGateway is an in-process placeholder model adapter.

func (*MockModelGateway) Complete

type MockToolClient

type MockToolClient struct{}

MockToolClient is an in-process placeholder for external tool systems.

func (*MockToolClient) Call

func (m *MockToolClient) Call(_ context.Context, tool string, input string) (string, error)

type ModelEndpointLookup

type ModelEndpointLookup interface {
	Get(ctx context.Context, name string) (resources.ModelEndpoint, bool, error)
}

ModelEndpointLookup resolves namespaced ModelEndpoint resources.

type ModelGateway

type ModelGateway interface {
	Complete(ctx context.Context, req ModelRequest) (ModelResponse, error)
}

ModelGateway abstracts model-provider calls for agent execution.

func NewModelGatewayFromConfig

func NewModelGatewayFromConfig(cfg ModelGatewayConfig) (ModelGateway, error)

NewModelGatewayFromConfig returns a provider-backed model gateway.

type ModelGatewayConfig

type ModelGatewayConfig struct {
	Provider     string
	APIKey       string
	BaseURL      string
	DefaultModel string
	Options      map[string]string
	Timeout      time.Duration
	HTTPClient   *http.Client
}

ModelGatewayConfig configures a runtime model gateway provider.

func DefaultModelGatewayConfig

func DefaultModelGatewayConfig() ModelGatewayConfig

DefaultModelGatewayConfig returns conservative defaults that preserve existing behavior.

type ModelGatewayError

type ModelGatewayError struct {
	StatusCode int
	Provider   string
	Message    string
}

ModelGatewayError is returned by model gateways when the upstream provider returns an HTTP error. Callers can inspect StatusCode to distinguish transient failures (5xx, 429) from permanent ones (4xx).

func IsModelGatewayError

func IsModelGatewayError(err error) (gatewayErr *ModelGatewayError, retryable bool)

IsModelGatewayError returns the underlying *ModelGatewayError if err wraps one, along with a flag indicating whether the caller should retry.

func (*ModelGatewayError) Error

func (e *ModelGatewayError) Error() string

type ModelProviderPlugin

type ModelProviderPlugin interface {
	Name() string
	Aliases() []string
	RequiresAPIKey() bool
	BuildGateway(cfg ModelGatewayConfig) (ModelGateway, error)
}

ModelProviderPlugin builds model gateways for a provider family.

type ModelProviderRegistry

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

ModelProviderRegistry stores model provider plugins by name and alias.

func DefaultModelProviderRegistry

func DefaultModelProviderRegistry() *ModelProviderRegistry

func NewModelProviderRegistry

func NewModelProviderRegistry() *ModelProviderRegistry

func (*ModelProviderRegistry) Lookup

func (r *ModelProviderRegistry) Lookup(provider string) (ModelProviderPlugin, bool)

func (*ModelProviderRegistry) Register

func (r *ModelProviderRegistry) Register(plugin ModelProviderPlugin) error

type ModelRequest

type ModelRequest struct {
	Model       string
	ModelRef    string
	Namespace   string
	Agent       string
	Prompt      string
	Step        int
	Tools       []string
	ToolSchemas map[string]ToolSchemaInfo
	Context     map[string]string
	Messages    []ChatMessage
}

ModelRequest defines one model inference request for an agent step.

type ModelResponse

type ModelResponse struct {
	Content   string
	Done      bool
	ToolCalls []ModelToolCall
	Usage     ModelUsage
}

ModelResponse captures model output used by the runtime loop.

type ModelRouter

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

ModelRouter routes model requests to ModelEndpoint-backed gateways by ModelRequest.ModelRef.

func NewModelRouter

func NewModelRouter(cfg ModelRouterConfig) *ModelRouter

func (*ModelRouter) Complete

func (r *ModelRouter) Complete(ctx context.Context, req ModelRequest) (ModelResponse, error)

type ModelRouterConfig

type ModelRouterConfig struct {
	Endpoints       ModelEndpointLookup
	Secrets         SecretResourceLookup
	SecretEnvPrefix string
}

ModelRouterConfig configures model routing via ModelEndpoint resources.

type ModelToolCall

type ModelToolCall struct {
	ID    string
	Name  string
	Input string
}

ModelToolCall is one model-selected tool invocation request.

type ModelUsage

type ModelUsage struct {
	InputTokens  int
	OutputTokens int
	TotalTokens  int
	Source       string
}

ModelUsage captures provider-reported or estimated token usage for one model call.

type NATSJetStreamAgentMessageBus

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

NATSJetStreamAgentMessageBus is a durable runtime message bus backed by JetStream.

func NewNATSJetStreamAgentMessageBus

func NewNATSJetStreamAgentMessageBus(url string, subjectPrefix string, streamName string, logger *log.Logger) (*NATSJetStreamAgentMessageBus, error)

func (*NATSJetStreamAgentMessageBus) Close

func (*NATSJetStreamAgentMessageBus) Consume

func (*NATSJetStreamAgentMessageBus) Publish

type OAuth2TokenCache

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

OAuth2TokenCache caches access tokens obtained via the client_credentials grant. Tokens are keyed by tokenURL+clientID and evicted on expiry or explicit eviction.

func NewOAuth2TokenCache

func NewOAuth2TokenCache(client HTTPDoer) *OAuth2TokenCache

func (*OAuth2TokenCache) Evict

func (c *OAuth2TokenCache) Evict(tokenURL, clientID string)

Evict removes a cached token, forcing a fresh exchange on next GetToken.

func (*OAuth2TokenCache) GetToken

func (c *OAuth2TokenCache) GetToken(ctx context.Context, tokenURL, clientID, clientSecret, scope string) (string, error)

GetToken returns a cached access token if valid, or performs a fresh exchange.

type OllamaModelGateway

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

OllamaModelGateway calls Ollama's /api/chat endpoint.

func NewOllamaModelGateway

func NewOllamaModelGateway(cfg OllamaModelGatewayConfig) (*OllamaModelGateway, error)

func (*OllamaModelGateway) Complete

type OllamaModelGatewayConfig

type OllamaModelGatewayConfig struct {
	BaseURL      string
	DefaultModel string
	Timeout      time.Duration
	HTTPClient   *http.Client
}

OllamaModelGatewayConfig defines Ollama chat settings.

func DefaultOllamaModelGatewayConfig

func DefaultOllamaModelGatewayConfig() OllamaModelGatewayConfig

DefaultOllamaModelGatewayConfig returns Ollama gateway defaults.

type OpenAIEmbeddingProvider

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

OpenAIEmbeddingProvider calls an OpenAI-compatible /embeddings endpoint. Works with OpenAI, Azure OpenAI, Ollama, and any compatible API.

func NewOpenAIEmbeddingProvider

func NewOpenAIEmbeddingProvider(baseURL, apiKey, model string) *OpenAIEmbeddingProvider

func (*OpenAIEmbeddingProvider) Dimensions

func (p *OpenAIEmbeddingProvider) Dimensions() int

func (*OpenAIEmbeddingProvider) Embed

func (p *OpenAIEmbeddingProvider) Embed(ctx context.Context, texts []string) ([][]float32, error)

type OpenAIModelGateway

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

OpenAIModelGateway calls an OpenAI-compatible Chat Completions endpoint.

func NewOpenAIModelGateway

func NewOpenAIModelGateway(cfg OpenAIModelGatewayConfig) (*OpenAIModelGateway, error)

func (*OpenAIModelGateway) Complete

type OpenAIModelGatewayConfig

type OpenAIModelGatewayConfig struct {
	APIKey       string
	BaseURL      string
	DefaultModel string
	Timeout      time.Duration
	HTTPClient   *http.Client
}

OpenAIModelGatewayConfig defines OpenAI-compatible model gateway settings.

func DefaultOpenAIModelGatewayConfig

func DefaultOpenAIModelGatewayConfig() OpenAIModelGatewayConfig

DefaultOpenAIModelGatewayConfig returns OpenAI gateway defaults.

type PersistentMemoryBackend

type PersistentMemoryBackend interface {
	Put(ctx context.Context, key, value string) error
	Get(ctx context.Context, key string) (string, bool, error)
	Search(ctx context.Context, query string, topK int) ([]MemorySearchResult, error)
	List(ctx context.Context, prefix string) ([]MemorySearchResult, error)
	Ping(ctx context.Context) error
}

PersistentMemoryBackend defines the interface for durable memory stores that persist across task runs. Implementations are selected based on the Memory CRD's spec.type and spec.provider fields.

func NewPersistentMemoryBackendFromConfig

func NewPersistentMemoryBackendFromConfig(memType, provider, embeddingModel string) (PersistentMemoryBackend, error)

NewPersistentMemoryBackendFromConfig creates a backend using the global provider registry. This is the primary entry point used by the controller.

type PersistentMemoryBackendRegistry

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

PersistentMemoryBackendRegistry manages named persistent backends keyed by Memory CRD name.

func NewPersistentMemoryBackendRegistry

func NewPersistentMemoryBackendRegistry() *PersistentMemoryBackendRegistry

func (*PersistentMemoryBackendRegistry) Get

func (*PersistentMemoryBackendRegistry) Register

type PgvectorBackend

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

PgvectorBackend implements PersistentMemoryBackend using PostgreSQL with the pgvector extension. Entries are stored with their vector embeddings, enabling cosine-similarity search.

func NewPgvectorBackend

func NewPgvectorBackend(dsn string, embedder EmbeddingProvider, opts PgvectorOptions) (*PgvectorBackend, error)

NewPgvectorBackend connects to the database, detects the embedding dimension (if not overridden), installs the vector extension, and creates the table with an HNSW index.

func (*PgvectorBackend) Get

func (b *PgvectorBackend) Get(ctx context.Context, key string) (string, bool, error)

func (*PgvectorBackend) List

func (b *PgvectorBackend) List(ctx context.Context, prefix string) ([]MemorySearchResult, error)

func (*PgvectorBackend) Ping

func (b *PgvectorBackend) Ping(ctx context.Context) error

func (*PgvectorBackend) Put

func (b *PgvectorBackend) Put(ctx context.Context, key, value string) error

func (*PgvectorBackend) Search

func (b *PgvectorBackend) Search(ctx context.Context, queryText string, topK int) ([]MemorySearchResult, error)

type PgvectorOptions

type PgvectorOptions struct {
	Table     string // table name, default "orloj_memory"
	Dimension int    // vector dimension override; auto-detected when 0
}

PgvectorOptions configures optional behaviour of the pgvector backend.

type ReActExecutionEngine

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

ReActExecutionEngine is the default runtime engine: model call + optional tool actions in bounded steps.

func NewReActExecutionEngine

func NewReActExecutionEngine(
	toolRuntime ToolRuntime,
	modelGateway ModelGateway,
	newMemoryStore func() MemoryStore,
	stepEvery time.Duration,
) *ReActExecutionEngine

func (*ReActExecutionEngine) Execute

type RetryRequestError

type RetryRequestError struct {
	Delay time.Duration
	Err   error
}

RetryRequestError instructs the message bus consumer to requeue after a delay.

func (*RetryRequestError) Error

func (e *RetryRequestError) Error() string

func (*RetryRequestError) Unwrap

func (e *RetryRequestError) Unwrap() error

type SecretResolver

type SecretResolver interface {
	Resolve(ctx context.Context, secretRef string) (string, error)
}

SecretResolver resolves tool auth secret references.

type SecretResourceLookup

type SecretResourceLookup interface {
	Get(ctx context.Context, name string) (resources.Secret, bool, error)
}

type SharedMemoryStore

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

SharedMemoryStore is a thread-safe key-value store shared across agents in a task.

func NewSharedMemoryStore

func NewSharedMemoryStore() *SharedMemoryStore

func (*SharedMemoryStore) Get

func (s *SharedMemoryStore) Get(key string) (string, bool)

func (*SharedMemoryStore) List

func (s *SharedMemoryStore) List(prefix string) []memoryEntry

func (*SharedMemoryStore) Put

func (s *SharedMemoryStore) Put(key, value string)

func (*SharedMemoryStore) Search

func (s *SharedMemoryStore) Search(query string, topK int) []memoryEntry

func (*SharedMemoryStore) Snapshot

func (s *SharedMemoryStore) Snapshot() map[string]string

type StaticToolCapabilityRegistry

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

StaticToolCapabilityRegistry stores tool policies in-memory for runtime checks.

func NewStaticToolCapabilityRegistry

func NewStaticToolCapabilityRegistry(specs map[string]resources.ToolSpec) *StaticToolCapabilityRegistry

func NewToolCapabilityRegistryFromTools

func NewToolCapabilityRegistryFromTools(tools []resources.Tool) *StaticToolCapabilityRegistry

func (*StaticToolCapabilityRegistry) Resolve

type StdioMcpTransport

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

StdioMcpTransport communicates with an MCP server via a child process's stdin/stdout using newline-delimited JSON-RPC 2.0 messages.

func NewStdioMcpTransport

func NewStdioMcpTransport(cfg StdioMcpTransportConfig) *StdioMcpTransport

func (*StdioMcpTransport) CallTool

func (t *StdioMcpTransport) CallTool(ctx context.Context, name string, arguments map[string]any) (*McpToolResult, error)

func (*StdioMcpTransport) Close

func (t *StdioMcpTransport) Close() error

func (*StdioMcpTransport) Initialize

func (t *StdioMcpTransport) Initialize(ctx context.Context) (*McpInitResult, error)

func (*StdioMcpTransport) ListTools

func (t *StdioMcpTransport) ListTools(ctx context.Context) ([]McpToolDefinition, error)

type StdioMcpTransportConfig

type StdioMcpTransportConfig struct {
	Command string
	Args    []string
	Env     []string
}

StdioMcpTransportConfig configures the child process to spawn.

type StoreSecretResolver

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

func NewStoreSecretResolver

func NewStoreSecretResolver(lookup SecretResourceLookup, defaultKey string) *StoreSecretResolver

func (*StoreSecretResolver) Resolve

func (r *StoreSecretResolver) Resolve(ctx context.Context, secretRef string) (string, error)

func (*StoreSecretResolver) WithNamespace

func (r *StoreSecretResolver) WithNamespace(namespace string) SecretResolver

type StreamableHTTPMcpTransport

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

StreamableHTTPMcpTransport communicates with an MCP server over HTTP using the Streamable HTTP transport (JSON-RPC 2.0 over POST).

func (*StreamableHTTPMcpTransport) CallTool

func (t *StreamableHTTPMcpTransport) CallTool(ctx context.Context, name string, arguments map[string]any) (*McpToolResult, error)

func (*StreamableHTTPMcpTransport) Close

func (t *StreamableHTTPMcpTransport) Close() error

func (*StreamableHTTPMcpTransport) Initialize

func (*StreamableHTTPMcpTransport) ListTools

type StreamableHTTPMcpTransportConfig

type StreamableHTTPMcpTransportConfig struct {
	Endpoint     string
	Headers      map[string]string
	Client       HTTPDoer
	AllowPrivate bool // permit connections to private/internal IPs
}

StreamableHTTPMcpTransportConfig configures the HTTP transport.

type TaskExecutor

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

TaskExecutor runs agents on-demand for Task execution.

func NewTaskExecutor

func NewTaskExecutor(logger *log.Logger) *TaskExecutor

func NewTaskExecutorWithRuntime

func NewTaskExecutorWithRuntime(
	logger *log.Logger,
	toolRuntime ToolRuntime,
	modelGateway ModelGateway,
	newMemoryStore func() MemoryStore,
) *TaskExecutor

func (*TaskExecutor) ExecuteAgent

func (e *TaskExecutor) ExecuteAgent(ctx context.Context, agent resources.Agent, input map[string]string) (AgentExecutionResult, error)

func (*TaskExecutor) ExecuteAgentWithRuntime

func (e *TaskExecutor) ExecuteAgentWithRuntime(
	ctx context.Context,
	agent resources.Agent,
	input map[string]string,
	override ToolRuntime,
) (AgentExecutionResult, error)

type TaskStateStore

type TaskStateStore interface {
	Get(ctx context.Context, name string) (resources.Task, bool, error)
	Upsert(ctx context.Context, item resources.Task) (resources.Task, error)
	AppendLog(ctx context.Context, name, message string) error
}

TaskStateStore stores task status updates produced by message consumers.

type ToolApprovalUpserter

type ToolApprovalUpserter interface {
	Upsert(ctx context.Context, item resources.ToolApproval) (resources.ToolApproval, error)
	Get(ctx context.Context, key string) (resources.ToolApproval, bool, error)
}

ToolApprovalUpserter persists ToolApproval resources when a governed tool requires approval.

type ToolCallAuthorizer

type ToolCallAuthorizer interface {
	Authorize(tool string, spec resources.ToolSpec) (*AuthorizeResult, error)
}

func NewAuthorizerWithApprovedToolGrant

func NewAuthorizerWithApprovedToolGrant(inner ToolCallAuthorizer, getter func(key string) (resources.ToolApproval, bool, error), taskKey, messageID string) ToolCallAuthorizer

NewAuthorizerWithApprovedToolGrant wraps inner (typically AgentToolAuthorizer). When inner requires approval, it allows the call if the ToolApproval row for (taskKey, messageID) is Approved and its spec.tool matches the requested tool.

type ToolCapabilityRegistry

type ToolCapabilityRegistry interface {
	Resolve(tool string) (resources.ToolSpec, bool)
}

ToolCapabilityRegistry resolves runtime policy/capability metadata for tools.

type ToolClient

type ToolClient = ToolRuntime

ToolClient is kept as a compatibility alias.

type ToolContractExecutor

type ToolContractExecutor interface {
	Execute(ctx context.Context, req ToolExecutionRequest) (ToolExecutionResponse, error)
}

ToolContractExecutor executes tools against the v1 tool request/response contract.

func NewToolContractExecutor

func NewToolContractExecutor(runtime ToolRuntime) ToolContractExecutor

type ToolError

type ToolError struct {
	Status    string
	Code      string
	Reason    string
	Retryable bool
	Message   string
	Details   map[string]string
	Cause     error
}

ToolError is the canonical runtime tool error envelope. It is serialized into deterministic message text so controllers/UI can parse stable fields.

func AsToolError

func AsToolError(err error) (*ToolError, bool)

func (*ToolError) Error

func (e *ToolError) Error() string

func (*ToolError) Unwrap

func (e *ToolError) Unwrap() error

type ToolExecutionAuth

type ToolExecutionAuth struct {
	Profile   string   `json:"profile,omitempty"`
	SecretRef string   `json:"secret_ref,omitempty"`
	Scopes    []string `json:"scopes,omitempty"`
}

type ToolExecutionFailure

type ToolExecutionFailure struct {
	Code      string            `json:"code,omitempty"`
	Reason    string            `json:"reason,omitempty"`
	Retryable bool              `json:"retryable"`
	Message   string            `json:"message,omitempty"`
	Details   map[string]string `json:"details,omitempty"`
}

type ToolExecutionOutput

type ToolExecutionOutput struct {
	Result string `json:"result,omitempty"`
}

type ToolExecutionRequest

type ToolExecutionRequest struct {
	ToolContractVersion string                    `json:"tool_contract_version,omitempty"`
	RequestID           string                    `json:"request_id,omitempty"`
	TaskID              string                    `json:"task_id,omitempty"`
	Namespace           string                    `json:"namespace,omitempty"`
	Agent               string                    `json:"agent,omitempty"`
	Tool                ToolExecutionRequestTool  `json:"tool,omitempty"`
	Input               map[string]string         `json:"input,omitempty"`
	InputRaw            string                    `json:"input_raw,omitempty"`
	Runtime             ToolExecutionRuntime      `json:"runtime,omitempty"`
	Auth                ToolExecutionAuth         `json:"auth,omitempty"`
	Trace               ToolExecutionTraceContext `json:"trace,omitempty"`
	Attempt             int                       `json:"attempt,omitempty"`
}

ToolExecutionRequest is the strict runtime contract envelope for one tool call.

func NormalizeToolExecutionRequest

func NormalizeToolExecutionRequest(req ToolExecutionRequest) (ToolExecutionRequest, error)

func (ToolExecutionRequest) EncodedInput

func (r ToolExecutionRequest) EncodedInput() (string, error)

type ToolExecutionRequestTool

type ToolExecutionRequestTool struct {
	Name         string   `json:"name,omitempty"`
	Operation    string   `json:"operation,omitempty"`
	Capabilities []string `json:"capabilities,omitempty"`
	RiskLevel    string   `json:"risk_level,omitempty"`
}

type ToolExecutionResponse

type ToolExecutionResponse struct {
	ToolContractVersion string                    `json:"tool_contract_version,omitempty"`
	RequestID           string                    `json:"request_id,omitempty"`
	Status              string                    `json:"status,omitempty"`
	Output              ToolExecutionOutput       `json:"output,omitempty"`
	Usage               ToolExecutionUsage        `json:"usage,omitempty"`
	Trace               ToolExecutionTraceContext `json:"trace,omitempty"`
	Error               *ToolExecutionFailure     `json:"error,omitempty"`
}

func (ToolExecutionResponse) ToError

func (r ToolExecutionResponse) ToError() error

type ToolExecutionRuntime

type ToolExecutionRuntime struct {
	Mode         string `json:"mode,omitempty"`
	TimeoutMS    int    `json:"timeout_ms,omitempty"`
	MaxAttempts  int    `json:"max_attempts,omitempty"`
	Backoff      string `json:"backoff,omitempty"`
	MaxBackoffMS int    `json:"max_backoff_ms,omitempty"`
	Jitter       bool   `json:"jitter,omitempty"`
}

type ToolExecutionTraceContext

type ToolExecutionTraceContext struct {
	TraceID string `json:"trace_id,omitempty"`
	SpanID  string `json:"span_id,omitempty"`
}

type ToolExecutionUsage

type ToolExecutionUsage struct {
	DurationMS int64 `json:"duration_ms,omitempty"`
	Attempt    int   `json:"attempt,omitempty"`
}

type ToolIsolationBackendFactory

type ToolIsolationBackendFactory func(options ToolIsolationBackendOptions) (ToolRuntime, error)

type ToolIsolationBackendOptions

type ToolIsolationBackendOptions struct {
	Mode                string
	ContainerConfig     ContainerToolRuntimeConfig
	SecretResolver      SecretResolver
	WASMConfig          WASMToolRuntimeConfig
	WASMExecutorFactory WASMToolExecutorFactory
	McpSessionManager   *McpSessionManager
	McpServerStore      McpServerLookup
}

type ToolIsolationBackendRegistry

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

ToolIsolationBackendRegistry resolves isolated runtime backends by mode. New backends can be registered without editing core switch logic.

func DefaultToolIsolationBackendRegistry

func DefaultToolIsolationBackendRegistry() *ToolIsolationBackendRegistry

func NewToolIsolationBackendRegistry

func NewToolIsolationBackendRegistry() *ToolIsolationBackendRegistry

func (*ToolIsolationBackendRegistry) Build

func (*ToolIsolationBackendRegistry) Modes

func (r *ToolIsolationBackendRegistry) Modes() []string

func (*ToolIsolationBackendRegistry) Register

type ToolPermissionLookup

type ToolPermissionLookup interface {
	List(ctx context.Context) ([]resources.ToolPermission, error)
}

type ToolResourceLookup

type ToolResourceLookup interface {
	Get(ctx context.Context, name string) (resources.Tool, bool, error)
}

ToolResourceLookup resolves Tool CRDs by name (optionally namespace scoped).

type ToolRuntime

type ToolRuntime interface {
	Call(ctx context.Context, tool string, input string) (string, error)
}

ToolRuntime executes external tool calls for agents.

func BuildGovernedToolRuntimeForAgent

func BuildGovernedToolRuntimeForAgent(
	ctx context.Context,
	baseRuntime ToolRuntime,
	isolatedRuntime ToolRuntime,
	lookup ToolResourceLookup,
	namespace string,
	toolNames []string,
) ToolRuntime

BuildGovernedToolRuntimeForAgent resolves tool policies for one agent in a namespace. Missing registry entries are treated as unsupported at call time when strict mode is enabled.

func BuildGovernedToolRuntimeForAgentWithGovernance

func BuildGovernedToolRuntimeForAgentWithGovernance(
	ctx context.Context,
	baseRuntime ToolRuntime,
	isolatedRuntime ToolRuntime,
	toolLookup ToolResourceLookup,
	roleLookup AgentRoleLookup,
	permissionLookup ToolPermissionLookup,
	namespace string,
	agent resources.Agent,
	approvalCtx *GovernedToolApprovalContext,
) ToolRuntime

func BuildToolIsolationRuntime

func BuildToolIsolationRuntime(options ToolIsolationBackendOptions) (ToolRuntime, error)

func NewUnsupportedWASMToolRuntime

func NewUnsupportedWASMToolRuntime() ToolRuntime

type ToolSchemaInfo

type ToolSchemaInfo struct {
	Description string
	InputSchema map[string]any
}

ToolSchemaInfo carries optional description and JSON Schema for a tool. When present, model gateways use these instead of the generic fallback.

type ToolSchemaResolver

type ToolSchemaResolver interface {
	ResolveToolSchemas(toolNames []string) map[string]ToolSchemaInfo
}

ToolSchemaResolver resolves rich tool schemas for model gateway formatting. Implementations that wrap tool registries (e.g. GovernedToolRuntime) can provide per-tool descriptions and JSON Schemas to the LLM.

type UnsupportedIsolatedToolRuntime

type UnsupportedIsolatedToolRuntime struct{}

UnsupportedIsolatedToolRuntime fails closed when isolation is required but no sandbox executor is wired.

func (*UnsupportedIsolatedToolRuntime) Call

type UnsupportedWASMToolRuntime

type UnsupportedWASMToolRuntime struct{}

UnsupportedWASMToolRuntime is an explicit fail-closed placeholder until a real WASM executor is wired.

func (*UnsupportedWASMToolRuntime) Call

type WASMCommandExecutor

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

func (*WASMCommandExecutor) Execute

type WASMCommandExecutorFactory

type WASMCommandExecutorFactory struct {
	Runner WASMCommandRunner
}

func NewWASMCommandExecutorFactory

func NewWASMCommandExecutorFactory() *WASMCommandExecutorFactory

func (*WASMCommandExecutorFactory) Build

type WASMCommandRunner

type WASMCommandRunner interface {
	Run(ctx context.Context, binary string, args []string, stdin string, env map[string]string) (stdout string, stderr string, err error)
}

WASMCommandRunner executes wasm runtime binary commands.

type WASMToolExecuteRequest

type WASMToolExecuteRequest struct {
	Namespace    string
	Tool         string
	Input        string
	Capabilities []string
	RiskLevel    string
	Runtime      WASMToolRuntimeConfig
}

WASMToolExecuteRequest is the portable execution envelope used by wasm executors.

type WASMToolExecuteResponse

type WASMToolExecuteResponse struct {
	Output string
}

type WASMToolExecutor

type WASMToolExecutor interface {
	Execute(ctx context.Context, req WASMToolExecuteRequest) (WASMToolExecuteResponse, error)
}

WASMToolExecutor is a pluggable wasm execution adapter.

type WASMToolExecutorFactory

type WASMToolExecutorFactory interface {
	Build(ctx context.Context, cfg WASMToolRuntimeConfig) (WASMToolExecutor, error)
}

WASMToolExecutorFactory creates wasm executors from runtime config.

type WASMToolModuleReqAuth

type WASMToolModuleReqAuth struct {
	Profile string            `json:"profile,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
}

type WASMToolModuleReqRuntime

type WASMToolModuleReqRuntime struct {
	Entrypoint     string `json:"entrypoint,omitempty"`
	MaxMemoryBytes int64  `json:"max_memory_bytes,omitempty"`
	Fuel           uint64 `json:"fuel,omitempty"`
	EnableWASI     bool   `json:"enable_wasi"`
}

type WASMToolModuleRequest

type WASMToolModuleRequest struct {
	ContractVersion string                   `json:"contract_version,omitempty"`
	Namespace       string                   `json:"namespace,omitempty"`
	Tool            string                   `json:"tool,omitempty"`
	Input           string                   `json:"input,omitempty"`
	Capabilities    []string                 `json:"capabilities,omitempty"`
	RiskLevel       string                   `json:"risk_level,omitempty"`
	Runtime         WASMToolModuleReqRuntime `json:"runtime,omitempty"`
	Auth            WASMToolModuleReqAuth    `json:"auth,omitempty"`
}

type WASMToolModuleResponse

type WASMToolModuleResponse struct {
	ContractVersion string                `json:"contract_version,omitempty"`
	Status          string                `json:"status,omitempty"`
	Output          string                `json:"output,omitempty"`
	Error           *ToolExecutionFailure `json:"error,omitempty"`
}

func DecodeWASMToolModuleResponse

func DecodeWASMToolModuleResponse(raw string) (WASMToolModuleResponse, error)

type WASMToolRuntime

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

WASMToolRuntime is a scaffold runtime for wasm-backed tool execution.

func NewWASMToolRuntime

func NewWASMToolRuntime(registry ToolCapabilityRegistry, executor WASMToolExecutor) *WASMToolRuntime

func NewWASMToolRuntimeWithFactory

func NewWASMToolRuntimeWithFactory(
	registry ToolCapabilityRegistry,
	factory WASMToolExecutorFactory,
	config WASMToolRuntimeConfig,
) *WASMToolRuntime

func (*WASMToolRuntime) Call

func (r *WASMToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*WASMToolRuntime) WithConfig

func (r *WASMToolRuntime) WithConfig(config WASMToolRuntimeConfig) *WASMToolRuntime

func (*WASMToolRuntime) WithNamespace

func (r *WASMToolRuntime) WithNamespace(namespace string) ToolRuntime

func (*WASMToolRuntime) WithRegistry

func (r *WASMToolRuntime) WithRegistry(registry ToolCapabilityRegistry) ToolRuntime

type WASMToolRuntimeConfig

type WASMToolRuntimeConfig struct {
	ModulePath     string
	Entrypoint     string
	MaxMemoryBytes int64
	Fuel           uint64
	EnableWASI     bool
	RuntimeBinary  string
	RuntimeArgs    []string
}

func DefaultWASMToolRuntimeConfig

func DefaultWASMToolRuntimeConfig() WASMToolRuntimeConfig

type WebhookCallbackToolRuntime

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

WebhookCallbackToolRuntime implements an async tool pattern: fire a ToolExecutionRequest to the tool endpoint, then poll a callback URL (or the same endpoint with the request ID) until a ToolExecutionResponse arrives or the context times out.

Flow:

  1. POST ToolExecutionRequest to Tool.spec.endpoint
  2. Receive 202 Accepted (or 200 with immediate result)
  3. If 202: poll GET {endpoint}/{request_id} until status != "pending"

func NewWebhookCallbackToolRuntime

func NewWebhookCallbackToolRuntime(registry ToolCapabilityRegistry, secrets SecretResolver, client HTTPDoer, pollInterval time.Duration) *WebhookCallbackToolRuntime

func (*WebhookCallbackToolRuntime) Call

func (r *WebhookCallbackToolRuntime) Call(ctx context.Context, tool string, input string) (string, error)

func (*WebhookCallbackToolRuntime) DeliverCallback

func (r *WebhookCallbackToolRuntime) DeliverCallback(requestID string, resp ToolExecutionResponse) bool

DeliverCallback allows external code to push an async response for a pending request.

func (*WebhookCallbackToolRuntime) WithNamespace

func (r *WebhookCallbackToolRuntime) WithNamespace(namespace string) ToolRuntime

func (*WebhookCallbackToolRuntime) WithRegistry

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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