Documentation
¶
Overview ¶
Package agentflow provides a small public facade for embedding the scenario-driven agent runtime in other Go projects.
Applications that need low-level extension points can import pkg/core, pkg/llm, pkg/memory, and pkg/runstate directly. Applications that only need to load a YAML scenario and run it should use this package.
Root package layout:
- core runtime: framework.go and the framework_*.go family (run, resume, checkpoints, streaming, workflow/hybrid orchestration, async job handler, event emit helpers)
- lifecycle and options: lifecycle.go, builder.go, security.go
- wiring validation: wiring.go (ValidateWiring and the New-time wiring checks; scenario knowledge/MCP wiring constructors live in pkg/httpx because they return []agentflow.Option)
- retention: retention.go (purge policies, orphan blob GC)
- run lease: lease.go
- metadata: meta.go (version, JSON schema, JSON helpers)
Convenience constructors that used to live here moved in v0.3:
- pkg/adapters: concrete adapter constructors (run-state/blob/memory stores, job queues, LLM providers, catalog manifests, knowledge, MCP, tool executors, tiered memory, observability sinks/stores). It never imports this root package.
- pkg/httpx: HTTP adapter constructors (checkpoint, retention, studio, webhook/human-gate, async jobs, production composition, observability dashboard) and the knowledge/MCP wiring options.
- pkg/testutil: the mock LLM gateway and test wiring helpers.
Index ¶
- Constants
- Variables
- func NewAPIKeyMiddleware(config APIKeyMiddlewareConfig) (func(http.Handler) http.Handler, error)
- func NewAuthorizationMiddleware(config AuthorizationMiddlewareConfig) (func(http.Handler) http.Handler, error)
- func NewFrameworkJobHandler(config FrameworkRunJobHandlerConfig) (async.Handler, error)
- func NewInMemoryLocker() coordination.Locker
- func NewJWTAuthenticator(config JWTAuthenticatorConfig) (security.BearerAuthenticator, error)
- func NewJWTMiddleware(config JWTMiddlewareConfig) (func(http.Handler) http.Handler, error)
- func NewOIDCJWTAuthenticator(config OIDCJWTAuthenticatorConfig) (security.BearerAuthenticator, error)
- func NewStaticAPIKeyAuthenticator(keys map[string]identity.Principal) (security.APIKeyAuthenticator, error)
- func ScenarioJSONSchema() []byte
- func StreamDetached(ctx context.Context) context.Context
- func ValidateScenario(scenario core.Scenario) error
- func ValidateWiring(scenario core.Scenario, opts ...Option) error
- func ValidateWiringWithOptions(scenario core.Scenario, wiring WiringOptions, opts ...Option) error
- type APIKeyMiddlewareConfig
- type AuthorizationMiddlewareConfig
- type CodegenResult
- type ComposeGraphRequest
- type ComposeGraphResult
- type ComposeMode
- type EventFilterPreset
- type EventRouter
- type ForkRunResult
- type Framework
- func (f *Framework) BlobStore() runstate.BlobStore
- func (f *Framework) Catalog() catalog.Catalog
- func (f *Framework) Close(ctx context.Context) error
- func (f *Framework) CompareRuns(ctx context.Context, runA, runB string) (studio.RunCompareResult, error)
- func (f *Framework) ComposeGraph(ctx context.Context, req ComposeGraphRequest) (ComposeGraphResult, error)
- func (f *Framework) ContinueRun(ctx context.Context, runID string) (*RunResult, error)
- func (f *Framework) ExportScenarioGraph() ScenarioGraph
- func (f *Framework) ForkRun(ctx context.Context, parentRunID string, version int64) (ForkRunResult, error)
- func (f *Framework) GenerateStudioBuilderCode(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
- func (f *Framework) GenerateStudioBuilderCodeWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
- func (f *Framework) GenerateStudioScenarioYAML(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
- func (f *Framework) GenerateStudioScenarioYAMLWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
- func (f *Framework) GetRunCheckpoint(ctx context.Context, runID string, version int64) (runstate.RunSnapshot, error)
- func (f *Framework) HandleEvent(ctx context.Context, event IncomingEvent) (RunResult, error)
- func (f *Framework) ImportStudioScenarioYAML(ctx context.Context, yamlData []byte, layout graph.ScenarioGraph) (ImportStudioResult, error)
- func (f *Framework) Interject(runID, text string) error
- func (f *Framework) ListRunCheckpoints(ctx context.Context, runID string, limit int) (ListRunCheckpointsResult, error)
- func (f *Framework) ListRunSteps(ctx context.Context, runID string) (ListRunStepsResult, error)
- func (f *Framework) ListRunThread(ctx context.Context, runID string) ([]ThreadRunSummary, error)
- func (f *Framework) MarkAbandonedRuns(ctx context.Context) ([]string, error)
- func (f *Framework) PurgeExpired(ctx context.Context, maxAge time.Duration) (int, error)
- func (f *Framework) PurgeOrphanBlobs(ctx context.Context) (int, error)
- func (f *Framework) PurgeRuns(ctx context.Context, filter runstate.ListFilter, opts ...PurgeRunsOption) (int, error)
- func (f *Framework) PurgeWithPolicy(ctx context.Context, policy RetentionPolicy) (int, error)
- func (f *Framework) ResolveEvent(event IncomingEvent) (RunRequest, error)
- func (f *Framework) Resume(ctx context.Context, token string, decision core.Decision, ...) error
- func (f *Framework) ResumeAndContinue(ctx context.Context, token string, decision core.Decision, ...) (RunResult, error)
- func (f *Framework) ResumeFromCheckpoint(ctx context.Context, runID string, version int64) (RunResult, error)
- func (f *Framework) ResumeFromStep(ctx context.Context, runID, nodeID string) (RunResult, error)
- func (f *Framework) ResumeRunByID(ctx context.Context, runID string, decision core.Decision, ...) (RunResult, error)
- func (f *Framework) RetryFailedRun(ctx context.Context, runID string) (RunResult, error)
- func (f *Framework) Run(ctx context.Context, req RunRequest) (RunResult, error)
- func (f *Framework) RunStateRepository() runstate.Repository
- func (f *Framework) RunStructured(ctx context.Context, req RunRequest) (RunResult, error)
- func (f *Framework) RunStudioGraph(ctx context.Context, edited graph.ScenarioGraph, req RunRequest) (RunResult, error)
- func (f *Framework) RunStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, ...) (RunResult, error)
- func (f *Framework) SaveStudioGraph(ctx context.Context, edited graph.ScenarioGraph, path string) (SaveStudioResult, error)
- func (f *Framework) SaveStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, ...) (SaveStudioResult, error)
- func (f *Framework) Scenario() core.Scenario
- func (f *Framework) Stream(ctx context.Context, req RunRequest) (<-chan llm.ChatChunk, error)
- func (f *Framework) StreamRun(ctx context.Context, req RunRequest, opts ...StreamRunOption) (<-chan StreamFrame, error)
- func (f *Framework) Studio() Studio
- func (f *Framework) StudioParts() StudioParts
- func (f *Framework) ValidateStudioGraph(ctx context.Context, edited graph.ScenarioGraph) (ValidateStudioResult, error)
- func (f *Framework) ValidateStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (ValidateStudioResult, error)
- type FrameworkRunJobHandlerConfig
- type GraphEdge
- type GraphNode
- type GraphView
- type ImportStudioResult
- type IncomingEvent
- type JWTAlgorithm
- type JWTAuthenticatorConfig
- type JWTKey
- type JWTMiddlewareConfig
- type ListRunCheckpointsResult
- type ListRunStepsResult
- type MapBranch
- type OIDCJWTAuthenticatorConfig
- type Option
- func WithApprovalStore(store toolorch.ApprovalStore) Option
- func WithAuditSink(sink audit.Sink) Option
- func WithBlobStore(store runstate.BlobStore) Option
- func WithCheckpointHistory(history runstate.CheckpointHistory) Option
- func WithCloser(fn func(context.Context) error) Option
- func WithCognitiveMemory(name string, repo memory.CognitiveMemory) Option
- func WithDatabase(db *sql.DB) Option
- func WithDeferredTools(enabled bool) Option
- func WithEventSink(sink core.EventSink) Option
- func WithEventStore(store observability.EventStore) Option
- func WithHITLTokenRotation(primary, secondary []byte, tokenWriter io.Writer) Option
- func WithHITLTokenSecret(secret []byte, tokenWriter io.Writer) Option
- func WithHITLTokenTTL(ttl time.Duration) Option
- func WithHumanGate(gate core.HumanGate) Option
- func WithInterjectDrainPolicy(policy interjection.DrainPolicy) Option
- func WithJobQueue(queue async.Queue) Option
- func WithLLMGateway(gateway llm.Gateway) Option
- func WithLLMPayloadCapture(capture bool) Option
- func WithLogger(logger log.Logger) Option
- func WithMemoryRepository(name string, repo memory.Repository) Option
- func WithOutboxRelay(interval time.Duration) Option
- func WithOutputRedactor(redactor governance.OutputRedactor) Option
- func WithRecorder(recorder observability.Recorder) Option
- func WithRequireLLM() Option
- func WithResumeAuthorizationHook(hook ResumeAuthorizationHook) Option
- func WithRunLease(locker coordination.Locker, owner string, ttl time.Duration) Option
- func WithRunReaper(interval, gracePeriod time.Duration) Option
- func WithRunStateRepository(repo runstate.Repository) Option
- func WithSecurityPolicy(policy security.Policy) Option
- func WithTierColdSummarizer(name string, summarizer tier.ContentSummarizer) Option
- func WithTierColdSummaryIndexer(name string, indexer tier.ColdSummaryIndexer) Option
- func WithTierMemory(name string, manager tier.Manager) Option
- func WithTierStore(name string, store tier.Store, policy tier.Policy) Option
- func WithToolApprovalEvaluator(evaluator core.ToolApprovalEvaluator) Option
- func WithToolCatalog(catalog toolcatalog.Catalog) Option
- func WithToolExecutor(name string, executor core.ToolExecutor) Option
- func WithToolGovernancePolicy(policy governance.ToolPolicy) Option
- func WithToolOrchestrator(orch toolorch.ToolOrchestrator) Option
- func WithToolOutputTransform(tool string, fn contextwindow.ToolOutputTransform) Option
- func WithToolResolver(resolver core.ToolResolver) Option
- func WithToolResolverCacheLimit(limit int) Option
- func WithTracer(tracer observability.Tracer) Option
- func WithTurnStopHook(hook core.TurnStopHook) Option
- type PendingHITLInfo
- type Plan
- type PurgeRunsOption
- type RedisLocker
- type RedisLockerConfig
- type ResumeAuthorizationHook
- type RetentionPolicy
- type RunRequest
- type RunResult
- type RunStep
- type SaveStudioResult
- type ScenarioBuilder
- type ScenarioGraph
- type StreamFrame
- type StreamFrameKind
- type StreamRunOption
- type Studio
- func (s Studio) CompareRuns(ctx context.Context, runA, runB string) (studio.RunCompareResult, error)
- func (s Studio) ComposeGraph(ctx context.Context, req ComposeGraphRequest) (ComposeGraphResult, error)
- func (s Studio) ForkRun(ctx context.Context, parentRunID string, version int64) (ForkRunResult, error)
- func (s Studio) GenerateStudioBuilderCode(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
- func (s Studio) GenerateStudioBuilderCodeWithScenario(_ context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
- func (s Studio) GenerateStudioScenarioYAML(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
- func (s Studio) GenerateStudioScenarioYAMLWithScenario(_ context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
- func (s Studio) ImportStudioScenarioYAML(_ context.Context, yamlData []byte, layout graph.ScenarioGraph) (ImportStudioResult, error)
- func (s Studio) ListRunThread(ctx context.Context, runID string) ([]ThreadRunSummary, error)
- func (s Studio) Parts() StudioParts
- func (s Studio) RunStudioGraph(ctx context.Context, edited graph.ScenarioGraph, req RunRequest) (RunResult, error)
- func (s Studio) RunStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, ...) (RunResult, error)
- func (s Studio) SaveStudioGraph(ctx context.Context, edited graph.ScenarioGraph, path string) (SaveStudioResult, error)
- func (s Studio) SaveStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, ...) (SaveStudioResult, error)
- func (s Studio) ValidateStudioGraph(ctx context.Context, edited graph.ScenarioGraph) (ValidateStudioResult, error)
- func (s Studio) ValidateStudioGraphWithScenario(_ context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (ValidateStudioResult, error)
- type StudioPart
- type StudioParts
- type ThreadRunSummary
- type TrustMode
- type ValidateStudioResult
- type WiringOptions
- type WorkflowBuilder
Examples ¶
Constants ¶
const ( TrustModeDefault = appexec.TrustModeDefault TrustModeFullTrust = appexec.TrustModeFullTrust )
const ( EventFilterProductUI = core.EventFilterProductUI EventFilterDiagnostic = core.EventFilterDiagnostic )
Event filter presets for StreamRun / EventStore.ListEvents read-side views.
const SchemaVersion = "2020-12"
SchemaVersion is the JSON Schema draft used by ScenarioJSONSchema.
const Version = "0.5.0"
Version is the library release version exposed to embedders.
Variables ¶
var ( ErrRunAlreadyCompleted = appexec.ErrRunAlreadyCompleted ErrRunInProgress = appexec.ErrRunInProgress ErrRunPaused = appexec.ErrRunPaused ErrRunFailed = appexec.ErrRunFailed ErrRunCancelled = appexec.ErrRunCancelled // ErrResumeInProgress reports that another caller is already resuming or // continuing this run in this process. A concurrent ResumeAndContinue / // ResumeRunByID / ContinueRun on the same run fails fast with it instead // of racing the pause token and surfacing an ambiguous ErrTokenSuperseded. ErrResumeInProgress = runstate.ErrResumeInProgress )
Classified run-state errors, re-exported from the runtime so callers of every orchestration mode's entry points can branch on them with errors.Is.
var AdaptiveRAG = scenariobuilder.AdaptiveRAG
AdaptiveRAG builds the adaptive-rag workflow example stack.
var AdaptiveRAGWorkflow = scenariobuilder.AdaptiveRAGWorkflow
AdaptiveRAGWorkflow builds the adaptive RAG workflow graph.
var CodeReviewPipeline = scenariobuilder.CodeReviewPipeline
CodeReviewPipeline builds the code review workflow example stack.
var CodeReviewPipelineWorkflow = scenariobuilder.CodeReviewPipelineWorkflow
CodeReviewPipelineWorkflow builds the code review workflow graph.
var ContextGovernance = scenariobuilder.ContextGovernance
ContextGovernance builds the context governance example stack.
var CorrectiveRAG = scenariobuilder.CorrectiveRAG
CorrectiveRAG builds the corrective-rag workflow example stack.
var CorrectiveRAGWorkflow = scenariobuilder.CorrectiveRAGWorkflow
CorrectiveRAGWorkflow builds the corrective RAG workflow graph.
var DeclarativeInterruptWorkflow = scenariobuilder.DeclarativeInterruptWorkflow
DeclarativeInterruptWorkflow builds the prepare → interrupt → continue graph.
var ErrFenceRequired = runstate.ErrFenceRequired
ErrFenceRequired reports that a leased run save requires a run-state repository implementing runstate.FencedRepository.
var ErrRunLeaseLost = coordination.ErrRunLeaseLost
ErrRunLeaseLost reports that this worker no longer holds the run lease (renewal returned not-held or failed) and must stop executing before another worker reaps or takes over the run. It aliases the coordination package's sentinel so the runtime engine classifies the same error the facade returns.
var ErrStaleFence = runstate.ErrStaleFence
ErrStaleFence reports that a fenced snapshot save presented a fencing token below the highest token already recorded for the run: this worker's run lease was superseded by a newer holder and its writes are rejected. It is handled exactly like ErrRunLeaseLost — the worker stops executing immediately and settles the run through the lease-lost path, never retrying the save. It aliases the runstate package's sentinel so facade and engine classify the same error.
var FixedWorkflowReviewWorkflow = scenariobuilder.FixedWorkflowReviewWorkflow
FixedWorkflowReviewWorkflow builds the inspect → review workflow graph.
var HybridResearch = scenariobuilder.HybridResearch
HybridResearch builds the hybrid research example stack.
var HybridResearchWorkflow = scenariobuilder.HybridResearchWorkflow
HybridResearchWorkflow builds the hybrid research workflow graph.
var MapItemField = scenariobuilder.MapItemField
MapItemField sets the per-item field name for map branches.
var MapNodeInput = scenariobuilder.MapNodeInput
MapNodeInput builds map node input JSON from a list field and branches.
var MapOnError = scenariobuilder.MapOnError
MapOnError sets the map node error policy branch.
var MinimalAutonomous = scenariobuilder.MinimalAutonomous
MinimalAutonomous builds the common mock/session/tool autonomous stack.
var MinimalDeclarativeInterrupt = scenariobuilder.MinimalDeclarativeInterrupt
MinimalDeclarativeInterrupt builds the declarative interrupt demo stack.
var MinimalFilesystemTool = scenariobuilder.MinimalFilesystemTool
MinimalFilesystemTool builds the filesystem tool example stack.
var MinimalFixedWorkflowReview = scenariobuilder.MinimalFixedWorkflowReview
MinimalFixedWorkflowReview builds the fixed workflow review example stack.
var MinimalHTTPTool = scenariobuilder.MinimalHTTPTool
MinimalHTTPTool builds the http tool example stack.
var MinimalHumanInLoop = scenariobuilder.MinimalHumanInLoop
MinimalHumanInLoop builds the human-in-loop demo stack.
var MinimalMCPTool = scenariobuilder.MinimalMCPTool
MinimalMCPTool builds the MCP tool example stack.
var MinimalRAG = scenariobuilder.MinimalRAG
MinimalRAG builds the rag-knowledge example stack.
var MinimalSQLTool = scenariobuilder.MinimalSQLTool
MinimalSQLTool builds the sql tool example stack.
var MinimalTicketHandling = scenariobuilder.MinimalTicketHandling
MinimalTicketHandling builds the ticket-handling example stack.
var MultiExpertResearch = scenariobuilder.MultiExpertResearch
MultiExpertResearch builds the multi-expert hybrid example stack.
var MultiExpertResearchWorkflow = scenariobuilder.MultiExpertResearchWorkflow
MultiExpertResearchWorkflow builds the parallel expert workflow graph.
var NewMinimal = scenariobuilder.NewMinimal
NewMinimal starts a scenario with the standard mock/session stack. Register tools, then call MinimalAgent or configure agents manually.
var NewScenarioBuilder = scenariobuilder.New
NewScenarioBuilder creates a scenario builder. Prefer pkg/builder when importing only the builder package without the root facade.
var NewWorkflowBuilder = scenariobuilder.NewWorkflow
NewWorkflowBuilder creates a workflow builder.
var SelfRAG = scenariobuilder.SelfRAG
SelfRAG builds the self-rag workflow example stack.
var SelfRAGWorkflow = scenariobuilder.SelfRAGWorkflow
SelfRAGWorkflow builds the self RAG workflow graph.
var TierMemoryAutonomous = scenariobuilder.TierMemoryAutonomous
TierMemoryAutonomous builds the tier-memory example stack.
var WorkflowEnhancements = scenariobuilder.WorkflowEnhancements
WorkflowEnhancements builds the workflow enhancements example stack.
var WorkflowEnhancementsWorkflow = scenariobuilder.WorkflowEnhancementsWorkflow
WorkflowEnhancementsWorkflow builds the workflow enhancements graph.
Functions ¶
func NewAPIKeyMiddleware ¶
func NewFrameworkJobHandler ¶ added in v0.1.2
func NewFrameworkJobHandler(config FrameworkRunJobHandlerConfig) (async.Handler, error)
func NewInMemoryLocker ¶ added in v0.3.0
func NewInMemoryLocker() coordination.Locker
NewInMemoryLocker creates an in-process lease manager for tests and single-process deployments.
func NewJWTAuthenticator ¶
func NewJWTAuthenticator(config JWTAuthenticatorConfig) (security.BearerAuthenticator, error)
func NewJWTMiddleware ¶
func NewOIDCJWTAuthenticator ¶
func NewOIDCJWTAuthenticator(config OIDCJWTAuthenticatorConfig) (security.BearerAuthenticator, error)
NewOIDCJWTAuthenticator creates a bearer authenticator that discovers and refreshes RSA verification keys from OIDC Discovery/JWKS endpoints.
func ScenarioJSONSchema ¶ added in v0.1.4
func ScenarioJSONSchema() []byte
ScenarioJSONSchema returns a copy of the AgentFlow scenario JSON Schema.
func StreamDetached ¶ added in v0.3.0
StreamDetached marks ctx so a run started by Framework.Stream keeps executing to a terminal state in the background when the caller's context is cancelled (client disconnect), instead of being marked Cancelled. It is the context-level equivalent of the WithStreamDetached StreamRun option for callers of the lower-level Stream API. An explicit run Cancel and a lost run lease still abort the run.
func ValidateScenario ¶
ValidateScenario validates a scenario built programmatically.
func ValidateWiring ¶ added in v0.1.4
ValidateWiring checks that a scenario's declared dependencies are covered by the provided options before constructing a Framework.
func ValidateWiringWithOptions ¶ added in v0.1.4
func ValidateWiringWithOptions(scenario core.Scenario, wiring WiringOptions, opts ...Option) error
ValidateWiringWithOptions validates wiring using explicit wiring rules.
Types ¶
type APIKeyMiddlewareConfig ¶
type APIKeyMiddlewareConfig struct {
Authenticator security.APIKeyAuthenticator
HeaderName string
}
type CodegenResult ¶ added in v0.2.0
CodegenResult contains generated builder code for a Studio graph.
type ComposeGraphRequest ¶ added in v0.4.0
type ComposeGraphRequest struct {
// Prompt is the one-sentence task the composed graph should accomplish.
Prompt string `json:"prompt"`
// Mode selects catalog (default) or scenario composition.
Mode ComposeMode `json:"mode,omitempty"`
// ComposerLLM names the LLM profile the composer agent uses; empty
// resolves to the scenario's "default" profile or the first profile.
ComposerLLM string `json:"composer_llm,omitempty"`
// MaxSteps caps the composer tool loop. Default 15.
MaxSteps int `json:"max_steps,omitempty"`
// Run executes the composed graph after validation when true. Runs are
// ephemeral: the live framework scenario is never replaced.
Run bool `json:"run,omitempty"`
// RunRequest is passed through to the run when Run is true (run_id,
// prompt, context, trust mode).
RunRequest RunRequest `json:"run_request,omitempty"`
}
ComposeGraphRequest drives one AI graph-composition call.
type ComposeGraphResult ¶ added in v0.4.0
type ComposeGraphResult struct {
Mode ComposeMode `json:"mode"`
// Graph is the exported topology of the composed (merged) scenario.
Graph graph.ScenarioGraph `json:"graph"`
// Scenario is the merged temporary scenario. It is never installed as
// the live scenario; persist explicitly via SaveStudioGraph or YAML
// codegen if desired.
Scenario *core.Scenario `json:"scenario,omitempty"`
Valid bool `json:"valid"`
Error string `json:"error,omitempty"`
// Run holds the ephemeral run outcome when Run was requested and the
// composed graph validated.
Run *RunResult `json:"run,omitempty"`
}
ComposeGraphResult reports the outcome of one composition call.
type ComposeMode ¶ added in v0.4.0
type ComposeMode string
ComposeMode selects what the AI composer may generate.
const ( // ComposeModeCatalog (default) lets the composer orchestrate only parts // already registered in the base scenario (agents, tools, skills, // subgraphs): it produces topology, nothing else. ComposeModeCatalog ComposeMode = "catalog" // ComposeModeScenario additionally lets the composer create new agents // and prompt skills, merged as an additive patch. Overwriting existing // part IDs is rejected, and new tools are never executable unless the // host bound an executor/resolver for them. ComposeModeScenario ComposeMode = "scenario" )
type EventFilterPreset ¶ added in v0.3.0
type EventFilterPreset = core.EventFilterPreset
EventFilterPreset is a named read-side event view (product_ui | diagnostic).
type EventRouter ¶ added in v0.1.2
type EventRouter = eventrouter.Router
EventRouter maps external events to run requests for a scenario.
func NewEventRouter ¶ added in v0.1.2
func NewEventRouter(scenario core.Scenario) *EventRouter
NewEventRouter creates a router from scenario trigger definitions.
type ForkRunResult ¶ added in v0.2.0
type Framework ¶
type Framework struct {
// contains filtered or unexported fields
}
Framework is an embeddable runtime wrapper for one scenario.
func New ¶
New creates a Framework for a validated scenario. By default it wires in-memory run-state and blob stores and a no-op event sink. Production applications should provide persistent repositories through options.
Example ¶
package main
import (
"context"
"encoding/json"
agentflow "github.com/aijustin/agentflow-go"
"github.com/aijustin/agentflow-go/pkg/builder"
"github.com/aijustin/agentflow-go/pkg/core"
)
func testAutonomousScenario() core.Scenario {
return builder.MinimalAutonomous("assistant", builder.MinimalScenarioName("autonomous-echo"))
}
type noopTool struct{}
func (noopTool) Execute(context.Context, core.ToolCall) (core.ToolResult, error) {
return core.ToolResult{}, nil
}
func main() {
fw, err := agentflow.New(testAutonomousScenario(), agentflow.WithToolExecutor("echo", noopTool{}))
if err != nil {
panic(err)
}
result, err := fw.Run(context.Background(), agentflow.RunRequest{
RunID: "example-run",
Prompt: "hello",
})
if err != nil {
panic(err)
}
out, _ := json.Marshal(result.Status)
println(string(out))
}
Output:
func (*Framework) Close ¶ added in v0.1.4
Close releases resources registered through WithCloser or WithDatabase.
func (*Framework) CompareRuns ¶ added in v0.2.0
func (*Framework) ComposeGraph ¶ added in v0.4.0
func (f *Framework) ComposeGraph(ctx context.Context, req ComposeGraphRequest) (ComposeGraphResult, error)
ComposeGraph is a thin Framework delegate — prefer Framework.Studio().
func (*Framework) ContinueRun ¶ added in v0.3.0
ContinueRun retries the continue of a run that is stuck in Running with unconsumed checkpoint metadata. That state arises when the human gate was approved (gate.Resume flipped the run back to Running) but the subsequent continue failed, or the worker crashed between the two; without this entry point the run would sit in Running forever with no public way forward.
The call is idempotent and safe to retry:
- a run that already reached Completed returns its persisted RunResult;
- a Running run with pending checkpoint metadata re-enters the internal continue-after-checkpoint path (workflow/hybrid runs resume from their persisted step outputs);
- anything else (Paused, Failed, Cancelled, or Running with no checkpoint metadata) returns a classified error naming the actual state, since the right entry point for those is ResumeAndContinue, RetryFailedRun, or none at all.
A concurrent ContinueRun/ResumeAndContinue on the same run fails fast with ErrResumeInProgress.
func (*Framework) ExportScenarioGraph ¶ added in v0.2.0
func (f *Framework) ExportScenarioGraph() ScenarioGraph
ExportScenarioGraph exports the framework scenario as a nested graph.
func (*Framework) GenerateStudioBuilderCode ¶ added in v0.2.0
func (f *Framework) GenerateStudioBuilderCode(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
func (*Framework) GenerateStudioBuilderCodeWithScenario ¶ added in v0.4.5
func (f *Framework) GenerateStudioBuilderCodeWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
func (*Framework) GenerateStudioScenarioYAML ¶ added in v0.2.0
func (f *Framework) GenerateStudioScenarioYAML(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
func (*Framework) GenerateStudioScenarioYAMLWithScenario ¶ added in v0.4.5
func (f *Framework) GenerateStudioScenarioYAMLWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
func (*Framework) GetRunCheckpoint ¶ added in v0.2.0
func (f *Framework) GetRunCheckpoint(ctx context.Context, runID string, version int64) (runstate.RunSnapshot, error)
GetRunCheckpoint loads one historical snapshot revision for a run.
func (*Framework) HandleEvent ¶ added in v0.1.2
HandleEvent resolves an incoming event and executes the scenario. The event type is carried into the run as its trigger kind ("event:<type>") so lifecycle events and metrics attribute the run to the external trigger that started it.
func (*Framework) ImportStudioScenarioYAML ¶ added in v0.2.0
func (f *Framework) ImportStudioScenarioYAML(ctx context.Context, yamlData []byte, layout graph.ScenarioGraph) (ImportStudioResult, error)
func (*Framework) Interject ¶ added in v0.3.0
Interject queues a mid-turn user message for an in-flight run. The autonomous tool loop drains it at the next safe point (before the next LLM call).
func (*Framework) ListRunCheckpoints ¶ added in v0.2.0
func (f *Framework) ListRunCheckpoints(ctx context.Context, runID string, limit int) (ListRunCheckpointsResult, error)
ListRunCheckpoints returns append-only snapshot revisions recorded for a run.
func (*Framework) ListRunSteps ¶ added in v0.2.0
ListRunSteps returns persisted step outputs and the current snapshot version.
func (*Framework) ListRunThread ¶ added in v0.2.0
func (*Framework) MarkAbandonedRuns ¶ added in v0.3.0
MarkAbandonedRuns scans this scenario's Running runs and marks as Failed (run_error_message="worker lost") every lease-managed run whose lease is no longer held: its worker crashed or was partitioned away, so nothing will ever move the run out of Running. It returns the IDs of the runs it marked. Requires WithRunLease.
Only runs stamped with a lease owner (run_lease_owner variable, written when the run executes under WithRunLease) are eligible: a Running run without the marker belongs to a worker that does not use lease coordination, and probing its lease would always succeed and reap live work. Tenant scope: when ctx carries a tenant-scoped principal, only that tenant's runs are scanned and reaped; runs belonging to other tenants are never touched even if the repository's List filtering is lax. Without a tenant principal this is an admin operation across all tenants.
func (*Framework) PurgeExpired ¶ added in v0.1.4
PurgeExpired deletes terminal run snapshots whose UpdatedAt is before now-maxAge. Snapshots without UpdatedAt are skipped.
func (*Framework) PurgeOrphanBlobs ¶ added in v0.1.4
PurgeOrphanBlobs deletes blob objects that are no longer referenced by any run snapshot for the current scenario (and tenant, when a principal is present).
func (*Framework) PurgeRuns ¶ added in v0.1.4
func (f *Framework) PurgeRuns(ctx context.Context, filter runstate.ListFilter, opts ...PurgeRunsOption) (int, error)
PurgeRuns deletes run snapshots matching the filter. Non-terminal runs (Running, Paused) are skipped unless WithPurgeForce is given. Each deleted run's checkpoint history is deleted alongside when a history store is configured, so time-travel data does not outlive its run.
func (*Framework) PurgeWithPolicy ¶ added in v0.1.4
PurgeWithPolicy deletes run snapshots using a retention policy.
func (*Framework) ResolveEvent ¶ added in v0.1.2
func (f *Framework) ResolveEvent(event IncomingEvent) (RunRequest, error)
ResolveEvent resolves an incoming event without executing it.
func (*Framework) Resume ¶
func (f *Framework) Resume(ctx context.Context, token string, decision core.Decision, amendment json.RawMessage) error
Resume approves or rejects a paused run via the human gate without continuing execution. An approved run becomes Running with its checkpoint metadata still attached and no execution driver behind it; call ContinueRun (or ResumeAndContinue) to carry it to a terminal state. Such a run is never reaped by MarkAbandonedRuns, which only touches runs stamped with a lease owner, so the recovery window is unbounded.
func (*Framework) ResumeAndContinue ¶ added in v0.1.2
func (f *Framework) ResumeAndContinue(ctx context.Context, token string, decision core.Decision, amendment json.RawMessage) (RunResult, error)
ResumeAndContinue resumes a paused run and continues execution until the next pause point or completion.
The call is idempotent: resuming a run that already reached Completed returns the persisted RunResult instead of a token error. A concurrent resume of the same run (with or without run leases) fails fast with ErrResumeInProgress rather than racing the pause token into an ambiguous ErrTokenSuperseded.
When run leases are enabled, the lease is acquired before gate.Resume so the run is never left Running without a holder. Callers that only approve via Resume / ResumeRunByID(..., false) can carry the run to a terminal state later with ContinueRun.
func (*Framework) ResumeFromCheckpoint ¶ added in v0.2.0
func (f *Framework) ResumeFromCheckpoint(ctx context.Context, runID string, version int64) (RunResult, error)
ResumeFromCheckpoint restores a historical snapshot revision and reruns the workflow forward from that restored state.
func (*Framework) ResumeFromStep ¶ added in v0.2.0
ResumeFromStep rewinds a workflow run to the given node, truncating that node and all downstream step outputs, then reruns from that point forward.
func (*Framework) ResumeRunByID ¶ added in v0.2.0
func (f *Framework) ResumeRunByID(ctx context.Context, runID string, decision core.Decision, amendment json.RawMessage, continueExecution bool) (RunResult, error)
ResumeRunByID resumes a paused run by signing a HITL token from the current snapshot. When continueExecution is true, execution continues until completion or the next pause.
The call is idempotent for a run that already reached Completed: it returns the persisted RunResult instead of a "not paused" error.
SECURITY: knowing the run ID alone is sufficient to mint a fresh resume token here — this is an indefinite resume capability that is NOT bounded by the HITL token TTL (the TTL only constrains tokens issued at pause time). Any HTTP surface exposing this method must authorize callers, e.g. via WithResumeAuthorizationHook; the built-in observability/studio and checkpoint write endpoints already default-deny without a configured policy.
func (*Framework) RetryFailedRun ¶ added in v0.3.0
RetryFailedRun moves a Failed run back to Running and re-executes it from its persisted progress: workflow nodes that already produced step outputs are skipped, a hybrid run whose workflow phase already finished re-enters the autonomous phase directly (workflow step outputs are re-hydrated into the request context), and an autonomous run with unconsumed checkpoint metadata (e.g. a lease-lost failure that left a tool-approval checkpoint behind) continues from that checkpoint. An autonomous run without pending checkpoint metadata resumes from the last persisted iteration boundary (StepOutputs["auto:iter:<n>"], written after every completed LLM+tools iteration): completed iterations are not re-sent to the LLM. Side effects of the one iteration that crashed before its boundary was persisted may replay - at-least-once at iteration granularity; side-effecting tools should deduplicate on the run-scoped idempotency key. A failed run with neither checkpoint metadata nor iteration progress has nothing resumable and returns an explicit error instead of silently re-running from scratch.
func (*Framework) RunStateRepository ¶
func (f *Framework) RunStateRepository() runstate.Repository
RunStateRepository returns the repository backing run-state snapshots.
func (*Framework) RunStructured ¶
RunStructured executes an agent using its configured output_schema and a gateway that implements llm.StructuredOutputter.
func (*Framework) RunStudioGraph ¶ added in v0.2.0
func (f *Framework) RunStudioGraph(ctx context.Context, edited graph.ScenarioGraph, req RunRequest) (RunResult, error)
func (*Framework) RunStudioGraphWithScenario ¶ added in v0.4.4
func (f *Framework) RunStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, req RunRequest) (RunResult, error)
func (*Framework) SaveStudioGraph ¶ added in v0.2.0
func (f *Framework) SaveStudioGraph(ctx context.Context, edited graph.ScenarioGraph, path string) (SaveStudioResult, error)
func (*Framework) SaveStudioGraphWithScenario ¶ added in v0.4.4
func (f *Framework) SaveStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, path string) (SaveStudioResult, error)
func (*Framework) Stream ¶
Stream executes an agent using a gateway that implements llm.Streamer. Callers must drain the returned channel to completion or cancel ctx; otherwise the engine goroutine (and any run lease renewer) may remain blocked indefinitely.
func (*Framework) StreamRun ¶ added in v0.3.0
func (f *Framework) StreamRun(ctx context.Context, req RunRequest, opts ...StreamRunOption) (<-chan StreamFrame, error)
StreamRun executes a run and merges LLM token chunks with runtime events into a single frame channel. Existing Stream remains unchanged.
Events are teed via a context-scoped sink for the duration of the stream so callers do not need an EventHub. Done is emitted only after the token stream closes and pending teed events have been flushed into the frame channel.
Use WithStreamEventFilterPreset to project events for product_ui vs diagnostic views. Default is diagnostic (full stream).
func (*Framework) Studio ¶ added in v0.3.0
Studio returns the development-time Studio API bound to this framework.
func (*Framework) StudioParts ¶ added in v0.4.0
func (f *Framework) StudioParts() StudioParts
StudioParts is a thin Framework delegate — prefer Framework.Studio().
func (*Framework) ValidateStudioGraph ¶ added in v0.2.0
func (f *Framework) ValidateStudioGraph(ctx context.Context, edited graph.ScenarioGraph) (ValidateStudioResult, error)
func (*Framework) ValidateStudioGraphWithScenario ¶ added in v0.4.5
func (f *Framework) ValidateStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (ValidateStudioResult, error)
type FrameworkRunJobHandlerConfig ¶
type FrameworkRunJobHandlerConfig struct {
Framework *Framework
}
type ImportStudioResult ¶ added in v0.2.0
type ImportStudioResult struct {
ScenarioName string `json:"scenario_name"`
Graph graph.ScenarioGraph `json:"graph"`
}
ImportStudioResult describes a YAML import into an editable Studio graph.
type IncomingEvent ¶ added in v0.1.2
type IncomingEvent = eventrouter.Event
IncomingEvent is an external trigger delivered through webhooks or CLI.
type JWTAlgorithm ¶
type JWTAlgorithm string
const ( JWTAlgorithmHS256 JWTAlgorithm = "HS256" JWTAlgorithmRS256 JWTAlgorithm = "RS256" )
type JWTAuthenticatorConfig ¶
type JWTKey ¶
type JWTKey struct {
ID string
Algorithm JWTAlgorithm
HMACSecret []byte
RSAPublicKeyPEM []byte
}
type JWTMiddlewareConfig ¶
type JWTMiddlewareConfig struct {
Authenticator security.BearerAuthenticator
}
type ListRunCheckpointsResult ¶ added in v0.2.0
type ListRunCheckpointsResult struct {
RunID string `json:"run_id"`
Checkpoints []runstate.CheckpointSummary `json:"checkpoints"`
}
ListRunCheckpointsResult summarizes append-only snapshot revisions for a run.
type ListRunStepsResult ¶ added in v0.2.0
type ListRunStepsResult struct {
RunID string `json:"run_id"`
Version int64 `json:"version"`
Status runstate.RunStatus `json:"status"`
CurrentNodeID string `json:"current_node_id,omitempty"`
PendingHITL *PendingHITLInfo `json:"pending_hitl,omitempty"`
Steps []RunStep `json:"steps"`
}
ListRunStepsResult summarizes checkpointed workflow steps for a run.
type MapBranch ¶ added in v0.2.0
type MapBranch = scenariobuilder.MapBranch
MapBranch configures a map node fan-out branch.
type OIDCJWTAuthenticatorConfig ¶
type OIDCJWTAuthenticatorConfig struct {
Issuer string
Audience string
DiscoveryURL string
JWKSURL string
HTTPClient *http.Client
RefreshInterval time.Duration
Now func() time.Time
Leeway time.Duration
PrincipalType identity.PrincipalType
TenantClaim string
WorkspaceClaim string
ProjectClaim string
RolesClaim string
}
type Option ¶
type Option func(*options) error
Option customizes Framework construction.
func WithApprovalStore ¶ added in v0.3.0
func WithApprovalStore(store toolorch.ApprovalStore) Option
WithApprovalStore wires a session/run-scoped approval decision cache.
func WithAuditSink ¶
WithAuditSink wires an audit sink used for compliance-oriented events.
func WithBlobStore ¶
WithBlobStore wires storage for large step outputs.
func WithCheckpointHistory ¶ added in v0.2.0
func WithCheckpointHistory(history runstate.CheckpointHistory) Option
WithCheckpointHistory wires append-only run snapshot history for time-travel.
func WithCloser ¶ added in v0.1.4
WithCloser registers a function invoked by Framework.Close in LIFO order.
func WithCognitiveMemory ¶ added in v0.1.9
func WithCognitiveMemory(name string, repo memory.CognitiveMemory) Option
WithCognitiveMemory wires a cognitive memory backend by scenario memory name.
func WithDatabase ¶ added in v0.1.4
WithDatabase registers a database handle for automatic close on Framework.Close.
func WithDeferredTools ¶ added in v0.4.2
WithDeferredTools controls whether a wired tool catalog defers non-pinned tool schemas until load_tool_schemas is called. Default true when a catalog is attached.
func WithEventSink ¶
WithEventSink wires observability event output.
func WithEventStore ¶ added in v0.3.1
func WithEventStore(store observability.EventStore) Option
WithEventStore wires the durable runtime event store so the framework can cascade retention deletions to event history (see PurgeRuns/PurgeExpired) and deliver outbox-parked events (see WithOutboxRelay). The store is typically the same one wrapped by the EventStoreSink passed to WithEventSink; the sink chain itself stays opaque to the framework.
func WithHITLTokenRotation ¶ added in v0.3.0
WithHITLTokenRotation wires the built-in human gate with a rotating key pair: new resume tokens are signed with primary, while tokens signed by either primary or secondary still verify. Deploy with (new, old), wait for in-flight tokens to drain, then switch back to WithHITLTokenSecret(new) — no token is invalidated mid-rotation. Both secrets must be at least runstate.MinTokenSecretLength bytes.
func WithHITLTokenSecret ¶
WithHITLTokenSecret wires the built-in HMAC-token human gate using the same RunStateRepository as the framework. tokenWriter can be nil. The secret must be at least runstate.MinTokenSecretLength bytes.
func WithHITLTokenTTL ¶
WithHITLTokenTTL sets the lifetime for tokens emitted by WithHITLTokenSecret. Without this option tokens expire after 24 hours; pass 0 explicitly to issue tokens that never expire.
func WithHumanGate ¶
WithHumanGate wires a custom human-in-the-loop gate.
func WithInterjectDrainPolicy ¶ added in v0.3.0
func WithInterjectDrainPolicy(policy interjection.DrainPolicy) Option
WithInterjectDrainPolicy controls when Framework.Interject messages enter the autonomous tool loop (Codex-style steer drain alignment).
func WithJobQueue ¶ added in v0.1.9
WithJobQueue wires an async queue used to enqueue memory.reconcile jobs after tier writes.
func WithLLMGateway ¶
WithLLMGateway wires a provider-neutral LLM gateway.
func WithLLMPayloadCapture ¶ added in v0.3.1
WithLLMPayloadCapture controls whether LLMCalled events include message and prompt plaintext. It is disabled by default: payloads carry only message count, per-message content lengths, and a truncated content hash, so user input - which may contain PII - is not persisted to the event store. Enable it only for debugging (Studio debug drawers show LLM 入参 only when capture is on); captured plaintext still passes through the output redactor configured with WithOutputRedactor before it is emitted.
func WithLogger ¶ added in v0.1.1
WithLogger wires a structured logger that receives warning and error messages from the runtime. If not provided, messages are silently discarded.
func WithMemoryRepository ¶
func WithMemoryRepository(name string, repo memory.Repository) Option
WithMemoryRepository wires a memory backend by scenario memory name.
func WithOutboxRelay ¶ added in v0.3.1
WithOutboxRelay starts a background loop (same GoSafe + closers pattern as the run reaper) that drains the run-state repository's event outbox: unpublished rows are delivered to the durable event store wired with WithEventStore and marked published, at-least-once — delivery failures leave the row unpublished for the next sweep, and redelivery is deduplicated by the event store's UNIQUE (run_id, sequence) constraint. The relay stops on Framework.Close.
Pair it with the outbox-capable event sink (adapters.NewPostgresOutboxEventSink) in the WithEventSink fanout: that sink parks events in the outbox whenever the durable append fails, and the relay closes the gap. Multiple nodes may relay concurrently against the same database; marking is a conditional update (WHERE published_at IS NULL) and duplicate delivery collapses on the sequence constraint.
interval defaults to 2s when non-positive. New returns an error unless the event store implements observability.SequencedEventStore and the run-state repository implements runstate.OutboxRepository — today that means the PostgreSQL runstate repository; combining Redis runstate with a PostgreSQL outbox is not supported because the outbox must share the snapshots' database.
func WithOutputRedactor ¶
func WithOutputRedactor(redactor governance.OutputRedactor) Option
WithOutputRedactor wires an output redactor that scrubs sensitive fields from step outputs before they are persisted or returned to callers.
func WithRecorder ¶ added in v0.1.1
func WithRecorder(recorder observability.Recorder) Option
WithRecorder wires a metrics recorder. If not provided, metrics are discarded via observability.NoopRecorder.
func WithRequireLLM ¶ added in v0.1.4
func WithRequireLLM() Option
WithRequireLLM makes New fail when no LLM gateway is wired.
func WithResumeAuthorizationHook ¶ added in v0.3.0
func WithResumeAuthorizationHook(hook ResumeAuthorizationHook) Option
WithResumeAuthorizationHook installs the authorization hook consulted by ResumeRunByID before it signs a new resume token. Without a hook the library keeps its historical behavior (any caller that knows the run ID may resume), so every HTTP exposure of ResumeRunByID must be authorized out-of-band — see the warning on ResumeRunByID.
func WithRunLease ¶ added in v0.3.0
WithRunLease enables distributed run-lease coordination: every Run, RunStructured, ResumeAndContinue, and RetryFailedRun holds (and renews) a lease on the run for as long as it executes. A run left in Running whose lease has expired belonged to a crashed or partitioned worker and can be reaped with MarkAbandonedRuns; pair it with WithRunReaper on multi-node deployments so reaping happens automatically.
The lease's fencing token travels with execution: when the run-state repository implements runstate.FencedRepository, every snapshot save is validated against the run's fence high-water mark, so a zombie writer whose lease was superseded fails with ErrStaleFence instead of clobbering the new owner's state. Framework construction fails with ErrFenceRequired when the configured run-state repository cannot fence; leased execution never falls back to an unprotected plain save.
owner identifies this worker in lease ownership; when empty, a random worker ID is generated. ttl defaults to 30s when non-positive.
func WithRunReaper ¶ added in v0.3.1
WithRunReaper starts a background loop that periodically calls MarkAbandonedRuns, failing Running runs whose worker crashed or was partitioned away (their run lease is no longer held). It requires WithRunLease; New returns an error otherwise.
The sweep is lease-probe based and idempotent, so any number of nodes may run it concurrently against shared storage — a run is reaped exactly once no matter how many reapers race it. Multi-node deployments are strongly encouraged to enable it on every worker: without it, a crashed worker leaves its runs in Running forever.
interval defaults to 1m when zero. gracePeriod overrides how long a Running run must go without snapshot updates before it becomes reapable; it defaults to the run-lease TTL, which covers the Resume and gate→lease windows. The reaper stops on Framework.Close.
func WithRunStateRepository ¶
func WithRunStateRepository(repo runstate.Repository) Option
WithRunStateRepository wires run-state persistence used for pause/resume.
func WithSecurityPolicy ¶
WithSecurityPolicy wires an authorization policy used by runtime execution.
func WithTierColdSummarizer ¶ added in v0.2.0
func WithTierColdSummarizer(name string, summarizer tier.ContentSummarizer) Option
WithTierColdSummarizer wires an LLM summarizer for cold-tier archive on a memory name.
func WithTierColdSummaryIndexer ¶ added in v0.2.0
func WithTierColdSummaryIndexer(name string, indexer tier.ColdSummaryIndexer) Option
WithTierColdSummaryIndexer wires a vector indexer for cold-tier summary recall on a memory name.
func WithTierMemory ¶ added in v0.1.9
WithTierMemory wires a tier manager by scenario memory name.
func WithTierStore ¶ added in v0.1.9
WithTierStore wires a tier store and the policy used to build its default manager. The supplied policy overrides the policy derived from the scenario memory tier settings for this memory name.
func WithToolApprovalEvaluator ¶ added in v0.3.0
func WithToolApprovalEvaluator(evaluator core.ToolApprovalEvaluator) Option
WithToolApprovalEvaluator wires dynamic tool approval evaluation beyond static scenario Tool.Approval policies.
func WithToolCatalog ¶ added in v0.4.2
func WithToolCatalog(catalog toolcatalog.Catalog) Option
WithToolCatalog attaches a deferred tool catalog to the engine. When set, the LLM initially sees only catalog meta-tools (search_tools, load_tool_schemas) plus pinned or non-MCP builtin tools on the agent.
func WithToolExecutor ¶
func WithToolExecutor(name string, executor core.ToolExecutor) Option
WithToolExecutor registers an executable tool implementation by scenario tool name. Agent tool policies still come from the scenario YAML.
func WithToolGovernancePolicy ¶
func WithToolGovernancePolicy(policy governance.ToolPolicy) Option
WithToolGovernancePolicy wires a per-invocation tool governance policy. The policy is evaluated before every tool execution and can deny calls based on side-effect level, call budget, or custom logic.
func WithToolOrchestrator ¶ added in v0.3.0
func WithToolOrchestrator(orch toolorch.ToolOrchestrator) Option
WithToolOrchestrator wires approval-cache / post-attempt orchestration. OS sandbox escalate remains host-owned via AttemptResult.
func WithToolOutputTransform ¶ added in v0.3.0
func WithToolOutputTransform(tool string, fn contextwindow.ToolOutputTransform) Option
WithToolOutputTransform registers a per-tool reshaper applied before LLM and memory persistence when ToolResultMaxTokens / ToolOutputMaxBytes apply.
func WithToolResolver ¶
func WithToolResolver(resolver core.ToolResolver) Option
WithToolResolver wires a resolver that creates or retrieves tool executors only when a declared tool is invoked. Explicit WithToolExecutor registrations take precedence over the resolver.
func WithToolResolverCacheLimit ¶ added in v0.4.5
WithToolResolverCacheLimit bounds principal-scoped lazy executor caching. The default is 1024 entries; zero disables caching.
func WithTracer ¶ added in v0.1.1
func WithTracer(tracer observability.Tracer) Option
WithTracer wires a distributed-tracing provider. If not provided, tracing is a no-op via observability.NoopTracer.
func WithTurnStopHook ¶ added in v0.3.0
func WithTurnStopHook(hook core.TurnStopHook) Option
WithTurnStopHook registers a host callback that may veto turn completion and inject a continuation prompt (Codex stop-hooks style).
type PendingHITLInfo ¶ added in v0.2.0
type PendingHITLInfo struct {
NodeID string `json:"node_id,omitempty"`
Interrupt bool `json:"interrupt,omitempty"`
}
PendingHITLInfo describes a paused run awaiting HITL approval.
type Plan ¶
type Plan struct {
Scenario core.Scenario
LLMs map[string]llm.Profile
Memory map[string]memory.Namespace
}
Plan is a resolved scenario plan that library users can inspect before creating a Framework.
type PurgeRunsOption ¶ added in v0.3.0
type PurgeRunsOption func(*purgeRunsOptions)
PurgeRunsOption customizes PurgeRuns.
func WithPurgeForce ¶ added in v0.3.0
func WithPurgeForce() PurgeRunsOption
WithPurgeForce lets PurgeRuns delete runs in any status, including Running and Paused. Without it, non-terminal runs are skipped so a retention sweep can never delete a run that is still executing or awaiting a human.
type RedisLocker ¶ added in v0.3.1
type RedisLocker interface {
coordination.Locker
Close() error
}
RedisLocker is a coordination.Locker with a Close method releasing the underlying connection pool. Lockers built from a caller-provided go-redis client do not close that client on Close.
func NewRedisLocker ¶
func NewRedisLocker(config RedisLockerConfig) (RedisLocker, error)
NewRedisLocker creates a Redis-backed lease manager for distributed worker and workflow coordination. Every Acquire mints a monotonically increasing fencing token (Lease.Token); Renew and Release compare the full "{owner}:{token}" lock value, so a stale handle from a superseded holder — including a different process configured with the same owner name — is rejected. The returned locker owns a pooled go-redis client; close it with Close when done.
func NewRedisLockerFromClient ¶ added in v0.3.1
func NewRedisLockerFromClient(client *redis.Client, keyPrefix string) (RedisLocker, error)
NewRedisLockerFromClient wraps an existing pooled go-redis client so several subsystems (run lease, device registry, command routing) can share one connection pool. The client stays owned by the caller and is not closed by the locker.
type RedisLockerConfig ¶
type ResumeAuthorizationHook ¶ added in v0.3.0
ResumeAuthorizationHook authorizes a ResumeRunByID call before the framework mints a fresh HITL token for runID. A nil error allows the resume; any non-nil error aborts it and is returned to the caller.
type RetentionPolicy ¶ added in v0.1.4
type RetentionPolicy struct {
MaxAge time.Duration
Status runstate.RunStatus
ScenarioName string
Limit int
}
RetentionPolicy controls run-state cleanup.
type RunRequest ¶
type RunRequest = appexec.RunRequest
RunRequest is the input passed to Framework.Run.
type RunStep ¶ added in v0.2.0
type RunStep struct {
NodeID string `json:"node_id"`
Output runstate.StepOutputRef `json:"output"`
}
RunStep describes one persisted workflow step output.
type SaveStudioResult ¶ added in v0.2.0
type SaveStudioResult struct {
Path string `json:"path"`
ScenarioName string `json:"scenario_name"`
Graph graph.ScenarioGraph `json:"graph,omitempty"`
}
SaveStudioResult describes a persisted Studio graph write.
type ScenarioBuilder ¶ added in v0.1.10
type ScenarioBuilder = scenariobuilder.ScenarioBuilder
ScenarioBuilder constructs scenarios with a fluent Go API. See pkg/builder for the full surface.
type ScenarioGraph ¶ added in v0.2.0
type ScenarioGraph = graph.ScenarioGraph
ScenarioGraph is a Studio-friendly orchestration topology view.
type StreamFrame ¶ added in v0.3.0
type StreamFrame struct {
Kind StreamFrameKind
Chunk *llm.ChatChunk // for token
Event *core.Event // for event
Err error
Result *RunResult // for done
// EventsLost carries the cumulative number of teed events dropped so far
// when Kind is StreamFrameEventsLost.
EventsLost int64
}
StreamFrame is a unified token/event/terminal frame for StreamRun.
type StreamFrameKind ¶ added in v0.3.0
type StreamFrameKind string
StreamFrameKind discriminates unified StreamRun frames.
const ( StreamFrameToken StreamFrameKind = "token" StreamFrameEvent StreamFrameKind = "event" StreamFrameDone StreamFrameKind = "done" StreamFrameError StreamFrameKind = "error" // StreamFrameEventsLost marks that teed events were dropped because the // frame consumer fell behind; EventsLost carries the cumulative count. // Token frames are never dropped, so the stream stays authoritative for // the answer itself. StreamFrameEventsLost StreamFrameKind = "events_lost" )
type StreamRunOption ¶ added in v0.3.0
type StreamRunOption func(*streamRunOptions)
StreamRunOption configures StreamRun read-side behavior.
func WithStreamDetached ¶ added in v0.3.0
func WithStreamDetached() StreamRunOption
WithStreamDetached detaches execution from the caller's context: when the caller's ctx is cancelled (e.g. the SSE client disconnects), the run is NOT marked Cancelled but keeps executing in the background until it reaches a terminal state and persists its result normally. The frame channel closes when the caller goes away; the terminal state is observable afterwards via the run-state repository. An explicit Framework-level cancellation of the run (Cancel API) and a lost run lease still abort it.
func WithStreamEventFilterPreset ¶ added in v0.3.0
func WithStreamEventFilterPreset(preset EventFilterPreset) StreamRunOption
WithStreamEventFilterPreset selects the event view for StreamFrameEvent frames. EventStore / WithEventSink still receive the full stream. Empty defaults to diagnostic (all events, including MemoryRead and ContextPrepared).
type Studio ¶ added in v0.3.0
type Studio struct {
// contains filtered or unexported fields
}
Studio groups development-time graph editing and run inspection APIs. Prefer Framework.Studio() for new call sites; existing Framework methods remain as thin delegates for compatibility.
func (Studio) CompareRuns ¶ added in v0.3.0
func (s Studio) CompareRuns(ctx context.Context, runA, runB string) (studio.RunCompareResult, error)
CompareRuns diffs step outputs between two persisted runs.
func (Studio) ComposeGraph ¶ added in v0.4.0
func (s Studio) ComposeGraph(ctx context.Context, req ComposeGraphRequest) (ComposeGraphResult, error)
ComposeGraph generates a validated scenario graph for a natural-language task using an agentic composer: an internal agent builds the draft through compose_* tools with incremental validation feedback, the result is merged onto a deep copy of the live scenario, fully validated, and optionally executed ephemerally. The live framework state is never mutated.
func (Studio) ForkRun ¶ added in v0.3.0
func (s Studio) ForkRun(ctx context.Context, parentRunID string, version int64) (ForkRunResult, error)
ForkRun copies a run snapshot into a new run ID without modifying the parent run.
func (Studio) GenerateStudioBuilderCode ¶ added in v0.3.0
func (s Studio) GenerateStudioBuilderCode(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
GenerateStudioBuilderCode renders builder Go code for an edited Studio graph.
func (Studio) GenerateStudioBuilderCodeWithScenario ¶ added in v0.4.5
func (s Studio) GenerateStudioBuilderCodeWithScenario(_ context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
GenerateStudioBuilderCodeWithScenario renders builder code including an optional additive scenario-mode composition draft.
func (Studio) GenerateStudioScenarioYAML ¶ added in v0.3.0
func (s Studio) GenerateStudioScenarioYAML(ctx context.Context, edited graph.ScenarioGraph) (CodegenResult, error)
GenerateStudioScenarioYAML renders legacy scenario YAML for an edited Studio graph.
func (Studio) GenerateStudioScenarioYAMLWithScenario ¶ added in v0.4.5
func (s Studio) GenerateStudioScenarioYAMLWithScenario(_ context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (CodegenResult, error)
GenerateStudioScenarioYAMLWithScenario renders YAML including an optional additive scenario-mode composition draft.
func (Studio) ImportStudioScenarioYAML ¶ added in v0.3.0
func (s Studio) ImportStudioScenarioYAML(_ context.Context, yamlData []byte, layout graph.ScenarioGraph) (ImportStudioResult, error)
ImportStudioScenarioYAML parses legacy scenario YAML and returns an editable graph. When layout is non-empty, node positions from layout are merged onto the imported graph.
func (Studio) ListRunThread ¶ added in v0.3.0
ListRunThread returns runs in the same fork/thread group as the given run.
func (Studio) Parts ¶ added in v0.4.0
func (s Studio) Parts() StudioParts
Parts lists the composable parts of the live scenario.
func (Studio) RunStudioGraph ¶ added in v0.3.0
func (s Studio) RunStudioGraph(ctx context.Context, edited graph.ScenarioGraph, req RunRequest) (RunResult, error)
RunStudioGraph validates an edited graph and executes it as a new run.
func (Studio) RunStudioGraphWithScenario ¶ added in v0.4.4
func (s Studio) RunStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, req RunRequest) (RunResult, error)
RunStudioGraphWithScenario executes a graph with an optional additive scenario-mode compose draft without mutating the live Framework.
func (Studio) SaveStudioGraph ¶ added in v0.3.0
func (s Studio) SaveStudioGraph(ctx context.Context, edited graph.ScenarioGraph, path string) (SaveStudioResult, error)
SaveStudioGraph validates an edited graph, writes legacy YAML to path, and atomically replaces the live scenario and engine so subsequent runs use the saved definition (not a half-updated Framework / stale Engine pair).
func (Studio) SaveStudioGraphWithScenario ¶ added in v0.4.4
func (s Studio) SaveStudioGraphWithScenario(ctx context.Context, edited graph.ScenarioGraph, draft *core.Scenario, path string) (SaveStudioResult, error)
SaveStudioGraphWithScenario persists a graph together with the additive agents/skills returned by scenario-mode ComposeGraph. Existing live parts are immutable; a stale or tampered draft that changes them is rejected.
func (Studio) ValidateStudioGraph ¶ added in v0.3.0
func (s Studio) ValidateStudioGraph(ctx context.Context, edited graph.ScenarioGraph) (ValidateStudioResult, error)
ValidateStudioGraph validates an edited Studio graph against the framework scenario.
func (Studio) ValidateStudioGraphWithScenario ¶ added in v0.4.5
func (s Studio) ValidateStudioGraphWithScenario(_ context.Context, edited graph.ScenarioGraph, draft *core.Scenario) (ValidateStudioResult, error)
ValidateStudioGraphWithScenario validates a graph together with the additive agents/skills returned by scenario-mode composition.
type StudioPart ¶ added in v0.4.0
type StudioPart struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
StudioPart describes one composable part of the live scenario.
type StudioParts ¶ added in v0.4.0
type StudioParts struct {
Agents []StudioPart `json:"agents"`
Tools []StudioPart `json:"tools"`
Skills []StudioPart `json:"skills"`
Subgraphs []StudioPart `json:"subgraphs"`
}
StudioParts groups the live scenario's composable parts by kind, sorted by name. It backs the Studio parts palette and AI composition catalog.
type ThreadRunSummary ¶ added in v0.2.0
type ThreadRunSummary struct {
RunID string `json:"run_id"`
ParentRunID string `json:"parent_run_id,omitempty"`
ForkFromVersion int64 `json:"fork_from_version,omitempty"`
ThreadID string `json:"thread_id"`
Status runstate.RunStatus `json:"status"`
ScenarioName string `json:"scenario_name,omitempty"`
}
ThreadRunSummary describes one run in a fork/thread group.
type TrustMode ¶ added in v0.3.0
TrustMode controls run-scoped tool approval overrides (e.g. full_trust).
type ValidateStudioResult ¶ added in v0.2.0
type ValidateStudioResult struct {
Valid bool `json:"valid"`
Error string `json:"error,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
Scenario string `json:"scenario_name"`
}
ValidateStudioResult reports graph/scenario validation output for Studio.
type WiringOptions ¶ added in v0.1.4
WiringOptions controls ValidateWiring and optional New-time checks.
type WorkflowBuilder ¶ added in v0.1.10
type WorkflowBuilder = scenariobuilder.WorkflowBuilder
WorkflowBuilder constructs workflow graphs with a fluent Go API.
Source Files
¶
- builder.go
- compose_builder.go
- doc.go
- framework.go
- framework_checkpoint.go
- framework_compose.go
- framework_continue.go
- framework_event.go
- framework_graph.go
- framework_hydrate.go
- framework_outbox.go
- framework_state.go
- framework_stream.go
- framework_studio.go
- framework_workflow.go
- lease.go
- lifecycle.go
- meta.go
- retention.go
- security.go
- wiring.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
go/builder
command
|
|
|
go/compose-graph
command
Command compose-graph demonstrates AI graph composition (Studio.ComposeGraph) in both modes: catalog (orchestrate existing parts only) and scenario (compose new agents plus topology).
|
Command compose-graph demonstrates AI graph composition (Studio.ComposeGraph) in both modes: catalog (orchestrate existing parts only) and scenario (compose new agents plus topology). |
|
go/event-trigger
command
|
|
|
go/hitl-resume
command
|
|
|
go/http-worker
command
|
|
|
go/minimal
command
|
|
|
go/postgres
command
|
|
|
go/scenario
Package scenario provides builder stacks shared by examples/go programs.
|
Package scenario provides builder stacks shared by examples/go programs. |
|
go/tier-memory
command
|
|
|
go/tier-worker
command
tier-worker runs the tier-memory builder stack with Postgres warm tier, file or blob cold tier, and async memory.reconcile jobs via a shared job queue.
|
tier-worker runs the tier-memory builder stack with Postgres warm tier, file or blob cold tier, and async memory.reconcile jobs via a shared job queue. |
|
go/validate
command
|
|
|
internal
|
|
|
adapter/coordination/inmem
Package inmem provides an in-process coordination.Locker for tests and single-process deployments.
|
Package inmem provides an in-process coordination.Locker for tests and single-process deployments. |
|
adapter/coordination/redis
Package redis provides a coordination.Locker backed by Redis with monotonically increasing fencing tokens.
|
Package redis provides a coordination.Locker backed by Redis with monotonically increasing fencing tokens. |
|
fsatomic
Package fsatomic provides crash-safe atomic file writes shared by the file-backed adapters.
|
Package fsatomic provides crash-safe atomic file writes shared by the file-backed adapters. |
|
toolinvoke
Package toolinvoke holds shared tool-invocation preflight checks used by both the autonomous runtime tool loop and the workflow NodeTool path so approval, input validation, side-effect retry, and security resource shape cannot drift between the two stacks.
|
Package toolinvoke holds shared tool-invocation preflight checks used by both the autonomous runtime tool loop and the workflow NodeTool path so approval, input validation, side-effect retry, and security resource shape cannot drift between the two stacks. |
|
migrations
|
|
|
postgres
Package postgres applies and inspects the versioned PostgreSQL schema migrations embedded from this directory (the NNNN_*.up.sql files).
|
Package postgres applies and inspects the versioned PostgreSQL schema migrations embedded from this directory (the NNNN_*.up.sql files). |
|
postgres/cmd/apply-migrations
command
Command apply-migrations applies the embedded agentflow PostgreSQL schema migrations to the database named by AGENT_POSTGRES_DSN (or the first argument).
|
Command apply-migrations applies the embedded agentflow PostgreSQL schema migrations to the database named by AGENT_POSTGRES_DSN (or the first argument). |
|
pkg
|
|
|
adapters
Package adapters collects the convenience constructors for the concrete adapters shipped with agentflow: run-state/blob/memory stores, job queues, LLM providers, catalog manifests, knowledge and MCP tooling, built-in tool executors, tiered memory, and observability sinks/stores.
|
Package adapters collects the convenience constructors for the concrete adapters shipped with agentflow: run-state/blob/memory stores, job queues, LLM providers, catalog manifests, knowledge and MCP tooling, built-in tool executors, tiered memory, and observability sinks/stores. |
|
builder
Package builder is the **primary** way to construct core.Scenario values for agentflow-go.
|
Package builder is the **primary** way to construct core.Scenario values for agentflow-go. |
|
httpx
Package httpx hosts the HTTP adapter constructors for the agentflow root facade (checkpoint, retention, studio, webhook/human-gate, async jobs, production composition, and the observability dashboard) plus the scenario wiring helpers whose signatures reference root-facade types such as agentflow.Framework and agentflow.Option.
|
Package httpx hosts the HTTP adapter constructors for the agentflow root facade (checkpoint, retention, studio, webhook/human-gate, async jobs, production composition, and the observability dashboard) plus the scenario wiring helpers whose signatures reference root-facade types such as agentflow.Framework and agentflow.Option. |
|
interjection
Package interjection formats and buffers mid-turn user messages.
|
Package interjection formats and buffers mid-turn user messages. |
|
memory/tier
Package tier implements the tiered memory subsystem: tier-scoped record stores, a manager that remembers and recalls records across hot/warm/cold levels, and the policies that migrate records between them.
|
Package tier implements the tiered memory subsystem: tier-scoped record stores, a manager that remembers and recalls records across hot/warm/cold levels, and the policies that migrate records between them. |
|
planmode
Package planmode provides a pure interactive plan-mode state machine.
|
Package planmode provides a pure interactive plan-mode state machine. |
|
retry
Package retry provides the retry classification and backoff shared by the autonomous runtime and the workflow orchestrator, so both apply the same semantics: only errors that explicitly classify themselves as retryable are re-attempted, with exponential backoff and jitter between attempts.
|
Package retry provides the retry classification and backoff shared by the autonomous runtime and the workflow orchestrator, so both apply the same semantics: only errors that explicitly classify themselves as retryable are re-attempted, with exponential backoff and jitter between attempts. |
|
security/ssrf
Package ssrf provides Server-Side Request Forgery guards for URL-fetching tools.
|
Package ssrf provides Server-Side Request Forgery guards for URL-fetching tools. |
|
testutil
Package testutil provides helpers for testing applications built on agentflow.
|
Package testutil provides helpers for testing applications built on agentflow. |
|
toolorch
Package toolorch provides Codex-inspired tool orchestration helpers for autonomous runs: sampling step freeze, approval cache, and deny breakers.
|
Package toolorch provides Codex-inspired tool orchestration helpers for autonomous runs: sampling step freeze, approval cache, and deny breakers. |
|
toolschema
Package toolschema provides a lightweight, dependency-free validator for tool call inputs against a tool's declared JSON-Schema-like InputSchema.
|
Package toolschema provides a lightweight, dependency-free validator for tool call inputs against a tool's declared JSON-Schema-like InputSchema. |
|
Package schemas embeds machine-readable configuration schemas for AgentFlow.
|
Package schemas embeds machine-readable configuration schemas for AgentFlow. |