agent

package
v0.0.0-...-137e883 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetCLIArgs

func GetCLIArgs(ctx context.Context) map[string]string

GetCLIArgs returns parsed CLI arguments stored on the context. Keys include user-supplied --set flags plus metadata keys: __command, __output, __color.

func IsCLIMode

func IsCLIMode(ctx context.Context) bool

IsCLIMode returns true if the current execution is in CLI mode.

Types

type Agent

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

Agent manages registration, lease renewal, and HTTP routing.

func New

func New(cfg Config) (*Agent, error)

New constructs an Agent.

func (*Agent) AI

func (a *Agent) AI(ctx context.Context, prompt string, opts ...ai.Option) (*ai.Response, error)

AI makes an AI/LLM call with the given prompt and options. Returns an error if AI is not configured for this agent.

Example usage:

response, err := agent.AI(ctx, "What is the weather?",
    ai.WithSystem("You are a weather assistant"),
    ai.WithTemperature(0.7))

func (*Agent) AIStream

func (a *Agent) AIStream(ctx context.Context, prompt string, opts ...ai.Option) (<-chan ai.StreamChunk, <-chan error)

AIStream makes a streaming AI/LLM call. Returns channels for streaming chunks and errors.

Example usage:

chunks, errs := agent.AIStream(ctx, "Tell me a story")
for chunk := range chunks {
    fmt.Print(chunk.Choices[0].Delta.Content)
}
if err := <-errs; err != nil {
    log.Fatal(err)
}

func (*Agent) AIWithTools

func (a *Agent) AIWithTools(ctx context.Context, prompt string, config ai.ToolCallConfig, discoveryOpts ...DiscoveryOption) (*ai.Response, *ai.ToolCallTrace, error)

AIWithTools makes an AI call with tool-calling support. It discovers available capabilities, converts them to tool schemas, and runs a tool-call loop that dispatches calls via agent.Call().

Example:

resp, trace, err := agent.AIWithTools(ctx, "Help the user with their ticket",
    ai.DefaultToolCallConfig(),
    agent.WithDiscoveryInputSchema(true),
)

func (*Agent) Call

func (a *Agent) Call(ctx context.Context, target string, input map[string]any) (map[string]any, error)

Call invokes another reasoner via the AgentField control plane, preserving execution context.

func (*Agent) CallLocal

func (a *Agent) CallLocal(ctx context.Context, reasonerName string, input map[string]any) (any, error)

CallLocal invokes a registered reasoner directly within this agent process, maintaining execution lineage and emitting workflow events to the control plane. It should be used for same-node composition; use Call for cross-node calls.

func (*Agent) DIDManager

func (a *Agent) DIDManager() *did.Manager

DIDManager returns the agent's DID manager, or nil if DID is not enabled.

func (*Agent) Discover

func (a *Agent) Discover(ctx context.Context, opts ...DiscoveryOption) (*types.DiscoveryResult, error)

Discover queries the control plane discovery API.

func (*Agent) Execute

func (a *Agent) Execute(ctx context.Context, reasonerName string, input map[string]any) (any, error)

Execute runs a specific reasoner by name.

func (*Agent) HandleServerlessEvent

func (a *Agent) HandleServerlessEvent(ctx context.Context, event map[string]any, adapter func(map[string]any) map[string]any) (map[string]any, int, error)

HandleServerlessEvent allows custom serverless entrypoints to normalize arbitrary platform events (Lambda, Vercel, Supabase, etc.) before delegating to the agent. The adapter can rewrite the incoming event into the generic payload that handleExecute expects: keys like path, target/reasoner, input, execution_context.

func (*Agent) Handler

func (a *Agent) Handler() http.Handler

Handler exposes the agent as an http.Handler for serverless or custom hosting scenarios.

func (*Agent) Harness

func (a *Agent) Harness(ctx context.Context, prompt string, schema map[string]any, dest any, opts harness.Options) (*harness.Result, error)

Harness dispatches a prompt to an external coding agent and returns structured results. It is the Go equivalent of Python SDK's .harness().

Parameters:

  • prompt: Task description for the coding agent.
  • schema: JSON Schema as map[string]any (nil for unstructured output).
  • dest: Pointer to struct for schema validation (nil if schema is nil).
  • opts: Per-call option overrides (zero values use runner defaults).

