Agent Accelerator 1.0

Agent Accelerator v1.0.0 is out.

When we first published v0.1.0, the SDK gave you one Agent class over multiple LLM providers with tool calling, streaming, and prompt caching. Since then, the codebase has been rebuilt around the things that actually fail once an agent runs outside a quick script: mid-turn crashes, duplicate tool execution, runaway loops, silent provider errors, untracked sub-agent spend, and configuration drifting between .env and application code.

Version 1.0.0 keeps the core small. It targets Bun, ships TypeScript source with no build step, uses native fetch with zero vendor SDKs, and requires only zod as a peer dependency. This post walks through what ships in 1.0 and how to use each part in code.


Install and quick start

bun add agent-accelerator zod

Put only provider API keys in .env (Bun loads it automatically):

GEMINI_API_KEY=...
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
OPENROUTER_API_KEY=...

Every other option lives in TypeScript code, never in environment variables. Here is a minimal agent run:

import { Agent } from "agent-accelerator";

const agent = new Agent({
  model: "google/gemini-4-hydrogen",
  instructions: "You are a concise engineering assistant.",
  maxTurns: 10,
});

const res = await agent.run("Explain what a mutex is in three bullet points.");
console.log(res.text);
console.log(res.usage);        // input, output, cached, thinking tokens + cost
console.log(res.finishReason); // "stop" when finished normally

Keeping instructions static across turns while passing changing per-turn state in additionalContext keeps the prompt prefix stable for provider caching:

import { Agent } from "agent-accelerator";

const agent = new Agent({
  model: "google/gemini-4-hydrogen",
  instructions: "Answer concisely using the provided context.",
});

const res = await agent.run("Summarize the status.", {
  additionalContext: "Region: eu-west-1, mode: read-only",
});
console.log(res.text);

Native providers and model routing

Models use a provider/model string. Changing providers means changing that string, with no adapter boilerplate in your code:

import { Agent, ModelProvider, setConfigs } from "agent-accelerator";

const googleAgent = new Agent({ model: "google/gemini-4-hydrogen" });
const openaiAgent = new Agent({ model: "openai/gpt-6.2-sol" });
const anthropicAgent = new Agent({ model: "anthropic/claude-sonnet-5-5" });
const openrouterAgent = new Agent({ model: "openrouter/z-ai/glm-5.3-flash" });

// Any custom prefix uses OpenAI-compatible Chat Completions after you register its base URL:
setConfigs({ values: { base_urls: { groq: "https://api.groq.com/openai/v1" } } });
const groqAgent = new Agent({ model: "groq/llama-3.3-70b-versatile" });

// Or pin provider, key, and options per agent explicitly:
const pinned = new Agent({
  model: ModelProvider.OpenAICompatible("groq/llama-3.3-70b-versatile", process.env.GROQ_API_KEY, {
    baseUrl: "https://api.groq.com/openai/v1",
  }),
});

Underneath the shared Agent interface, each first-class provider speaks its own native REST wire protocol:

Provider Wire API Adapter behavior
google Interactions API Chains turns server-side (previous_interaction_id, 23h free / 54d paid), replays raw steps and thought signatures verbatim, and automatically runs Gemini 4 calls over 65,536 maxOutputTokens in background mode
openai Responses API Sends stateless turns (store: false), preserves encrypted reasoning items across tool loops, and forwards prompt_cache_key and service_tier
anthropic Messages API Uses output_config.effort for adaptive thinking, preserves signed thinking blocks across tool loops, and sets cache_control (implicit, 5m, 1h)
openrouter Chat Completions Streams every request so cancellation closes the connection, keeps reasoning_details and PDF annotations across turns, and preserves provider-reported cost

A few strict rules apply across all adapters:

  • No silent option mismatches: an unsupported option (such as cache: "1h" on Google or toolChoice: "validated" on non-Google providers) is dropped and emits a provider_warning event on telemetryBus.
  • No fake HTTP 200 successes: empty JSON objects, inline reply errors, or streams cut off mid-tool-call fail as retryable ProviderError / incomplete_stream errors instead of returning blank text.
  • No temperature, topP, seed, or stop: these options were removed so the API does not expose controls that modern reasoning models ignore or reject.

