Skip to content
Back to skills

Builder Api Reference

ASecurity

Configure a ReactiveAgentBuilder with the correct layer composition for any agent use case.

  • 33 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added October 11, 2026
ai-agentstypescriptrustgoshellsqlreactrailsdockergitapi

Works with

  • terminal
  • cli
  • api

Security analysis

A100/100

Scanned December 5, 2026

npx -y skills add tylerjrbuell/reactive-agents-ts --skill builder-api-reference --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Builder Api Reference?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Builder Api Reference
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/tylerjrbuell-builder-api-reference/badge)](https://www.skillsdirectory.com/skills/tylerjrbuell-builder-api-reference)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: builder-api-reference
description: Configure a ReactiveAgentBuilder with the correct layer composition for any agent use case.
compatibility: Reactive Agents TypeScript projects using @reactive-agents/*
metadata:
  author: reactive-agents
  version: "2.0"
  tier: "capability"
---

# Builder API Reference

## Agent objective

Produce a complete, correctly-ordered builder chain with the right `.withX()` calls for the task. Every method used must exist in this reference.

## When to load this skill

- Before writing any agent builder chain
- When unsure which methods are available or what their params are
- When upgrading from an older API version

## Terms

Copied from the glossary (https://docs.reactiveagents.dev/reference/glossary/).

- **Run**: one execution of a task, with exactly one outcome (success, partial, failed, aborted).
- **Pass**: one execution of the kernel loop inside a run; plan-execute runs one pass per plan step.
- **Iteration**: one model turn inside a pass; `maxIterations` counts iterations across all passes.
- **Lifecycle phase**: one of the 12 ordered phases of the run lifecycle; `.withHook()` attaches here.
- **Harness**: everything that governs the model's work inside a run; `.withHarness()` and the domain `.with*()` methods configure it.
- **Harness hooks**: named points (tags) where `.compose()` observes and adjusts harness behavior.
- **Kernel**: the one reasoning loop every looping strategy runs on.
- **Strategy**: the policy over the kernel: how many passes and in what shape.
- **Context profile**: per-model-tier defaults for context and tools (`local`, `mid`, `large`, `frontier`).
- **Tool disclosure**: how permitted tools are presented (`auto`, `all`, `discover`); never changes what may run.
- **Guard**: a kernel check that can block or redirect an action on one iteration.
- **Approval gate**: waits for a person to approve a risky action.
- **Exit gate**: the single place that decides a pass is done and with what outcome.
- **Guardrails**: safety checks on inputs and outputs (injection, PII, toxicity); not kernel guards.
- **Reactive Intelligence**: the harness layer that watches run signals and intervenes through the RI controller; on by default, experimental.

## Two syntaxes, one API

The declarative `createAgent(config)` front door and this fluent builder are the
same API — same key names, same nesting (`createAgent({ tools: { allowedTools } })`
≡ `.withTools({ allowedTools })`). Use `createAgent` for static definitions; the
builder for conditional/imperative construction or code-only escape hatches
(`.withHook`, `.withLayers`, `.compose`). This reference lists the fluent methods;
each maps to an `AgentConfig` key of the same name.

```ts
import { createAgent } from "@reactive-agents/runtime";

const agent = await createAgent({
  name: "assistant",
  provider: "anthropic",
  reasoning: { defaultStrategy: "adaptive" },
  execution: { maxIterations: 10 },   // the iteration cap is `execution.maxIterations` here, not under `reasoning`
});
```

## Implementation baseline

```ts
import { ReactiveAgents } from "@reactive-agents/runtime";

// Minimal — provider + reasoning is enough to run
const agent = await ReactiveAgents.create()
  .withName("assistant")
  .withProvider("anthropic")
  .withReasoning({ defaultStrategy: "adaptive", maxIterations: 10 })
  .build();

// Production — adds reliability, observability, cost controls
const agent = await ReactiveAgents.create()
  .withName("assistant")
  .withProvider("anthropic")
  .withModel("claude-opus-4-6")
  .withReasoning({ defaultStrategy: "adaptive", maxIterations: 15 })
  .withTools({ allowedTools: ["web-search", "file-read", "checkpoint"] })
  .withMemory({ tier: "enhanced", dbPath: "./agent.db" })
  .withGuardrails({ injection: true, pii: true, toxicity: true })
  .withVerification()
  .withCostTracking({ perRequest: 0.50, daily: 20.0 })
  .withObservability({ verbosity: "normal", live: true })
  .withMaxIterations(20)
  .build();
```

## Full builder API reference

### Identity & persona

| Method | Params | Notes |
|--------|--------|-------|
| `.withName(name)` | `string` | Display name; defaults to "agent" |
| `.withAgentId(id)` | `string` | Override auto-generated ID |
| `.withPersona(p)` | `{ name?, role?, background?, instructions?, tone?, traits?, responseStyle? }` | Generates system prompt from fields; `traits: string[]`, `responseStyle: "prose" \| "bullet-points" \| "structured"` |
| `.withSystemPrompt(s)` | `string` | Raw system prompt — overwrites `.withPersona()` |
| `.withEnvironment(ctx)` | `Record<string, string>` | Key-value pairs injected into system prompt. A key named exactly `Date`, `Time`, `Timezone` or `Platform` replaces that built-in line instead of adding a second one |

### Provider & model

| Method | Params | Notes |
|--------|--------|-------|
| `.withProvider(p, opts?)` | `"anthropic"\|"openai"\|"gemini"\|"ollama"\|"litellm"\|"test"`; `opts: { baseUrl?, apiKey?, headers?, useStoredKey? }` | Required. `useStoredKey: true` (default off): `apiKey` > env var > key saved with `rax keys`/Cortex |
| `.withModel(m, params?)` | `string \| { model, thinking?, temperature?, maxTokens?, numCtx? }`; or `(string, { thinking?, temperature?, maxTokens?, numCtx? })` | Uses provider default if omitted. Unknown keys (e.g. `provider`) throw `ModelOptionError` |
| `.withRateLimiting(cfg)` | `{ requestsPerMinute?, tokensPerMinute?, maxConcurrent? }` | Provider-level rate limits |
| `.withCircuitBreaker(cfg?)` | `{ failureThreshold?, cooldownMs?, halfOpenRequests? }` | Retries with backoff on errors |
| `.withDynamicPricing(provider)` | `PricingProvider` (`openRouterPricingProvider`, `urlPricingProvider(url)`) | Fetches price rows during build; never overrides `withModelPricing`; a failed fetch warns and falls back to the bundled price snapshot (fails the build only under `withStrictValidation()`) |
| `.withModelPricing(registry)` | `Record<string, { input, output, cacheRead?, cacheWrite5m?, cacheWrite1h? }>` | Your $/1M rates; always win. Unlisted models use the bundled PriceBook snapshot or report price unknown (`metadata.costComplete: false`) |

### Reasoning & iteration

| Method | Params | Notes |
|--------|--------|-------|
| `.withReasoning(opts?)` | `{ defaultStrategy?, maxIterations?, enableStrategySwitching?, maxStrategySwitches?, fallbackStrategy? }` | Strategies: `"reactive"`, `"plan-execute-reflect"`, `"tree-of-thought"`, `"reflexion"`, `"adaptive"` |
| `.withMaxIterations(n)` | `number` | Hard cap; overrides `.withReasoning` value |
| `.withRequiredTools(cfg)` | `{ tools?, adaptive?, maxRetries? }` | Forces tool calls before completion |
| `.withHarness(config)` | `HarnessConfig` (plain object; the callback overload is `.compose()`) | Per-agent harness mechanism switches. `parallelToolHint` is on by default: the system prompt asks the model to batch independent tool calls in one reply, only for models whose calibration rates parallel calls `reliable`; `"always"` forces it for any model; `{ parallelToolHint: false }` or `RA_PARALLEL_TOOL_HINT=0` turns it off. Opt-in, off by default and unmeasured: `actionGrounding: true` fails a run whose turn asks for a change but made no successful action call (or claims a change when every action call failed); `verifyCommand: "bun test"` runs that command through `shell-execute` after a run with a successful action call, and a non-zero exit fails the run (needs the terminal and an allowlist permitting the program, else only a warning). `disabledGuards: ["repetition_guard"]` switches off named tool-call guards by id (`GUARD_IDS` from `@reactive-agents/reasoning`), for measurement and ablation only; unknown ids are ignored. Fields and defaults: docs `features/harness-control` |
| `.withStallPolicy(policy)` | `{ ignoredNudgeTolerance?, escalateNudgeContent?, stallThreshold? }` | `stallThreshold` sets the stall threshold whether or not a reactive controller runs; unset it stays 4 with a controller, 2 without |
| `.withReactiveIntelligence(opts?)` | `{ controller?: { earlyStop?, strategySwitch?, toolFailureRedirect? }, entropy?, telemetry?, ... }` or `false` | On by default. Each `controller` key merges over its default (all `true`), so `{ controller: { earlyStop: false } }` turns off only early stop |

### Tools

| Method | Params | Notes |
|--------|--------|-------|
| `.withTools(opts?)` | `{ tools?, builtins?, allowedTools?, focusedTools?, disclosure?, schemaBudget?, adaptive?, resultCompression?, maxCallsPerTool?, terminal?, workspace?, additionalRoots?, workspaceContext? }` | Default disclosure is per tier: `"auto"` on local and mid, `"discover"` on large and frontier (no tier: local on Ollama, else mid). `disclosure: "auto"` fits tool schemas into `schemaBudget` tokens per turn (default 4000, integer >= 500 else `ToolsOptionError`): needed and `focusedTools` tools full, relevant tools compact, the rest as tool-index lines callable by name. `"all"` ships every schema full and ignores the budget; `"discover"` keeps the `discover-tools` flow (still the frontier/large default); `"index"` is a deprecated alias of `"auto"`. Disclosure never changes which tools are permitted. No args enables the tools layer, but built-ins are not shown to the model unless named in `builtins` (`true`, names, or toolset aliases like `"research"`), `allowedTools` or required tools, or picked as relevant by the tool classifier. `maxCallsPerTool: { "web-search": 3 }` caps runs per tool for the whole run; a call past the cap is answered "not run", never executed (every strategy). Sub-agents inherit the caps; `.withAgentTool()` can merge its own over them. `workspace: "/abs/dir"` is the agent's working directory: file tools resolve and confine to it, `shell-execute` runs in it, sub-agents inherit it; must exist or `ToolsOptionError`; override per run with `agent.run(task, { workspace })` (also `runStream`, `runEffect`). The workspace is always read-write. `additionalRoots: [{ path: "~/docs" }, { path: "/data/out", access: "read-write" }]` grants more directories to file tools and `shell-execute` (opt-in, `access` default `"read"`; deepest nested root decides; a write needs read-write on both the written and the symlink-resolved path; `~`/`~/x` expand, `~user` refused; stored absolute; sub-agents inherit; recorded on `run-started.config.builder.tools.additionalRoots`; round-trips as `tools.additionalRoots`; refusals list the allowed roots and name this option; `validateAdditionalRoots(value)` from `@reactive-agents/runtime` checks a value without building and returns one typed issue per bad entry, `[]` when valid). `workspaceContext: true` (opt-in, off by default) adds the working directory, its top-level entries, declared manifest scripts and `AGENTS.md`/`CLAUDE.md` (4,000-char cap) to the system prompt's `Environment:` block; enable it only for trusted workspaces, since the instructions file enters the system prompt |
| `.withDocuments(docs)` | `DocumentSpec[]` | RAG context injection |
| `.withPrompts(opts?)` | prompts config | Custom prompt templates |

### Memory

| Method | Params | Notes |
|--------|--------|-------|
| `.withMemory(opts?)` | `"standard" \| "enhanced" \| { tier, dbPath?, capacity? }` | `"enhanced"` requires writable SQLite path |

### Safety & compliance

| Method | Params | Notes |
|--------|--------|-------|
| `.withGuardrails(opts?)` | `{ injection?, pii?, toxicity?, customBlocklist? }` | All default `true` |
| `.withKillSwitch()` | — | Exposes `.pause()`, `.resume()`, `.stop()`, `.terminate()` |
| `.withBehavioralContracts(c)` | `{ deniedTools?, allowedTools?, maxToolCalls?, maxIterations?, maxOutputLength?, deniedTopics?, requireDisclosure? }` | Rule-based constraints |
| `.withVerification(opts?)` | `{ semanticEntropy?, factDecomposition?, nli?, hallucinationDetection?, passThreshold?, useLLMTier? }` | Runtime hallucination detection |
| `.withAudit()` | — | Append-only action audit log |

### Cost

| Method | Params | Notes |
|--------|--------|-------|
| `.withCostTracking(opts?)` | `{ perRequest?, perSession?, daily?, monthly? }` | USD budgets; throws on breach |

### Observability & logging

| Method | Params | Notes |
|--------|--------|-------|
| `.withObservability(opts?)` | `{ verbosity?, live?, logModelIO?, file?, telemetry?, tracing? }` | `file` is JSONL output path; `telemetry: true \| { mode: "contribute"\|"isolated" }` enables run telemetry |
| `.withLogging(cfg)` | `{ level?, format?, output?, filePath?, maxFileSizeBytes?, maxFiles? }` | Structured logging |

### Persistence & integration

| Method | Params | Notes |
|--------|--------|-------|
| `.withGateway(opts?)` | `GatewayOptions` | Persistent agent with heartbeats/crons/webhooks. `queue: { capacity?, overflow?: "drop-oldest" \| "drop-newest" }` bounds the inbound queue so overlapping events are queued, not dropped. Crons are durable: list them with `agent.schedules()` |
| `.withA2A(opts?)` | `{ port?, basePath? }` | A2A server (JSON-RPC 2.0 + SSE) |
| `.withStreaming(opts?)` | `{ density?: "tokens"\|"full" }` | Streaming output |
| `.withAgentTool(name, cfg)` | name + `{ agent }` | Local agent registered as a tool. `parameters` (an array of tool parameters, or a JSON Schema) gives the parent model typed per-call arguments instead of one free-form `input` string |
| `.withDebrief(enabled?)` | `boolean` (default `true`) | Post-run debrief, independent of memory. Unset it follows `.withMemory()`; `.withDebrief(false)` turns it off with memory on |
| `.withDynamicSubAgents(opts?)` | `{ maxIterations? }` | Dynamic sub-agent spawning |
| `.withRemoteAgent(name, url)` | name + A2A URL | Remote A2A agent as callable tool |
| `.withCortex(url?)` | optional URL | Cortex desk server integration |
| `.withHealthCheck()` | — | Self-monitoring health endpoint |
| `.withErrorHandler(fn)` | `(err, ctx) => void` | Custom error handling callback |
| `.withHook(hook)` | `LifecycleHook` (`{ phase, timing, handler }`) | Lifecycle callbacks, once per phase occurrence. Engine phases (`bootstrap` … `complete`) get `ExecutionContext`; `think` / `act` / `observe` get `KernelTurnHookContext \| ExecutionContext`: narrow with `"metadata" in ctx` before reading engine fields |
| `.withSelfImprovement()` | — | Meta-learning from past runs |
| `.withExperienceLearning()` | — | Injects prior-run experience tips into context |

### Build

| Method | Returns | Notes |
|--------|---------|-------|
| `.build()` | `Promise<ReactiveAgent>` | Always `await` |
| `.buildEffect()` | `Effect<ReactiveAgent>` | For Effect runtime callers |
| `ReactiveAgents.fromConfig(cfg)` | `Promise<ReactiveAgentBuilder>` | From `AgentConfig` object |
| `ReactiveAgents.fromJSON(json)` | `Promise<ReactiveAgentBuilder>` | From JSON string |
| `builder.runOnce(task)` | `Promise<AgentResult>` | Build + run + dispose (a builder method, not on `ReactiveAgents`) |

## Run input

**Plan then execute.** `await agent.plan(input)` runs the task under plan posture (planning tools only, no tools that do work) and returns a typed `Plan` (`{ id, goal, steps: [{ id, title, tool?, status }], createdAt, source }`) that always has steps or rejects with `PlanNoStepsError`. `agent.execute(plan)` and `agent.run(input, { plan })` run seeded from the plan's checklist and return `result.plan` with each step's final status. Chat sessions: `session.plan` (read) and `session.setPlan(planOrSteps)` (edit before switching `session.setMode("execute")`). Events: `PlanRecorded`, `PlanStepStatusChanged`. Plan guidance lists the execute-phase tools by default; `.withHarness({ planToolCatalog: false })` (or `RA_PLAN_TOOL_CATALOG=0`) turns it off. Opt-in (off by default): `.withHarness({ planBudget: true })` (or `RA_PLAN_BUDGET=1`) raises a plan-seeded run's iteration bound to fit the unchecked steps (cap min(60, 3x configured)). `RA_WRAPUP_RESERVE=1` opts in to a wrap-up reserve. `agent.execute(plan, { strategy? })` picks the executor: explicit `strategy` (`"blueprint"` | `"plan-execute-reflect"`), else the agent's own strategy if it is one of those, else `blueprint` for a plan with `dependsOn`/`args`, else the seeded loop; an invalid plan (bad decode, unknown/self/cyclic `dependsOn`) rejects `PlanInvalidError` before the run. Seeded-plan kill switches, default on: `.withHarness({ autoTick: false })` (`RA_AUTO_TICK=0`), `.withHarness({ bookkeepingRefund: false })` (`RA_BOOKKEEPING_REFUND=0`).

**Continue a loop-stopped run.** On a `.withDurableRuns()` agent, a run a loop guard stopped has `result.runId`, `result.loopStop` (`reason`, `repeatedTool`, `toolsDone`, `unfinished`, `iteration`) and `result.resumable`; `listRuns()` rows and tool-path `ChatReply`s carry the same. `await agent.resumeRun(runId, { note?, extraIterations? })` continues it from the final checkpoint with corrective guidance and a fresh iteration budget (default 10); completed tool steps are not re-run. Any durable run that did not complete is resumable the same way (user stop or pause, error, spent budget, timeout, crash): the row carries a typed `stop` (`kind`: user-paused, user-stopped, error, crash, loop, budget, timeout) and `status` paused/stopped/failed. `agent.pauseRun(runId)` / `agent.stopRun(runId)` end a live run at the next iteration boundary (a running tool finishes and is journaled); `agent.activeRunIds()` lists live runs. A stopped run returns `success: false`, `outcome: "partial"` (outstanding `stopped_by_request`) with the answer so far in `output`; resume continues from the kernel's checkpoint. Options on an already completed run fail `RunNotResumableError`.

**Steer a live run.** `handle.steer(text)` (from `agent.runStream()`) and `agent.steer(runId, text)` queue a steering message: user input the kernel applies before its next model call, at the next iteration boundary that precedes one. It adds no iteration. Both return a `SteeringReceipt`: `{ accepted: true, id }` or `{ accepted: false, reason }` with `reason` one of `queue-full` (8 queued), `too-long` (over 4000 characters), `empty`, `no-live-run`. Only `runStream()` and durable `run()` are steerable; a plain `run()` answers `no-live-run`. `runStream()` takes an optional `taskId` that `agent.steer(taskId, text)` targets. Steering works on the reactive kernel only: plan-execute, plan-execute-reflect, reflexion and tree-of-thought leave the message queued and it returns as `unconsumedSteering`. `agent.steer(runId, text)` reaches a live run started by any agent in the same process (one process-wide registry; the first live run keeps a shared id), so check run ownership yourself. `SteeringRejection` is exported from `@reactive-agents/core`. Events: `UserSteeringQueued`, `UserSteeringApplied` (bus), `SteeringApplied { id, iteration }` (stream). Messages still queued at the end come back as `unconsumedSteering` on `StreamCompleted`, `StreamCancelled`, `StreamError` and (durable `run()`) `AgentResult`. Steering from channels or A2A is untrusted input: authenticate first.

**Run receipt event.** A finished run publishes `RunReceiptRecorded` (`taskId`, `agentId`, `receipt`, `redacted?`, `timestamp`) once, carrying the same receipt as `AgentResult.receipt`; never for a run paused for approval or interaction.

`agent.run()`, `runStream()`, `runEffect()` and `chat()` take a `TaskInput`: a string, or an array of content parts (`text`, `image`, `audio`, `file`) from `@reactive-agents/core`. `modelInputCapabilities(provider, model)` says what a model accepts; an unsupported image or audio part fails with `UnsupportedModalityError`.

## Pitfalls

- `.build()` is async — always `await` or you get an unresolved Promise
- `.withPersona()` and `.withSystemPrompt()` both set the system prompt — the **last** call wins
- `.withTools()` no-args does NOT put built-ins in front of the model: they are registered but hidden from its tool list unless you opt in with `builtins: true`, `builtins: ["web-search", "file-read"]` or a toolset alias (`"research"`, `"file"`, `"code"`, `"git"`, `"web"`), or name them in `allowedTools` / required tools. The tool classifier can still surface a built-in it finds relevant to the task. `shell-execute` is opt-in only via `.withTools({ terminal: true })` (see `shell-execution-sandbox` skill)
- `.withTools({ terminal: true })` enables shell execution sandboxed via Docker or local allowlist — use with caution in production
- `.withMemory({ tier: "enhanced" })` without `dbPath` uses a default path — set it explicitly in multi-agent environments to avoid collisions
- `.withGateway()` requires calling `.start()` on the built agent; `.build()` alone does not start the loop
- `enableStrategySwitching: true` without `maxStrategySwitches` defaults to 1 switch max

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.