Example:

type ReviewResult struct {
    Findings []string `json:"findings"`
    Severity string   `json:"severity"`
}
var result ReviewResult
schema, _ := harness.StructToJSONSchema(result)
hr, err := agent.Harness(ctx, "Review this code...", schema, &result, harness.Options{
    Model: "sonnet",
})

func (*Agent) HarnessRunner

func (a *Agent) HarnessRunner() *harness.Runner

HarnessRunner returns the agent's lazily-initialized harness runner.

func (*Agent) Initialize

func (a *Agent) Initialize(ctx context.Context) error

Initialize registers the agent with the AgentField control plane without starting a listener.

func (*Agent) Memory

func (a *Agent) Memory() *Memory

Memory returns the agent's memory system for state management. Memory provides hierarchical scoped storage (workflow, session, user, global).

Example usage:

// Store in default (session) scope
agent.Memory().Set(ctx, "key", "value")

// Retrieve from session scope
val, _ := agent.Memory().Get(ctx, "key")

// Use global scope for cross-session data
agent.Memory().GlobalScope().Set(ctx, "shared_key", data)

func (*Agent) Note

func (a *Agent) Note(ctx context.Context, message string, tags ...string)

Note sends a progress/status message to the AgentField server. This is useful for debugging and tracking agent execution progress in the AgentField UI.

Notes are sent asynchronously (fire-and-forget) and will not block the handler or raise errors that interrupt the workflow.

Example usage:

agent.Note(ctx, "Starting data processing", "debug", "processing")
// ... do work ...
agent.Note(ctx, "Processing completed", "info")

func (*Agent) Notef

func (a *Agent) Notef(ctx context.Context, format string, args ...any)

Notef sends a formatted progress/status message to the AgentField server. This is a convenience method that formats the message using fmt.Sprintf.

Example usage:

agent.Notef(ctx, "Processing %d items...", len(items))

func (*Agent) RegisterReasoner

func (a *Agent) RegisterReasoner(name string, handler HandlerFunc, opts ...ReasonerOption)

RegisterReasoner makes a handler available at /reasoners/{name}.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context) error

Run intelligently routes between CLI and server modes.

func (*Agent) Serve

func (a *Agent) Serve(ctx context.Context) error

Serve starts the agent HTTP server, registers with the control plane, and blocks until ctx is cancelled.

func (*Agent) ServeHTTP

func (a *Agent) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler directly.

func (*Agent) VCGenerator

func (a *Agent) VCGenerator() *did.VCGenerator

VCGenerator returns the agent's VC generator, or nil if VC generation is not enabled.

type CLIConfig

type CLIConfig struct {
	AppName        string
	AppDescription string
	DisableColors  bool

	DefaultOutputFormat string
	HelpPreamble        string
	HelpEpilog          string
	EnvironmentVars     []string
}

CLIConfig controls CLI behaviour and presentation.

type CLIError

type CLIError struct {
	Code int
	Err  error
}

CLIError represents an error encountered while handling CLI input. Code follows common CLI semantics: 0 success, 1 runtime error, 2 usage error.

func (*CLIError) Error

func (e *CLIError) Error() string

func (*CLIError) ExitCode

func (e *CLIError) ExitCode() int

func (*CLIError) Unwrap

func (e *CLIError) Unwrap() error

type Config