Model limits, modalities, thinking levels, and pricing are synced lazily from models.dev into <home>/catalog/ (12-hour TTL, stale-while-revalidate, or disabled via catalog_refresh: "off"). You can inspect or register private models in code:

import {
  createGenericModelSpec,
  getModelFromCatalog,
  registerModel,
  resolveModel,
} from "agent-accelerator";

const resolved = resolveModel("google/gemini-4-hydrogen");
const spec = getModelFromCatalog(resolved.provider.id, resolved.modelId);
console.log(spec?.contextWindow, spec?.maxOutputTokens);

registerModel({
  ...createGenericModelSpec("openai", "ft:gpt-5.5:internal"),
  contextWindow: 128_000,
  pricing: { inputPerMillion: 3, outputPerMillion: 12 },
});

Tools with validation, concurrency, and replay safety

Tools are plain TypeScript functions paired with a zod schema (or raw JSON Schema via parameters) and execution policies:

import { Agent, tool } from "agent-accelerator";
import { z } from "zod";

const computeHash = tool({
  description: "Compute a SHA-256 hex digest for an input string.",
  input: z.object({ text: z.string().describe("Plain text to hash") }),
  idempotent: true,
  timeoutMs: 5_000,
  maxConcurrency: 4,
  execute: async ({ text }, ctx) => {
    ctx.log("hashing input", { length: text.length });
    const buf = new TextEncoder().encode(text);
    const digest = await crypto.subtle.digest("SHA-256", buf);
    return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
  },
});

const agent = new Agent({
  model: "google/gemini-4-hydrogen",
  tools: { computeHash },
});

const res = await agent.run("Hash the string 'agent-accelerator'.");
console.log(res.toolResults[0]?.durationMs, res.text);

When a model invokes a tool, the executor enforces:

  • Strict schema checks: malformed arguments never reach execute; the validation error and expected parameters go back to the model so it can correct the call. Truncated streamed tool calls never execute.
  • Bounded concurrency: up to 8 tool calls run concurrently per batch, and maxConcurrency on a tool is enforced process-wide across agents and worker copies until execute settles.
  • Repeat guard: the 3rd identical consecutive tool call is blocked (repeat_blocked) unless idempotent: true or repeatable: true is set.
  • Output sanitization: results are serialized safely (maxResultChars default 20,000), and errors returned to the model strip stack traces and absolute file paths. With persist: { dir }, each call also writes a full local log under tool-logs/ via ctx.log(...) that stays out of model context.
  • Multimodal tool results and clean stops: return toolContent([...]) to pass images or files back to multimodal models, or call ctx.stop(reason) inside execute to end the run cleanly after the current parallel batch with finishReason: "stopped".

Durable sessions and crash recovery

Enable persist: { dir } to keep a folder per conversation (<dir>/<sessionId>/) with a snapshot (session.json), an append-only journal.ndjson flushed line-by-line after every step, and a media/ folder for binary inputs:

import { Agent } from "agent-accelerator";

const agent = new Agent({
  model: "google/gemini-4-hydrogen",
  persist: { dir: "sessions" },
  sessionId: "worker-job-1",
  tools: { computeHash },
});

const res = await agent.run("Run the hash tool on 'hello'.");
console.log(res.text);

Every file replacement writes to a 0600 temp file, fsyncs file and directory, keeps the previous good snapshot as .bak, and swaps atomically. Corrupt files are quarantined as *.corrupt-<timestamp> rather than deleted.

Resuming after a crash

When a new Agent opens the same persist: { dir } and sessionId, it loads the saved history, spending totals, and worker traces automatically. By default (resume: "automatic"), any run interrupted mid-flight continues immediately. Use resume: "explicit" to inspect pending state before resuming:

import { Agent } from "agent-accelerator";

const agent = new Agent({
  model: "google/gemini-4-hydrogen",
  persist: { dir: "sessions" },
  sessionId: "worker-job-1",
  resume: "explicit",
});

for (const item of agent.interrupted()) {
  console.log(item.waiting ? "waiting prompt:" : "cut-off run:", item.prompt, item.pendingToolCalls);
}

await agent.resume();

Tool replay after a crash follows two rules:

  1. Calls that already finished before the crash are never re-run; their saved result is returned to the model.
  2. Calls cut off mid-execution only re-run if the tool sets idempotent: true or replay: "safe". Any other tool receives an interrupted error result so the model sees that it may have partially executed.

To deduplicate repeated invocations while a process is running, pass requestId (remembers the last 1,000 successful/completed IDs in memory):

await agent.run("Process batch #42", { requestId: "batch-42" });

Folder locks and cleanup

Each active persisted session folder holds a .lock file whose mtime heartbeat refreshes every 10 seconds. A second process opening the same sessionId fails immediately with ConfigError; any lock silent for over 120 seconds (hung process, killed process, or moved directory) is taken over automatically. Call agent.close() when finished with an agent to flush pending saves, close active workers, and release the lock right away.


Streaming, steering, and hooks

Streaming and mid-session steering

Use agent.stream() for async iteration or agent.run(prompt, { stream: true, ... }) for callbacks:

import { Agent } from "agent-accelerator";

const agent = new Agent({
  model: "google/gemini-4-hydrogen",
  midSession: { whenBusy: "auto", maxQueued: 20 },
});

const stream = agent.stream("List five sorting algorithms.");
for await (const event of stream) {
  if (event.type === "text_delta") process.stdout.write(event.delta ?? "");
}
const final = await stream.result();
console.log(`\nTurns: ${final.turns}`);

While a run is active, you can send follow-up input without waiting:

  • agent.steer(prompt) injects a message at the next turn or tool boundary inside the active run. Calling agent.stream(prompt, { enqueue: "steer" }) returns a stream scoped to that steer starting at steer_injected.
  • agent.queue(prompt) runs after the active run finishes.
  • agent.interrupt(message?) aborts the active HTTP request and tool AbortSignals immediately, optionally starting message ahead of queued prompts.

With persist: { dir }, waiting steers and queued prompts are saved in the journal and survive restarts in order.

Hooks and context compaction

hooks lets your code intercept beforeTool, afterTool, beforeRequest, and onYield. beforeTool fails closed (if it throws, the call is blocked) and workers inherit parent hooks automatically.

Saved sessions have no default message or byte limit (persist.loadLimits is opt-in). Instead, beforeRequest exposes ctx.inputTokens and ctx.contextWindow so you can implement your own compaction policy and persist it via { history }:

import { Agent, type Message } from "agent-accelerator";

const summarize = async (older: Message[]): Promise<Message> => ({
  role: "user",
  content: `Summary of ${older.length} earlier messages.`,
});

const agent = new Agent({
  model: "google/gemini-4-hydrogen",
  persist: { dir: "sessions" },
  hooks: {
    beforeTool: async (call) => {
      if (call.name === "restricted_op") return { block: "Blocked by policy." };
    },
    beforeRequest: async (messages, ctx) => {
      if (!ctx.inputTokens || !ctx.contextWindow) return;
      if (ctx.inputTokens < 0.8 * ctx.contextWindow) return;
      return { history: [await summarize(messages.slice(0, -10)), ...messages.slice(-10)] };
    },
  },
});

Sub-agents, persistent workers, and scheduled actions

Version 1.0 removes the separate SubAgent class. Every worker is a plain Agent with its own instructions, tools, and session folder.

  • Fixed workers (subagents): pass data entries ({ name, description, instructions, model?, tools? }) or full Agent instances. Each invocation runs on an isolated fork() copy so parallel calls never collide.
  • Dynamic workers (dynamicSubagents + agent.workers): gives the model the built-in subagents tool (spawn, message, close, list) and gives your code agent.workers. The developer controls the worker model, thinking, tool pool, maxSpawn, maxDepth, and workerBudget.
