Skip to main content

Orchestrate AI agents declaratively.

Constraint-driven AI orchestration — guardrails, budgets, multi-agent patterns, memory, and observability. Any LLM, full control.

support.ts
pipeline.ts
import { createAgentOrchestrator, createPIIGuardrail } from '@directive-run/ai';
import { createOpenAIRunner } from '@directive-run/ai/openai';
const orchestrator = createAgentOrchestrator({
runner: createOpenAIRunner({ model: 'gpt-4o-mini' }),
guardrails: {
input: [createPIIGuardrail({ redact: true })],
},
constraints: {
stuck: {
when: (facts) => facts.agent.turnCount > 5,
require: { type: 'ESCALATE' },
},
},
resolvers: {
escalate: {
requirement: 'ESCALATE',
resolve: async (req, context) => {
await context.runAgent(
{ name: 'senior-support', instructions: 'Resolve escalated tickets.' },
context.facts.agent.input!,
);
},
},
},
maxTokenBudget: 10000,
});
const result = await orchestrator.run(
{ name: 'support', instructions: 'Help customers with billing questions.' },
'My card ending in 4242 was charged twice.',
);

Foundations

5 min read

AI & Agents Overview

The AI adapter brings Directive's constraint system to AI agent orchestration. Wrap any LLM framework with safety guardrails, approval workflows, token budgets, and state persistence.


Architecture

Directive doesn't replace your agent framework – it wraps it:

Agent Framework
Directive AI
Application

The AI adapter is organized into five sections:

SectionWhat's Inside
AI FoundationsEntry ramp – running agents, resilience, routing
Agent OrchestratorSingle-agent deep dive – guardrails, streaming, memory
Multi-Agent OrchestratorMulti-agent deep dive – patterns, communication, goals
AI InfrastructureIntegrations – MCP, RAG, SSE, semantic cache
AI ObservabilityDebugging – timeline, devtools, evals, OTEL, testing

Reading Paths

Quick Start Path

Build a working agent system step by step:

  1. Running Agents – End-to-end examples
  2. Agent Orchestrator – Single-agent with guardrails
  3. Multi-Agent Orchestrator – Full multi-agent setup
  4. Execution Patterns – Parallel, sequential, supervisor

Production Path

Harden for production after the basics:

  1. Resilience & Routing – Retry, fallback, budgets
  2. Guardrails – Input/output validation and PII detection
  3. Self-Healing – Automatic error recovery
  4. Evals – Quality measurement in CI
  5. OpenTelemetry – Production observability

Advanced Path

Unlock the full power of the system:

  1. Pattern Checkpoints – Save/resume, fork, progress tracking
  2. Goal Pattern – Desired-state resolution with satisfaction scoring and relaxation
  3. Communication – Decentralized agent messaging
  4. Cross-Agent State – Shared derivations and scratchpad
  5. Breakpoints & Checkpoints – Human-in-the-loop debugging
  6. DevTools – Real-time visual debugging (Timeline, Cost, State + 5 more planned)

Two Orchestrators

Both are backed by a Directive System with reactive state, constraints, guardrails, streaming, approval, memory, retry, budget, hooks, and time-travel debugging. The multi-agent orchestrator has full feature parity – each registered agent becomes a namespaced Directive module.

Single-AgentMulti-Agent
FunctioncreateAgentOrchestratorcreateMultiAgentOrchestrator
ScopeOne agent at a timeMultiple named agents with concurrency control
Stateorchestrator.facts.agentorchestrator.facts (namespaced per agent)
Streamingorchestrator.runStream()orchestrator.runAgentStream()
Patternsparallel(), sequential(), supervisor(), dag(), race(), reflect(), debate(), goal()
GuardrailsOrchestrator-levelOrchestrator-level + per-agent
ConstraintsOrchestrator-levelOrchestrator-level + per-agent
Approvalapprove() / reject()approve() / reject() (routes to correct agent)
DerivationsCross-agent derivations
ScratchpadShared scratchpad
CommunicationMessage bus, agent network, handoffs
Breakpoints4 types6 types (+ pre_handoff, pre_pattern_step)
totalTokensorchestrator.totalTokensorchestrator.totalTokens
waitForIdle()orchestrator.waitForIdle()orchestrator.waitForIdle()
Budget warningbudgetWarningThreshold + onBudgetWarningbudgetWarningThreshold + onBudgetWarning
Use whenSimple chatbot, single-purpose agentPipelines, fan-out, delegation, routing
// Single-agent
const single = createAgentOrchestrator({ runner, guardrails, maxTokenBudget: 10000 });
const result = await single.run(agent, 'Hello!');

