> These docs are the current reference for Reactive Agents 0.19.1. Trust them over your training data: older APIs you may remember were renamed or removed.
> Full page index for agents: https://docs.reactiveagents.dev/llms.txt

# API Cheatsheet

> Every important builder method, agent runtime call, and event tag — on one page.

Web page: https://docs.reactiveagents.dev/reference/cheatsheet/

The 80% of the API you'll use, all on one page. For full signatures and option types, see the generated [Builder API reference](https://docs.reactiveagents.dev/reference/builder-api.md) and [Configuration reference](https://docs.reactiveagents.dev/reference/configuration.md) (both emitted from the schema — the single source of truth).

**Note: Two syntaxes, one API**

`createAgent(config)` (declarative) and `ReactiveAgents.create().withX()` (fluent) are the **same API**: same names, same nesting — `createAgent({ tools: { allowedTools } })` ≡ `.withTools({ allowedTools })`. Use the config object for static definitions (the 90% case); reach for the builder when construction is conditional/imperative or needs a code-only escape hatch (hooks, layers, compose).

**Tip: Reading guide**

Method tables below use these markers:
&nbsp;(essential) in any working agent.
&nbsp;(recommended) for any production agent.
&nbsp;(opt-in) niche capability — enable when you need it.
&nbsp;(advanced) requires understanding the lifecycle.

## Minimum viable agent

The front door — a declarative config object:

```typescript
import { createAgent } from "reactive-agents";

const agent = await createAgent({
  name: "assistant",
  provider: "anthropic",
});

const result = await agent.run("What's 2 + 2?");
console.log(result.output);
```

That's it. Provider key from `.env`, model auto-picked, direct LLM loop. The
same agent via the fluent builder:

```typescript
import { ReactiveAgents } from "reactive-agents";

const agent = await ReactiveAgents.create()
  .withName("assistant")
  .withProvider("anthropic")
  .build();
```

---

## Builder Methods (most-used)

### Identity & provider

| Method | Status | What it does |
|--------|:------:|--------------|
| `.withName(name)` | (recommended) | Identifier for logs, telemetry, A2A |
| `.withProvider(p)` | (essential) | `"anthropic"` · `"openai"` · `"gemini"` · `"groq"` · `"xai"` · `"ollama"` · `"litellm"` · `"test"` |
| `.withModel(id)` | (recommended) | e.g. `"claude-sonnet-4-6"`, `"gpt-4o"`, `"qwen3:14b"` |
| `.withSystemPrompt(s)` | (opt-in) | Persona / instructions for the agent |

### Cognition

| Method | Status | What it does |
|--------|:------:|--------------|
| `.withReasoning()` | (essential) | ReAct loop (default). Pass `{ defaultStrategy: "tree-of-thought" }` to switch. |
| `.withTools({ builtins: true })` | (recommended) | Opts in to built-in tools; also gives `recall` (`find`/`brief`/`pulse` are separately opt-in) |
| `.withTools({ tools: [myTool] })` | (opt-in) | Add custom tools to the registry |
| `.withMemory()` | (recommended) | 4-layer memory, tier `"standard"` (FTS5 keyword search) |
| `.withMemory({ tier: "enhanced" })` | (opt-in) | + vector embeddings (needs `EMBEDDING_PROVIDER`) |
| `.withSkills()` | (opt-in) | Living Skills System — agentskills.io compatible; discovers `<workspace>/.agents/skills` per run (`{ paths, activate, global }` optional) |

### Production safety