import { Agent } from "agent-accelerator";

const lead = new Agent({
  name: "Lead",
  model: "google/gemini-4-hydrogen",
  persist: { dir: "sessions" },
  tools: { computeHash },
  dynamicSubagents: {
    model: "google/gemini-4-hydrogen",
    tools: { computeHash },
    maxSpawn: 3,
    maxDepth: 2,
    workerBudget: { maxCostUsd: 0.25 },
    allowScheduledActions: true,
  },
});

const reply = await lead.workers.spawn({
  name: "Hasher",
  instructions: "Hash inputs and report digests clearly.",
  task: "Hash 'alpha'.",
  tools: ["computeHash"],
});

const next = await lead.workers.message(reply.id, "Now hash 'beta'.");
console.log(next.text);

With persist: { dir }, workers persist under <parent session>/workers/<id>/ and rebuild on restart. If a spawn or message call with a callId replays after a crash, it returns the saved worker answer instead of duplicating the run.

Scheduled actions

When allowScheduledActions: true is enabled, your code (agent.scheduled.create(...)) or the model (scheduled_actions and get_datetime) can schedule one-shot or recurring background workers while the process runs:

lead.scheduled.create({
  instructions: "Write a short status brief.",
  task: "Summarize the current state in three lines.",
  tools: ["computeHash"],
  scheduled_action: {
    name: "Daily brief",
    id: "daily-brief",
    timeToDeliver: "01:09:00", // DD:HH:MM (1 day from today at 9:00...)
    meridiem: "AM",            // ...AM
    repeatEvery: "01:00:00",   // repeat every 24h
    retries: 2,                // retry transient errors (5s, 15s, 45s)
    onMissed: "run",           // run on startup if missed while stopped
  },
});

Results land in <home>/scheduled/ using the documented Scheduled action files format, and scheduled_action.delivered fires on telemetryBus when a file is ready.


Reasoning, caching, retries, and concurrency