type Config struct {
	// NodeID is the unique identifier for this agent node. Required.
	// Must be a non-empty identifier suitable for registration (alphanumeric
	// characters, hyphens are recommended). Example: "my-agent-1".
	NodeID string

	// Version identifies the agent implementation version. Required.
	// Typically in semver or short string form (e.g. "v1.2.3" or "1.0.0").
	Version string

	// TeamID groups related agents together for organization. Optional.
	// Default: "default" (if empty, New() sets it to "default").
	TeamID string

	// AgentFieldURL is the base URL of the AgentField control plane server.
	// Optional for local-only or serverless usage, required when registering
	// with a control plane or making cross-node calls. Default: empty.
	// Format: a valid HTTP/HTTPS URL, e.g. "https://agentfield.example.com".
	AgentFieldURL string

	// ListenAddress is the network address the agent HTTP server binds to.
	// Optional. Default: ":8001" (if empty, New() sets it to ":8001").
	// Format: "host:port" or ":port" (e.g. ":8001" or "0.0.0.0:8001").
	ListenAddress string

	// PublicURL is the public-facing base URL reported to the control plane.
	// Optional. Default: "http://localhost" + ListenAddress (if empty,
	// New() constructs a default using ListenAddress).
	// Format: a valid HTTP/HTTPS URL.
	PublicURL string

	// Token is the bearer token used for authenticating to the control plane.
	// Optional. Default: empty (no auth). When set, the token is sent as
	// an Authorization: Bearer <token> header on control-plane requests.
	Token string

	// DeploymentType describes how the agent runs (affects execution behavior).
	// Optional. Default: "long_running". Common values: "long_running",
	// "serverless". Use a descriptive string for custom modes.
	DeploymentType string

	// LeaseRefreshInterval controls how frequently the agent refreshes its
	// lease/heartbeat with the control plane. Optional.
	// Default: 2m (2 minutes). Valid: any positive time.Duration.
	LeaseRefreshInterval time.Duration

	// DisableLeaseLoop disables automatic periodic lease refreshes.
	// Optional. Default: false.
	DisableLeaseLoop bool

	// Logger is used for agent logging output. Optional.
	// Default: a standard logger writing to stdout with the "[agent] " prefix
	// (if nil, New() creates a default logger).
	Logger *log.Logger

	// AIConfig configures LLM/AI capabilities for the agent.
	// Optional. If nil, AI features are disabled. Provide a valid
	// *ai.Config to enable AI-related APIs.
	AIConfig *ai.Config

	// CLIConfig controls CLI-specific behaviour and help text.
	// Optional. If nil, CLI behavior uses sensible defaults.
	CLIConfig *CLIConfig

	// MemoryBackend allows plugging in a custom memory storage backend.
	// Optional. If nil, an in-memory backend is used (data lost on restart).
	MemoryBackend MemoryBackend

	// DID is the agent's decentralized identifier for DID authentication.
	// Optional. If set along with PrivateKeyJWK, enables DID auth on
	// all control plane requests without auto-registration.
	DID string

	// PrivateKeyJWK is the JWK-formatted Ed25519 private key for signing
	// DID-authenticated requests. Optional. Must be set together with DID.
	PrivateKeyJWK string

	// EnableDID enables automatic DID registration during Initialize().
	// The agent registers with the control plane's DID service to obtain
	// a cryptographic identity (Ed25519 keys and DID). DID authentication
	// is then applied to all subsequent control plane requests.
	// If DID and PrivateKeyJWK are already set, registration is skipped.
	// Optional. Default: false.
	EnableDID bool

	// VCEnabled enables Verifiable Credential generation after each execution.
	// Requires DID authentication (either EnableDID or DID/PrivateKeyJWK).
	// When enabled, the agent generates a W3C Verifiable Credential for each
	// reasoner execution and stores it on the control plane for audit trails.
	// Optional. Default: false.
	VCEnabled bool

	// Tags are metadata labels attached to the agent during registration.
	// Used by the control plane for protection rules (e.g., agents tagged
	// "sensitive" require permission for cross-agent calls).
	// Optional. Default: nil.
	Tags []string

	// InternalToken is validated on incoming requests when RequireOriginAuth
	// is true. The control plane sends this token as Authorization: Bearer
	// when forwarding execution requests. If empty, Token is used instead.
	// Optional. Default: "" (falls back to Token).
	InternalToken string

	// RequireOriginAuth when true, validates that incoming execution
	// requests include an Authorization header matching InternalToken
	// (or Token if InternalToken is empty). This ensures only the
	// control plane can invoke reasoners, blocking direct access to the
	// agent's HTTP port. /health and /discover endpoints remain open.
	// Optional. Default: false.
	RequireOriginAuth bool

	// LocalVerification enables decentralized verification of incoming
	// requests using cached policies, revocations, and the admin's public key.
	// When enabled, the agent verifies DID signatures locally without
	// hitting the control plane for every call.
	// Optional. Default: false.
	LocalVerification bool

	// VerificationRefreshInterval controls how often the local verifier
	// refreshes its caches from the control plane.
	// Optional. Default: 5 minutes.
	VerificationRefreshInterval time.Duration

	// HarnessConfig configures the default harness runner for dispatching
	// tasks to external coding agents (opencode, claude-code).
	// Optional. If nil, Harness() calls require per-call provider options.
	HarnessConfig *HarnessConfig
}