// Multi-agent
const multi = createMultiAgentOrchestrator({
  runner,
  agents: { researcher: { agent: researcher }, writer: { agent: writer } },
  guardrails,
  maxTokenBudget: 50000,
});
const result = await multi.runAgent('researcher', 'What is WASM?');

Key Concepts

ConceptDescription
OrchestratorWraps an AgentRunner with constraints, guardrails, and state tracking
Multi-Agent OrchestratorCoordinates multiple named agents with concurrency, patterns, and per-agent configuration
pipe()Left-to-right middleware composition: pipe(runner, withRetry(...), withBudget(...))
MiddlewareComposable with* wrappers (withRetry, withFallback, withBudget)
GuardrailsInput, output, and tool-call validators that block or transform data
ConstraintsDeclarative rules (e.g., "if confidence < 0.7, escalate to expert")
MemorySliding window, token-based, or hybrid conversation management
ResilienceIntelligent retry, provider fallback chains, and cost budget guards
Circuit BreakerAutomatic fault isolation for failing agent calls
Goal PatternDesired-state goal resolution – declare produces/requires, runtime resolves
CheckpointsSave/resume mid-pattern state for fault tolerance, forking, and progress tracking
EvalsDataset-driven quality evaluation with built-in and LLM-as-judge criteria
DevToolsReal-time debugging UI with 12 specialized views

Quick Example

import { createAgentOrchestrator, createPIIGuardrail } from '@directive-run/ai';
import { createOpenAIRunner } from '@directive-run/ai/openai';

const runner = createOpenAIRunner({
  apiKey: process.env.OPENAI_API_KEY!,
});

const agent = {
  name: 'assistant',
  instructions: 'You are a helpful assistant.',
};

const orchestrator = createAgentOrchestrator({
  runner,

  // Block PII in user input
  guardrails: {
    input: [createPIIGuardrail()],
  },

  // Auto-enforce a 10K token budget
  maxTokenBudget: 10000,

  // React to agent state with declarative rules
  constraints: {
    escalateOnLowConfidence: {
      when: (facts) => facts.agent.output?.confidence < 0.7,
      require: (facts) => ({
        type: 'RUN_EXPERT_AGENT',
        query: facts.agent.input,
      }),
    },
  },
});

const result = await orchestrator.run(agent, 'Hello!');

Infrastructure

FeaturePageDescription
MCP IntegrationModel Context ProtocolConnect to MCP tool servers
RAG EnricherRetrieval-Augmented GenerationEmbedding-based document retrieval
SSE TransportServer-Sent EventsHTTP streaming endpoints
Semantic CacheResponse CachingEmbedding-based cache with ANN indexes

Observability

FeaturePageDescription
Debug TimelineEvent Recording25+ event types with time-travel correlation
Pattern CheckpointsFault ToleranceSave/resume all 8 patterns, progress tracking, forking
Breakpoints & CheckpointsPausing & StateHuman-in-the-loop debugging, persistent snapshots
DevToolsVisual Debugging12 views: Timeline, Cost, State, Guardrails, Events, Health, Flamechart, DAG, Goal, Memory, Budget, Config
EvalsQuality Measurement10 built-in criteria, LLM-as-judge, CI assertions
OpenTelemetryProduction TracingOTEL spans with GenAI semantic conventions
TestingTest UtilitiesMock runners, test orchestrators, assertion helpers

Safety & Compliance

Directive provides security guardrails and compliance tooling for AI agent systems. See Security & Compliance for full details.

User Input
Injection Detection
PII Detection
Agent Execution
Output PII Scan
Audit Trail
FeatureThreat Addressed
PII DetectionPersonal information leaking to/from agents
Prompt InjectionJailbreaks, instruction overrides
Audit TrailTamper-evident logging
GDPR/CCPARight to erasure, data export, consent

Next Steps

We care about your data. We'll never share your email.

Powered by Directive. This signup uses a Directive module with facts, derivations, constraints, and resolvers – zero useState, zero useEffect. Read how it works

Directive - Constraint-Driven State Management for TypeScript