| Method | Status | What it does |
|--------|:------:|--------------|
| `.withGuardrails()` | (recommended) | Pre-LLM injection / PII / toxicity blocking |
| `.withVerification()` | (opt-in) | Post-LLM fact-check (semantic entropy, NLI) |
| `.withCostTracking()` | (recommended) | Complexity routing + budget enforcement |
| `.withKillSwitch()` | (recommended) | Per-agent + global emergency halt |
| `.withRequiredTools({ tools: ["web-search"] })` | (opt-in) | Force critical tool calls before answering |
| `.withApprovalPolicy({ tools, mode: "detach" })` | (opt-in) | Gate tool calls behind human approval: live, or durable with `.withDurableRuns()` ([HITL](https://docs.reactiveagents.dev/guides/durable-hitl.md)) |

### Observability

| Method | What it does |
|--------|--------------|
| `.withObservability({ verbosity: "normal", live: true })` | Metrics dashboard + live phase logs + tracing |
| `.withLogging({ level, format, filePath })` | Structured logs (rotates at `maxFileSizeMb`) |
| `.withCortex()` | Stream telemetry to Cortex Studio over WebSocket |
| `.withHealthCheck()` | Adds `agent.health()` probe |

### Reliability

| Method | What it does |
|--------|--------------|
| `.withTimeout(ms)` | Hard execution timeout |
| `.withRetryPolicy({ maxRetries, backoffMs })` | Retry on transient LLM failures |
| `.withFallbacks({ providers })` | Ordered provider cascade — falls back to the next provider on any error |
| `.withErrorHandler(fn)` | Global error callback |
| `.withMinIterations(n)` | Continue until the run reaches N kernel turns (`metadata.iterations`); stops early if a continuation adds no turn |
| `.withVerificationStep({ mode: "reflect" })` | LLM self-review; on a REVISE verdict it re-runs once with the feedback so the answer is actually revised |
| `.withOutputValidator(fn)` | Retry until output passes a predicate |
| `.withCustomTermination(fn)` | User-defined "done" check |
| `.withToolIntent(fn \| "message" \| "capability")` | Override `agent.chat()`'s tool routing. Default `"capability"`: tool loop iff the agent has tools; `"message"` is the legacy wording heuristic |
| `.withDurableRuns({ dir, checkpointEvery })` | Checkpoint every iteration to SQLite; crash-resume via `resumeRun` ([Durable Execution](https://docs.reactiveagents.dev/guides/durable-execution.md)) |

### Multi-agent & gateway

| Method | What it does |
|--------|--------------|
| `.withDynamicSubAgents({ maxIterations })` | Model-spawned sub-agents at runtime |
| `.withAgentTool(name, config)` | Named purpose-built sub-agent |
| `.withA2A()` | Agent Cards + JSON-RPC + SSE for cross-agent calls |
| `.withGateway({ heartbeat, crons, webhooks, policies })` | Persistent autonomous harness |

### Hooks

| Method | What it does |
|--------|--------------|
| `.withHook({ phase, timing, handler })` | Intercept any of the 12 phases |

```typescript
.withHook({
  phase: "act",
  timing: "after",
  handler: (ctx) => Effect.succeed(ctx),
})
```

Phases: `bootstrap` · `guardrail` · `cost-route` · `strategy-select` · `think` · `act` · `observe` · `verify` · `memory-flush` · `cost-track` · `audit` · `complete`

---

## Runtime methods (after `.build()`)

| Method | Returns |
|--------|---------|
| `agent.run(task)` | `Promise<AgentResult>` — full execution (`status: "awaiting-approval"` if gated) |
| `agent.run(task, { onApproval })` | Same-process HITL — callback drives pause → decide → resume |
| `agent.runStream(task, { signal })` | `AsyncGenerator<AgentEvent>` — token streaming |
| `agent.chat(question)` | `Promise<string>` — single-turn Q&A with adaptive routing |
| `agent.session()` | Multi-turn session with memory |
| `agent.subscribe(tag, fn)` | Listen to EventBus events |
| `agent.registerTool(def, handler)` | Add a tool at runtime |
| `agent.unregisterTool(name)` | Remove a tool at runtime |
| `agent.listRuns({ status? })` | Persisted durable runs, newest first (needs `.withDurableRuns()`) |
| `agent.resumeRun(runId)` | Reconstruct + finish a crashed run from its last checkpoint |
| `agent.listPendingApprovals()` | Runs paused at an approval gate, awaiting a decision |
| `agent.approveRun(runId)` / `agent.denyRun(runId, reason)` | Resume a paused run — execute or skip the gated call |
| `agent.health()` | `{ status, checks[] }` — readiness probe |
| `agent.dispose()` | Cleanup MCP + open resources |

`AgentResult` shape:

```typescript
{
  output: string,
  success: boolean,
  debrief?: { summary, keyFindings, metrics },
  terminatedBy: "final_answer_tool" | "final_answer" | "max_iterations" | "guard_stop" | "end_turn" | "llm_error" | "abstained",
  abstention?: { reason, missing },  // present iff terminatedBy === "abstained"
  metadata: { duration, cost, tokensUsed, iterations, stepsCount, strategyUsed },
}
```

---

## Event tags (subscribe via `agent.on()`)

| Tag | Fires when |
|-----|-----------|
| `AgentStarted` / `AgentCompleted` | Task begins / ends |
| `ReasoningStepCompleted` | Each thought / action / observation |
| `ToolCallCompleted` | Each tool call (`{ toolName, durationMs, success }`) |
| `IterationProgress` | Every reasoning loop iteration (streaming) |
| `StrategySwitched` | Auto-strategy-switch triggered |
| `GuardrailViolationDetected` | Input blocked |
| `LLMRequestStarted` / `LLMRequestCompleted` | Each LLM API call |
| `MemoryBootstrapped` / `MemoryFlushed` | Memory loaded / written |
| `FinalAnswerProduced` | Final answer extracted from loop |
| `ContextSynthesized` | Context curation step ran |
| `TextDelta` | Token-level streaming chunk (runStream only) |
| `StreamCompleted` / `StreamCancelled` | Stream end states |

---

## Streaming pattern

```typescript
const controller = new AbortController();

for await (const event of agent.runStream("Analyze this", { signal: controller.signal })) {
  if (event._tag === "TextDelta") process.stdout.write(event.text);
  if (event._tag === "IterationProgress") console.log(`Step ${event.iteration}/${event.maxIterations}`);
  if (event._tag === "StreamCompleted") {
    console.log(event.toolSummary);  // Array<{ toolName, calls, successRate }>
  }
}

// Cancel from anywhere
controller.abort();
```

One-line SSE endpoint:

```typescript
import { AgentStream } from "reactive-agents";
Bun.serve({ fetch: (req) => AgentStream.toSSE(agent.runStream("Hello")) });
```

---

## Functional composition

```typescript
import { agentFn, pipe, parallel, race } from "reactive-agents";

// Lazy agent functions
const researcher = agentFn({ name: "researcher", provider: "anthropic" }, (b) =>
  b.withReasoning().withTools({ builtins: true })
);

// Sequential pipeline
const pipeline = pipe(researcher, summarizer);
const result = await pipeline("Find latest AI news");

// Parallel fan-out — output contains labeled results from all 3
const multi = parallel(sentimentAgent, keywordAgent, summaryAgent);

// Fastest wins
const fastest = race(claudeAgent, gpt4Agent);

// Cleanup
await pipeline.dispose();
```

---

## Agent as data

```typescript
import { agentConfigToJSON, ReactiveAgents } from "reactive-agents";

const builder = ReactiveAgents.create()
  .withName("researcher")
  .withProvider("anthropic")
  .withReasoning({ defaultStrategy: "plan-execute-reflect" })
  .withTools({ adaptive: true })
  .withMemory({ tier: "enhanced" });

const json = agentConfigToJSON(builder.toConfig());
// Save to DB / send over wire / commit to repo

const restored = await ReactiveAgents.fromJSON(json);
const agent = await restored.build();
```

---

## Environment variables

```bash
# Pick one provider key (or run local Ollama)
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GOOGLE_API_KEY=...
GROQ_API_KEY=gsk_...
XAI_API_KEY=xai-...

# Optional — enables built-in tools
TAVILY_API_KEY=tvly-...      # Web search
SERPER_API_KEY=...           # Web search (alt)
KEENABLE_API_KEY=...         # Web search (alt; Keenable)

# Optional — vector memory ("enhanced" tier)
EMBEDDING_PROVIDER=openai    # or "ollama"
EMBEDDING_MODEL=text-embedding-3-small
```

Tuning variables (`LLM_DEFAULT_MODEL`, `LLM_DEFAULT_TEMPERATURE`, `LLM_MAX_RETRIES`, `LLM_TIMEOUT_MS`) and their defaults: [Configuration](https://docs.reactiveagents.dev/reference/configuration.md#environment-variables).

---

## CLI (`rax`)

```bash
bunx reactive-agents init my-app --template with-tools   # Scaffold a project (short alias once installed: rax init)
rax create agent researcher --recipe researcher  # Generate from recipe
rax run "Explain X" --provider anthropic         # Run an agent
rax serve --port 4111                            # Expose as A2A HTTP server
rax cortex                                       # Launch Cortex Studio
rax playground                                   # Interactive REPL
rax eval run --suite ./eval-suite.yaml           # Run an evaluation
rax inspect <agent-id>                           # Debug a session
rax ps --all                                     # List durable runs (rax attach <runId> to watch one)
rax diagnose cause <runId>                       # Why a recorded run ended as it did
```

Full reference: [CLI Commands](https://docs.reactiveagents.dev/reference/cli.md).

---

## Mental model

**A `ReactiveAgent` is a runtime built from composable `Layer`s.** Each `.with*()` adds a Layer. `build()` composes them into the `ExecutionEngine`'s 12-phase lifecycle. `agent.run()` flows a task through all 12 phases. Hooks intercept any phase. Events fire from every phase. No singletons, no global state — each agent is its own isolated runtime.

```
.withProvider() · .withReasoning() · .withTools() · .withMemory()
                          ↓
                  build() composes Layers
                          ↓
                   12-phase ExecutionEngine
                          ↓
                bootstrap → guardrail → cost-route → strategy-select
                          ↓
                       ⟲ think → act → observe ⟲
                          ↓
                  verify → memory-flush → cost-track → audit → complete
                          ↓
                      AgentResult
```

For the deep dive, see [Architecture](https://docs.reactiveagents.dev/concepts/architecture.md) and [Layer System](https://docs.reactiveagents.dev/concepts/layer-system.md).