Config drives Agent behaviour.

type ConstraintEntry

type ConstraintEntry struct {
	Operator string  `json:"operator"`
	Value    float64 `json:"value"`
}

ConstraintEntry represents a parameter constraint in a policy.

type ControlPlaneMemoryBackend

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

ControlPlaneMemoryBackend implements MemoryBackend by delegating to the Agentfield control plane distributed memory endpoints under `/api/v1/memory/*`.

It preserves the SDK Memory API surface while making storage distributed and scope-aware.

func NewControlPlaneMemoryBackend

func NewControlPlaneMemoryBackend(agentFieldURL, token, agentNodeID string) *ControlPlaneMemoryBackend

NewControlPlaneMemoryBackend creates a distributed memory backend that uses the control plane. agentFieldURL should be the control plane base URL (e.g. http://localhost:8080).

func (*ControlPlaneMemoryBackend) Delete

func (b *ControlPlaneMemoryBackend) Delete(scope MemoryScope, scopeID, key string) error

func (*ControlPlaneMemoryBackend) DeleteVector

func (b *ControlPlaneMemoryBackend) DeleteVector(scope MemoryScope, scopeID, key string) error

func (*ControlPlaneMemoryBackend) Get

func (b *ControlPlaneMemoryBackend) Get(scope MemoryScope, scopeID, key string) (any, bool, error)

func (*ControlPlaneMemoryBackend) GetVector

func (b *ControlPlaneMemoryBackend) GetVector(scope MemoryScope, scopeID, key string) ([]float64, map[string]any, bool, error)

func (*ControlPlaneMemoryBackend) List

func (b *ControlPlaneMemoryBackend) List(scope MemoryScope, scopeID string) ([]string, error)

func (*ControlPlaneMemoryBackend) SearchVector

func (b *ControlPlaneMemoryBackend) SearchVector(scope MemoryScope, scopeID string, embedding []float64, opts SearchOptions) ([]VectorSearchResult, error)

func (*ControlPlaneMemoryBackend) Set

func (b *ControlPlaneMemoryBackend) Set(scope MemoryScope, scopeID, key string, value any) error

func (*ControlPlaneMemoryBackend) SetVector

func (b *ControlPlaneMemoryBackend) SetVector(scope MemoryScope, scopeID, key string, embedding []float64, metadata map[string]any) error

type DiscoveryOption

type DiscoveryOption func(*discoveryOptions)

DiscoveryOption configures discovery requests.

func WithAgent

func WithAgent(id string) DiscoveryOption

WithAgent filters discovery to a single agent ID.

func WithAgentIDs

func WithAgentIDs(ids []string) DiscoveryOption

WithAgentIDs filters discovery to a set of agent IDs.

func WithDiscoveryDescriptions

func WithDiscoveryDescriptions(enabled bool) DiscoveryOption

WithDiscoveryDescriptions toggles inclusion of descriptions.

func WithDiscoveryExamples

func WithDiscoveryExamples(enabled bool) DiscoveryOption

WithDiscoveryExamples toggles inclusion of examples.

func WithDiscoveryInputSchema

func WithDiscoveryInputSchema(enabled bool) DiscoveryOption

WithDiscoveryInputSchema toggles inclusion of input schemas.

func WithDiscoveryOutputSchema

func WithDiscoveryOutputSchema(enabled bool) DiscoveryOption

WithDiscoveryOutputSchema toggles inclusion of output schemas.

func WithFormat

func WithFormat(format string) DiscoveryOption

WithFormat sets the desired response format: json (default), xml, or compact.

func WithHealthStatus

func WithHealthStatus(status string) DiscoveryOption

WithHealthStatus filters by health status.

func WithLimit

func WithLimit(limit int) DiscoveryOption

WithLimit controls pagination limit.

func WithNodeID

func WithNodeID(id string) DiscoveryOption

WithNodeID aliases WithAgent for clarity.

func WithNodeIDs

func WithNodeIDs(ids []string) DiscoveryOption

WithNodeIDs aliases WithAgentIDs.

func WithOffset

func WithOffset(offset int) DiscoveryOption

WithOffset controls pagination offset.

func WithReasonerPattern

func WithReasonerPattern(pattern string) DiscoveryOption

WithReasonerPattern applies a wildcard pattern to reasoner IDs.

func WithSkillPattern

func WithSkillPattern(pattern string) DiscoveryOption

WithSkillPattern applies a wildcard pattern to skill IDs.

func WithTags

func WithTags(tags []string) DiscoveryOption

WithTags filters capabilities by tag (supports wildcards).

type ExecuteError

type ExecuteError struct {
	StatusCode   int
	Message      string
	ErrorDetails interface{}
}

ExecuteError is a structured error from agent-to-agent calls via the control plane. It preserves the HTTP status code and any structured error details (e.g., permission_denied response fields) so callers can inspect them.

func (*ExecuteError) Error

func (e *ExecuteError) Error() string

type ExecutionContext

type ExecutionContext struct {
	RunID             string
	ExecutionID       string
	ParentExecutionID string
	SessionID         string
	ActorID           string
	WorkflowID        string
	ParentWorkflowID  string
	RootWorkflowID    string
	Depth             int
	AgentNodeID       string
	ReasonerName      string
	StartedAt         time.Time

	// DID fields — populated when DID authentication is enabled.
	CallerDID    string
	TargetDID    string
	AgentNodeDID string
}

ExecutionContext captures the headers AgentField sends with each execution request.

func ExecutionContextFrom

func ExecutionContextFrom(ctx context.Context) ExecutionContext

ExecutionContextFrom returns the execution context embedded in the provided context, if any.

func (ExecutionContext) ChildContext

func (ec ExecutionContext) ChildContext(agentNodeID, reasonerName string) ExecutionContext

ChildContext creates a new execution context for a nested local call.

type HandlerFunc

type HandlerFunc func(ctx context.Context, input map[string]any) (any, error)

HandlerFunc processes a reasoner invocation.

type HarnessConfig

type HarnessConfig struct {
	// Provider is the default provider: "claude-code", "codex", "gemini", or "opencode".
	Provider string

	// Model is the default model identifier.
	Model string

	// MaxTurns is the default max agent iterations.
	MaxTurns int

	// PermissionMode is the default permission mode ("auto", "plan").
	PermissionMode string

	// Env is additional environment variables for the subprocess.
	Env map[string]string

	// BinPath overrides the provider binary path.
	BinPath string

	// Timeout in seconds for the subprocess. Default 600.
	Timeout int

	// MaxRetries for transient errors. Default 3.
	MaxRetries int

	// SchemaMaxRetries for schema validation failures. Default 2.
	SchemaMaxRetries int
}

harness.go integrates the harness package with the Agent struct, providing lazy initialization and a convenience Harness() method. HarnessConfig configures the default harness runner for the agent.

type InMemoryBackend

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

InMemoryBackend provides a thread-safe in-memory implementation of MemoryBackend. Data is lost when the process exits.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

NewInMemoryBackend creates a new in-memory storage backend.

func (*InMemoryBackend) Clear

func (b *InMemoryBackend) Clear()

Clear removes all data from the backend. Useful for testing.

func (*InMemoryBackend) ClearScope

func (b *InMemoryBackend) ClearScope(scope MemoryScope, scopeID string)

ClearScope removes all data for a specific scope and scopeID.

func (*InMemoryBackend) Delete

func (b *InMemoryBackend) Delete(scope MemoryScope, scopeID, key string) error

Delete removes a key.

func (*InMemoryBackend) DeleteVector

func (b *InMemoryBackend) DeleteVector(scope MemoryScope, scopeID, key string) error

DeleteVector removes a vector.

func (*InMemoryBackend) Get

func (b *InMemoryBackend) Get(scope MemoryScope, scopeID, key string) (any, bool, error)

Get retrieves a value.

func (*InMemoryBackend) GetVector

func (b *InMemoryBackend) GetVector(scope MemoryScope, scopeID, key string) ([]float64, map[string]any, bool, error)

GetVector retrieves a vector.

func (*InMemoryBackend) List

func (b *InMemoryBackend) List(scope MemoryScope, scopeID string) ([]string, error)

List returns all keys in a scope.

func (*InMemoryBackend) SearchVector

func (b *InMemoryBackend) SearchVector(scope MemoryScope, scopeID string, embedding []float64, opts SearchOptions) ([]VectorSearchResult, error)

SearchVector performs similarity search (stubbed - returns empty list for in-memory).

func (*InMemoryBackend) Set

func (b *InMemoryBackend) Set(scope MemoryScope, scopeID, key string, value any) error

Set stores a value.

func (*InMemoryBackend) SetVector

func (b *InMemoryBackend) SetVector(scope MemoryScope, scopeID, key string, embedding []float64, metadata map[string]any) error

SetVector stores a vector.

type LocalVerifier

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

LocalVerifier verifies incoming requests locally using cached policies, revocation lists, registered DIDs, and the admin's Ed25519 public key. Periodically refreshes caches from the control plane.

func NewLocalVerifier

func NewLocalVerifier(agentFieldURL string, refreshInterval time.Duration, apiKey string) *LocalVerifier

NewLocalVerifier creates a new local verifier.

func (*LocalVerifier) CheckRegistration

func (v *LocalVerifier) CheckRegistration(callerDID string) bool

CheckRegistration returns true if the caller DID is registered with the control plane. When the cache is empty (not yet loaded), returns true to avoid blocking requests before the first refresh completes.

func (*LocalVerifier) CheckRevocation

func (v *LocalVerifier) CheckRevocation(callerDID string) bool

CheckRevocation returns true if the DID is revoked.

func (*LocalVerifier) EvaluatePolicy

func (v *LocalVerifier) EvaluatePolicy(callerTags, targetTags []string, functionName string, inputParams map[string]any) bool

EvaluatePolicy evaluates access policies locally.

func (*LocalVerifier) NeedsRefresh

func (v *LocalVerifier) NeedsRefresh() bool

NeedsRefresh returns true if the cache is stale.

func (*LocalVerifier) Refresh

func (v *LocalVerifier) Refresh() error

Refresh fetches policies, revocations, registered DIDs, and admin public key from the control plane.

func (*LocalVerifier) VerifySignature

func (v *LocalVerifier) VerifySignature(callerDID, signatureB64, timestamp string, body []byte, nonce string) bool

VerifySignature verifies an Ed25519 DID signature on an incoming request. Resolves the caller's public key from their DID (did:key embeds the key directly; other methods fall back to the admin public key).

type Memory

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

Memory provides hierarchical state management for agent handlers. It supports multiple isolation scopes (workflow, session, user, global) with automatic scope ID resolution from execution context.

func NewMemory

func NewMemory(backend MemoryBackend) *Memory

NewMemory creates a Memory instance with the given backend. If backend is nil, an in-memory backend is used.

func (*Memory) Delete

func (m *Memory) Delete(ctx context.Context, key string) error

Delete removes a key from the session scope.

func (*Memory) DeleteVector

func (m *Memory) DeleteVector(ctx context.Context, key string) error

DeleteVector removes a vector from the session scope (default scope).

func (*Memory) Get

func (m *Memory) Get(ctx context.Context, key string) (any, error)

Get retrieves a value from the session scope (default scope). Returns nil if the key does not exist.

func (*Memory) GetVector

func (m *Memory) GetVector(ctx context.Context, key string) (embedding []float64, metadata map[string]any, err error)

GetVector retrieves a vector from the session scope (default scope).

func (*Memory) GetWithDefault

func (m *Memory) GetWithDefault(ctx context.Context, key string, defaultVal any) (any, error)

GetWithDefault retrieves a value from the session scope, returning the default if the key does not exist.

func (*Memory) GlobalScope

func (m *Memory) GlobalScope() *ScopedMemory

GlobalScope returns a ScopedMemory for global storage. Data is shared across all sessions, users, and workflows.

func (*Memory) List

func (m *Memory) List(ctx context.Context) ([]string, error)

List returns all keys in the session scope.

func (*Memory) Scoped

func (m *Memory) Scoped(scope MemoryScope, scopeID string) *ScopedMemory

Scoped returns a ScopedMemory for a specific scope and ID.

func (*Memory) SearchVector

func (m *Memory) SearchVector(ctx context.Context, embedding []float64, opts SearchOptions) ([]VectorSearchResult, error)

SearchVector performs a similarity search across session scope (default).

func (*Memory) SessionScope

func (m *Memory) SessionScope() *ScopedMemory

SessionScope returns a ScopedMemory for session-level storage. Data persists across workflow executions within the same session.

func (*Memory) Set

func (m *Memory) Set(ctx context.Context, key string, value any) error

Set stores a value in the session scope (default scope).

func (*Memory) SetVector

func (m *Memory) SetVector(ctx context.Context, key string, embedding []float64, metadata map[string]any) error

SetVector stores a vector in the session scope (default scope).

func (*Memory) UserScope

func (m *Memory) UserScope() *ScopedMemory

UserScope returns a ScopedMemory for user/actor-level storage. Data persists across sessions for the same user.

func (*Memory) WorkflowScope

func (m *Memory) WorkflowScope() *ScopedMemory

WorkflowScope returns a ScopedMemory for workflow-level storage. Data is isolated to the current workflow execution.

type MemoryBackend

type MemoryBackend interface {
	// Set stores a value at the given scope and key.
	Set(scope MemoryScope, scopeID, key string, value any) error
	// Get retrieves a value; returns (value, found, error).
	Get(scope MemoryScope, scopeID, key string) (any, bool, error)
	// Delete removes a key from storage.
	Delete(scope MemoryScope, scopeID, key string) error
	// List returns all keys in a scope.
	List(scope MemoryScope, scopeID string) ([]string, error)

	// SetVector stores a vector embedding with optional metadata.
	SetVector(scope MemoryScope, scopeID, key string, embedding []float64, metadata map[string]any) error
	// GetVector retrieves a vector and its metadata.
	GetVector(scope MemoryScope, scopeID, key string) (embedding []float64, metadata map[string]any, found bool, err error)
	// SearchVector performs a similarity search.
	SearchVector(scope MemoryScope, scopeID string, embedding []float64, opts SearchOptions) ([]VectorSearchResult, error)
	// DeleteVector removes a vector from storage.
	DeleteVector(scope MemoryScope, scopeID, key string) error
}

MemoryBackend is the pluggable storage interface for memory operations. Implementations can use in-memory storage, Redis, databases, or external APIs.

type MemoryScope

type MemoryScope string

MemoryScope represents different memory isolation levels.

const (
	// ScopeWorkflow isolates memory to the current workflow execution.
	ScopeWorkflow MemoryScope = "workflow"
	// ScopeSession isolates memory to the current session.
	ScopeSession MemoryScope = "session"
	// ScopeUser isolates memory to the current user/actor.
	ScopeUser MemoryScope = "user"
	// ScopeGlobal provides cross-session, cross-workflow storage.
	ScopeGlobal MemoryScope = "global"
)

type PolicyEntry

type PolicyEntry struct {
	Name           string                     `json:"name"`
	CallerTags     []string                   `json:"caller_tags"`
	TargetTags     []string                   `json:"target_tags"`
	AllowFunctions []string                   `json:"allow_functions"`
	DenyFunctions  []string                   `json:"deny_functions"`
	Constraints    map[string]ConstraintEntry `json:"constraints"`
	Action         string                     `json:"action"`
	Priority       int                        `json:"priority"`
	Enabled        *bool                      `json:"enabled"`
}

PolicyEntry represents a cached access policy for local evaluation.

type Reasoner

type Reasoner struct {
	Name         string
	Handler      HandlerFunc
	InputSchema  json.RawMessage
	OutputSchema json.RawMessage
	Tags         []string

	CLIEnabled   bool
	DefaultCLI   bool
	CLIFormatter func(context.Context, any, error)
	Description  string

	// VCEnabled overrides the agent-level VCEnabled setting for this reasoner.
	// nil = inherit agent setting, true/false = override.
	VCEnabled *bool

	// RequireRealtimeValidation forces control-plane verification for this
	// reasoner, skipping local verification even when enabled.
	RequireRealtimeValidation bool
}

Reasoner represents a single handler exposed by the agent.

type ReasonerOption

type ReasonerOption func(*Reasoner)

ReasonerOption applies metadata to a reasoner registration.

func WithCLI

func WithCLI() ReasonerOption

WithCLI marks this reasoner as CLI-accessible.

func WithCLIFormatter

func WithCLIFormatter(formatter func(context.Context, any, error)) ReasonerOption

WithCLIFormatter registers a custom formatter for CLI output.

func WithDefaultCLI

func WithDefaultCLI() ReasonerOption

WithDefaultCLI marks the reasoner as the default CLI handler.

func WithDescription

func WithDescription(desc string) ReasonerOption

WithDescription adds a human-readable description for help/list commands.

func WithInputSchema

func WithInputSchema(raw json.RawMessage) ReasonerOption

WithInputSchema overrides the auto-generated input schema.

func WithOutputSchema

func WithOutputSchema(raw json.RawMessage) ReasonerOption

WithOutputSchema overrides the default output schema.

func WithReasonerTags

func WithReasonerTags(tags ...string) ReasonerOption

WithReasonerTags sets tags for this reasoner (used for tag-based authorization).

func WithRequireRealtimeValidation

func WithRequireRealtimeValidation() ReasonerOption

WithRequireRealtimeValidation forces control-plane verification for this reasoner instead of local verification, even when LocalVerification is enabled.

func WithVCEnabled

func WithVCEnabled(enabled bool) ReasonerOption

WithVCEnabled overrides VC generation for this specific reasoner.

type ScopedMemory

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

ScopedMemory provides memory operations within a specific scope.

func (*ScopedMemory) Delete

func (s *ScopedMemory) Delete(ctx context.Context, key string) error

Delete removes a key from this scope.

func (*ScopedMemory) DeleteVector

func (s *ScopedMemory) DeleteVector(ctx context.Context, key string) error

DeleteVector removes a vector from this scope.

func (*ScopedMemory) Get

func (s *ScopedMemory) Get(ctx context.Context, key string) (any, error)

Get retrieves a value from this scope. Returns nil if the key does not exist.

func (*ScopedMemory) GetTyped

func (s *ScopedMemory) GetTyped(ctx context.Context, key string, dest any) error

GetTyped retrieves a value and unmarshals it into the provided type. This is useful when storing complex objects as JSON.

func (*ScopedMemory) GetVector

func (s *ScopedMemory) GetVector(ctx context.Context, key string) (embedding []float64, metadata map[string]any, err error)

GetVector retrieves a vector from this scope.

func (*ScopedMemory) GetWithDefault

func (s *ScopedMemory) GetWithDefault(ctx context.Context, key string, defaultVal any) (any, error)

GetWithDefault retrieves a value from this scope, returning the default if the key does not exist.

func (*ScopedMemory) List

func (s *ScopedMemory) List(ctx context.Context) ([]string, error)

List returns all keys in this scope.

func (*ScopedMemory) SearchVector

func (s *ScopedMemory) SearchVector(ctx context.Context, embedding []float64, opts SearchOptions) ([]VectorSearchResult, error)

SearchVector performs a similarity search in this scope.

func (*ScopedMemory) Set

func (s *ScopedMemory) Set(ctx context.Context, key string, value any) error

Set stores a value in this scope.

func (*ScopedMemory) SetVector

func (s *ScopedMemory) SetVector(ctx context.Context, key string, embedding []float64, metadata map[string]any) error

SetVector stores a vector in this scope.

type SearchOptions

type SearchOptions struct {
	Limit     int            `json:"limit"`
	Threshold float64        `json:"threshold"`
	Filters   map[string]any `json:"filters"`
	Scope     MemoryScope    `json:"scope"`
}

SearchOptions defines parameters for similarity search.

type VectorSearchResult

type VectorSearchResult struct {
	Key      string         `json:"key"`
	Score    float64        `json:"score"`
	Metadata map[string]any `json:"metadata"`
	Scope    MemoryScope    `json:"scope"`
	ScopeID  string         `json:"scope_id"`
}

VectorSearchResult represents a single result from a similarity search.

Jump to

Keyboard shortcuts

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