For AI agents
A compact, rule-first page for coding agents that write code with
agent-accelerator. People can read the guides, which explain the same things in more detail.
How to work
- Import everything from
"agent-accelerator". Use.tsextensions only for relative imports inside a repo. - Read the guide for a feature before you write code for it. The notes by feature at the bottom of this page list exact signatures and traps.
- Run only what the task needs. The programs in
examples/call real providers and cost money. The test suite is fully mocked. - Never print or hard-code API keys. Use
process.envand placeholders.
Decision table
| Task | Use | Guide |
|---|---|---|
| One answer | await agent.run(prompt), then res.text | Agents |
| Live output | agent.stream(prompt), then await stream.result() | Streaming and steering |
| Call my code | tool({ description, input: z.object(...), execute }) in tools | Tools |
| JSON result | output: zodSchema, then read res.parsed | Agents |
| Specialist helpers | subagents: [{ name, description, instructions }, agentB] | Sub-agents |
| Helpers the model starts | dynamicSubagents: { model, tools } | Sub-agents |
| Work later or on repeat | dynamicSubagents.allowScheduledActions and agent.scheduled.create(...) | Scheduled actions |
| Redirect a busy agent | steer(), queue(), interrupt(), interrupt(message) | Streaming and steering |
| Do not run a repeated message twice | { requestId } on run, queue, steer or ask | Streaming and steering |
| Save, resume, survive a crash | persist: { dir } and the same sessionId. Also loadSessionDir and importSession. | Sessions |
| Images, audio, video, PDFs | A ContentPart[] prompt, and fileAccess.roots | Media input |
| Change a prompt the SDK sends | prompts: { name: "text with " }. Keep the original unless you must. | Prompts |
| Cost control | budget, limits, usageLimit, res.usage | Limits and retries |
| Limit provider calls at once | The concurrency setting and getConcurrencyStatus() | Limits and retries |
| Set options in code, choose what a user may change | setConfigs({ values, editable }), getConfigs(), setConfig(key, value) | Settings |
| Fix the models a program may use | setModels(list), listModels(), setModel(id), setSubAgentModel(id) | Allowed models |
| What it cost | agent.usageReport(). For one run, res.usage. | Usage and cost |
| Let a program edit an agent | agent.toConfig() and Agent.fromConfig(edited, base) | Agents |
| Approve or change a tool call | The beforeTool hook, or ctx.stop(reason) inside execute | Tools |
| Watch what the SDK does | telemetryBus.onEvent | Errors and telemetry |
| Test an agent offline | fauxProvider(steps) | Testing |
Template: a safe production agent
ts
import { Agent, tool } from "agent-accelerator";
import { z } from "zod";
const search_docs = tool({
description: "Search internal docs. Read-only.",
input: z.object({ query: z.string().describe("Search terms") }),
idempotent: true,
timeoutMs: 5_000,
// Pass ctx.signal to real I/O.
execute: async ({ query }) => ({ query, hits: [] as string[] }),
});
const agent = new Agent({
model: "google/gemini-3.5-flash-lite",
instructions: "You answer questions using the search_docs tool. Be concise.",
tools: { search_docs },
maxTurns: 8,
limits: { deadlineMs: 120_000 },
budget: { maxCostUsd: 0.25 },
fileAccess: { roots: [process.cwd()] },
});
const res = await agent.run("How do I reset my password?", {
signal: AbortSignal.timeout(130_000),
});
console.log(res.text, res.usage.cost ?? "cost unknown");Hard rules
- Stable prompts. Never put timestamps or per-request data in
instructions, and never change the tool set between calls. UseadditionalContext. - Explicit config wins over the environment. A custom provider prefix needs its own
<PREFIX>_API_KEYand its address in thebase_urls.<prefix>setting. Never reuse another vendor's key. - Bound everything that runs unattended. Nothing is limited by default except three network timeouts. Set
maxTurns,limits.deadlineMs,budgetand asignal. For workers, setusageLimit,dynamicSubagents.workerBudget,scheduledActionBudget,maxSpawnandmaxDepth.0orInfinityturns a network timeout off. - Branch on error classes and
err.retryable, never on message text. UseisAbortError(err)for cancellation. - Unknown cost is
undefined, not zero. - Tool names match
^[a-zA-Z0-9_-]{1,64}$. Passctx.signalto I/O. - Workers are set by the developer. The model never chooses a worker's model or reasoning level.
- Keep a scheduled action's creating
Agentreferenced. Several processes may share a home. The process that registered the agent runs and delivers its actions. - Never edit the model catalog cache (
<home>/catalog/<provider>/models.json). UseregisterModel(). The catalog keeps only gemini-3+, gpt-5+, claude-5+ and text-output OpenRouter models. Anything else is unknown: no price and permissive thinking. - Everything the SDK stores lives in one folder. Move it with
setHome(dir)or an agent'shome. Never write SDK state anywhere else.
Things that do not exist
Do not generate code for these.
| Do not use | Why, and what to use instead |
|---|---|
Ignoring a failed saveSessionDir or saveSessionFile | They throw when they cannot write. Catch the error, or use persist with onPersistError. |
A tool named __proto__ | Refused. Use a name that matches ^[a-zA-Z0-9_-]{1,64}$. |
needsApproval | Removed. Ask inside execute and refuse with ctx.stop(reason), or use the beforeTool hook. |
A hooks name other than beforeTool, afterTool, beforeRequest, onYield | It throws ConfigError. |
Tool retry, tags, output | Removed. They did nothing. |
thinking.budgetTokens | Not forwarded to any provider. |
stop, seed | Removed. Do not pass them. |
temperature, topP, sampling | Removed on every provider. |
| Gemini 1.x or 2.x | Rejected. The minimum is Gemini 3. |
cache values a provider lacks | They warn and fall back. See Reasoning and caching. |
| Two processes on one saved session | The folder is locked. The second process gets a ConfigError. Use a different sessionId per process. They can share a home. |
The SubAgent class, agentFromEnv(), Agent.fromEnv(), .asTool(), .toTool() | Removed. Write the helper as data, { name, description, instructions } in subagents: [...] (no model means the worker model), or use new Agent({ name, model, instructions }), or agentToTool({ name, agent }). For an Agent that should use the saved or default main model, leave out model. See Migration. |
| The OpenRouter Responses transport | Gone. OpenRouter uses Chat Completions. |
Error to fix
| Symptom | Likely cause and fix |
|---|---|
ConfigError before any request | No key or address for that prefix. Set <PREFIX>_API_KEY and the base_urls.<prefix> setting. |
SettingNotEditableError | setConfig on a hidden setting. Only keys in getConfigs() can be changed. |
ModelNotAllowedError | The model is not in your setModels list. Pick one from err.allowed. |
ThinkingLevelError | The model does not support that level. Use one from err.allowedLevels. |
SubAgentModelError | Set dynamicSubagents.model, or a default worker model with setModels or setSubAgentModel. |
BudgetExceededError | Raise budget, or reduce the work. err.partial has the progress. |
SecurityPolicyError | A path outside fileAccess.roots, or a private or loopback URL. |
SessionLoadError | A session is over the load limits you set (persist.loadLimits, or the limits argument). Raise them, or archive the session. |
A tool result repeat_blocked | The model repeated an identical call 3 times. Fix the tool's output, or mark it repeatable. |
finishReason: "max_turns" | Raise maxTurns, or simplify the task. |
| A scheduled action never fires | Its creating Agent was garbage-collected, or the process exited. |
Repeated provider_warning | An option is not supported by that provider. Remove it. |
Notes by feature
Agents and models
- Create:
new Agent(config: AgentConfig). Run:await agent.run(prompt: string | ContentPart[], options?: AgentRunOptions): Promise<AgentResponse>. - Precedence: explicit config beats the environment.
thinkingbeatsthinkingLevel. A per-run option beats the agent's default, and objects merge key by key. maxTurns: 0means unlimited. An unknown or unsupported option is warned about and dropped. It is not an error.- To see where a model string goes:
resolveModel(modelString)returns{ provider, modelId, modelSpec }. - Errors you can branch on:
ThinkingLevelError,ValidationError,ConfigError,ProviderError. See the Reference.
Tools and streaming
- Define a tool with
tool({ description, input: z.object({...}), execute }). Register it withtools: { name: def }. The record key is the name. - Defaults: 1 attempt (3 if
idempotent), a 20,000 character result cap, 8 tools at once, and the third identical consecutive call is blocked. ctx.stop(reason)throws and never returns. It savesreasonas the call's result, lets the rest of the batch finish, and ends the run withfinishReason: "stopped"and no more model turns.agent.stream()returns anAssistantMessageEventStream. Alwaysawait stream.result()for the finalAgentResponse.steer,queueandinterruptonly make sense whileagent.isBusy.
Workers and scheduling
- Fixed:
new Agent({ subagents: [{ name, description, instructions }, agentB] }); data entries run on the worker model unless they name one, and take onlyname,description,instructions,modelandtools. Dynamic:dynamicSubagents: { model, tools, maxSpawn }, and the model gets thesubagentstool. Scheduling:dynamicSubagents.allowScheduledActions: trueand a worker model, or you getSubAgentModelError. agent.scheduled.create(input)throws oneValidationErrorthat lists every problem.scheduled_action.idmust be lowercase kebab-case, at most 48 characters.timeToDeliverhasHHfrom 01 to 12.- Workers that keep a conversation:
agent.workers.spawn,message,closeandlist. PasscallIdfor exactly-once after a crash. They need a worker model, andpersist: { dir }on the parent to survive a restart. - Track workers with
track,listTrackedSubAgentsandsubscribeToSubAgent. Do not poll files. - Scheduled action files: read each
<id>/task.jsonand the run files as plain JSON. Never writestate,current,next*,lastRunordelivery.json. To change an action, callagent.scheduled.update, not the file. A run's cost is in its header.costUsdisunknown(never 0) when no price is known, so checkunpricedTurnsbefore you treat it as exact.
Sessions, media and cost
- One agent per request in a server: call
agent.close()when the request is done. It releases the folder lock, open workers and per-session provider state; a closed agent throwsValidationErroron new work. - Crash recovery:
persist: { dir }and the samesessionId. Useresume: "automatic"or"explicit",agent.interrupted()andagent.resume(). To continue a finished chat by hand:findLatestSessionDir, thenloadSessionDir, thenagent.importSession(saved.session). - A prompt is
string | ContentPart[]. Part keys areimage,audio,videoandfile, plusfilenameandmimeType. - Cost may be
undefined. Handle it. UseSessionTelemetryfor running totals. - Older models (gemini-2, gpt-4, claude-4 and so on) are not in the catalog.
Safety
- For anything unattended, set
maxTurns,limits.deadlineMsandbudget, and pass asignalper call. err.partialholds progress.err.retryabletells you whether to retry.- Keep
captureRawat"redacted"unless you are debugging locally. - Use
fileAccess: { roots: [...] }whenever file paths or sessions come from outside your program.
Generators
- Images: import
generateImage. The model is aprovider/modelstring fromlistImageModels(). Do not invent model ids. Never combinesizewithaspectRatioorresolution. ReadgetImageModel(model)for what a model accepts. result.imageis never undefined. Save it withawait result.image.save(path). To change a picture, callimage.edit(prompt).- To let a text agent make pictures, use
imageTool({ model, allow, maxImages })intools. Setallowonly for options the model has. - A runnable offline demo for each generator is in
examples/(17 to 20).
Prompts
promptsisPartial<Record<PromptName, string>>.DEFAULT_PROMPTSis a frozenRecord<PromptName, string>.PromptNameandPromptOverridesare exported types.- An agent cannot edit prompts through
toConfigorfromConfig. Onlymodel,instructionsandtoolsare editable. - Machine-readable parts stay out of the prompt text:
repeat_blockedis also anerrorCode, and the[worker <id>]header is only text for the model. - Do not rely on a prompt change for safety. It is advice to the model, not enforcement.
Where to look
llms.txt is a one-screen index. The Reference has every key and code. The authoritative source is src/index.ts (the public exports) and src/types/.