Set reasoning uniformly via thinking ("none" | "dynamic" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"), validated pre-flight against the model catalog (ThinkingLevelError lists allowed values). Configure prompt caching with cache ("implicit" | "5m" | "30m" | "1h" | "12h") and serviceTier ("flex" | "priority").

Failures are handled in two layers:

  • retry: per-request exponential backoff on transient HTTP statuses (408, 425, 429, 500, 502, 503, 504, Anthropic 529, OpenRouter in-flight budget 402), timeouts (TimeoutError), and incomplete_stream.
  • runRetries: whole-run retries (default 3) on run() after 5s, 15s, 45s, 60s, resuming without repeating completed tool calls.

To rate-limit requests process-wide across agents, workers, and scheduled runs, configure the concurrency governor in setConfigs:

import { getConcurrencyStatus, setConfigs } from "agent-accelerator";

setConfigs({
  values: {
    concurrency: { max_requests: 8, per_provider: { google: 4 } },
  },
});

console.log(getConcurrencyStatus());

If a provider returns 429 with Retry-After, the governor pauses new calls to that provider (capped at 60 seconds) without blocking other providers.


Cost accounting and spending caps

Each turn is priced in integer micro-USD: provider-reported cost wins when present, otherwise catalog pricing is applied per turn (fresh input, cache reads, cache writes, >200k tiers, and flex/priority multipliers). When a model has no known price, cost stays undefined (or null in reports), never 0.

agent.usageReport() aggregates the agent, dynamic workers, fixed-worker forks, and imageTool calls into one tree without double-counting:

const report = lead.usageReport();
console.log(report.total.cost.totalUsd, report.total.cost.unpricedTurns);
for (const w of report.workers) {
  console.log(w.id, w.status, w.turns, w.cost.totalUsd);
}

Every spending cap is opt-in and unlimited until set:

  • budget: per run() or stream(), including workers.
  • usageLimit: lifetime cap for a conversation across restarts.
  • dynamicSubagents.workerBudget: per worker spawn or message run.
  • dynamicSubagents.scheduledActionBudget: per scheduled-action run.

Configuration in code, self-editing, and safety

For applications distributed to end users, setModels and setConfigs keep policy in TypeScript code while optionally exposing selected keys to <home>/configs.json:

import { setConfigs, setModels } from "agent-accelerator";

setModels({
  default: { model: "google/gemini-4-hydrogen", sub_agent_model: "google/gemini-4-hydrogen" },
  providers: {
    google: { models: ["gemini-4-hydrogen"] },
    openai: { models: ["gpt-5.5"] },
  },
});

setConfigs({
  values: { usage_limit: { max_cost_usd: 5 }, catalog_refresh: "on" },
  editable: ["catalog_refresh"], // only listed keys can be changed via setConfig / configs.json
});

To expose constrained self-editing (model, instructions, and tools names only) while locking down limits, keys, and hooks in your base config, use agent.toConfig() and Agent.fromConfig(edited, base).

Built-in safety and observability defaults:

  • Key isolation: provider keys never cross to another vendor's host, and custom prefixes fail before the network if missing a base URL.
  • Media guards: fileAccess: { roots: [...] } restricts local media reads (including toolContent), and SDK-fetched media URLs block private, loopback, and link-local hosts across DNS lookups and redirects.
  • Telemetry and redaction: the SDK never calls console.*; events emit to telemetryBus (or .ndjson files when telemetry: { persist: true }), and res.raw redacts auth headers and secret query parameters by default (captureRaw: "redacted").

Stateless one-call helpers

For tasks that do not need a multi-turn Agent loop, 1.0 exports four stateless helpers sharing the same catalog, concurrency governor, retry logic, and cost tracking:

  • generateImage (plus imageTool for agents) and GeneratedImage.edit()
  • generateEmbedding and cosineSimilarity
  • generateDecision for typed noul (yes/no), choice, and score probability queries
  • generateVideo, GeneratedVideo.edit(), and resumeVideo (errors after job creation carry err.jobId so interrupted jobs can be resumed)

Structured output and offline testing

Pass a zod schema or JSON Schema via AgentConfig.output to constrain the final answer into res.parsed.

For offline tests without keys or network calls, fauxProvider scripts replies behind the real adapter and tool loop:

import { Agent, fauxProvider } from "agent-accelerator";

const faux = fauxProvider([
  { toolCalls: [{ name: "computeHash", arguments: { text: "test" } }] },
  "Digest computed.",
]);

const testAgent = new Agent({ ...faux.config, tools: { computeHash } });
const reply = await testAgent.run("Hash 'test'.");
console.log(reply.text, faux.calls.length);

In the SDK's own suite, 1,876 tests across 139 files run offline in ~30 seconds, including SIGKILL crash tests against spawned Bun child processes. Before releasing 1.0.0, free-tier live smoke checks were also run on Google (gemini-3.5-flash-lite) and OpenRouter (nvidia/nemotron-3.5-lightning:free), while OpenAI, Anthropic, and paid routes remain verified via spec-matched mocks.


Versioning and upgrading from 0.x

Starting at 1.0.0, the SDK follows Semantic Versioning as documented on the Versioning page:

  • Patch releases fix bugs without changing public names, options, or file formats.
  • Minor releases add functionality while keeping earlier 1.x code working.
  • Major releases are the only place public exports or options may be renamed or removed, accompanied by entries in the Migration guide.

No @deprecated aliases remain in 1.0.0: every option has one canonical name (thinking, dynamicSubagents.model, midSession.whenBusy, maxAttempts, redactError, ModelProvider.OpenAICompatible), old pre-0.5.1 session readers and env-var settings are removed, and saved 1.x sessions stay compatible across 1.x.