Agent spec files (AgentSpec)
This page describes spec version 1. New specs use Agent spec v2; upgradeSpec() converts a v1 spec.
A declarative agent is a YAML (.yaml/.yml) or JSON (.json) file,
validated with zod by loadSpec() (src/spec/schema.ts). It is the format
lousho dev serves and lousho build deploys.
Snippets on this page leave some names to you:provideris anyLLMProvider(offline:createMockProvider()).
A missing or invalid field fails with an error naming the exact field, e.g.
'prompt': Required.
Tools a spec can reference
github and jira need credentials a spec has no field for; referencing
them throws an error telling you to build the agent with createAgent() and
pass a configured tool instead.
Policy (policy)
specToAgent() compiles policy into createAgent() options, so a spec
enforces what it declares. The known fields are validated by loadSpec();
other keys are kept for the other harness generators (Claude Code, Codex, Pi),
which read the raw policy.
Every guardrail also takes
on: input, output or tools (a tool call’s
arguments), or a list of them. The default is [input, output]. An unknown name
or option fails validation, naming the guardrails available and a “did you
mean” suggestion:
'policy.guardrails.0': unknown guardrail 'deny-topic' (did you mean 'deny-topics'?).
requiresApproval pauses the run (finishReason: 'awaiting-approval') until
agent.approvals.resolve(); before this, a spec that set it ran its tools
without asking. lousho doctor agent.yaml prints one line per policy block.
MCP servers (mcpServers)
mcpServers declares the MCP servers an agent uses, as a map from a server
name (it namespaces that server’s tools) to either a stdio server (command,
optional args and env) or an HTTP server (url, optional headers).
Each entry sets exactly one of command / url; args/env apply only to
stdio and headers only to HTTP. The field is validated by loadSpec(), and
an invalid entry fails with the entry name in the message, e.g.
'mcpServers.files': missing 'command' (stdio server) or 'url' (HTTP server).
An optional approval (always, the default, annotations or never) says which of the server’s tools ask for approval; see Approval for MCP tools.
An optional deferLoading: true withholds the server’s tools from the model until it finds them with tool_search; see Tool search.
An optional optional: true leaves out a server that cannot connect (with a warning) instead of failing every send; see Use MCP servers in an agent.
An HTTP entry may set oauth (redirectUri, optional clientId, clientSecret, scopes and clientName) to sign in to the server with OAuth instead of a static Authorization header; see MCP servers with OAuth.
lousho doctor checks each stdio command is resolvable.
specToAgent() passes the servers to createAgent({ mcpServers }), described
in MCP, so lousho dev and lousho mcp agents get their tools.
MCP clients, connectMcp(), tool approval and serving an agent over MCP are on their own page: MCP (Model Context Protocol).
Provider credentials
Real providers are resolved byresolveProvider('<provider>/<model>')
(also used for spec files), which reads the credential from the environment:
The
mock provider needs no credentials and returns canned responses; it is
what the examples and the Quick Start use by default.
Provider retries and fallback
createAgent() retries failed model calls on its own, and can fall back to
other models. The vendor/ model prefix chooses the provider; with OpenRouter
use openrouter/<vendor>/<model> (e.g. openrouter/openai/gpt-4o-mini).
retrytakes thewithRetry()options below. It applies to themodelstring (or the model picked from the environment) and to everyfallbackModelsentry. createAgent builds those providers with theaiSDK’s own retries off (maxRetries: 0), so retries happen in one place and the default{ maxRetries: 2 }makes as many calls as before.- A built-in provider instance (
OpenAIProvider,AnthropicProvider,OpenRouterProvider,OllamaProvider) or afromAiSdk()provider is wrapped inwithRetry()too, even withoutretry: then with the provider’s ownmaxRetries(default 2), so its retries emitprovider.retryevents like a model string’s. Its calls go out with theaiSDK’s own retries off, so{ maxRetries: 2 }makes at most 3 requests, andretry: falsesends each call once. Any otherproviderinstance (your ownLLMProvider) is wrapped only when you setretry.fallbackModelswork with all of them. fallbackModelsareprovider/modelstrings, resolved likemodelwhen the agent is created. The agent runswithFallback([withRetry(primary), withRetry(fallback1), ...]): every call starts with the primary model.stream()andsession.stream()report each retry as aprovider.retryevent and each switch asprovider.fallback; itsfromandtoare provider names (such asopenai) andfromModel/toModelthe model ids (see Streaming).send()returns the final result as before.
withRetry(provider, options) and withFallback(providers, options) wrap any
LLMProvider and return another one, so they compose and can be passed
anywhere a provider is accepted:
withRetryretriesgenerate()andstream()(defaultmaxRetries: 2) on rate limits, timeouts, network errors (including a dropped socket), malformed or truncated responses and 5xx responses, using the same classification ascompactProviderError(). Auth failures, invalid requests and context-length errors are not retried; neither is a cancellation. A provider’sretryAfterMshint (retry-after-msorRetry-After, on a 429 or a 503) replaces the backoff delay, unless it is longer thanbackoff.maxMs(default 30 s): then the call fails at once with aCompactedLLMProviderErrorwhosecompacted.retryAfterMsholds the hint, so your code decides whether to wait. PassretryOn(error, attempt)to change the rule,timeoutMsfor a per-attempt time limit, andsignalto stop retrying. Forstream(),timeoutMsonly bounds the wait for the first chunk: a stream that has started is never cut off by it.idleTimeoutMs(stream only) fails a stream that goes quiet for longer than that between chunks, with aTimeoutError(retried only while no text or tool call was out).- A
stream()call is retried when it rejects, and when its stream fails before any output: reasoning chunks and empty text deltas don’t count, so a local runtime that sends an emptyreasoning-endand then a 500 (LM Studio) is retried. A failure after text, a tool call or the finish is not retried. An agent streams its model calls whenever it has an event listener, so this is what keepsagent.stream()as resilient assend(). - Reasoning streamed before such a failure was already reported. In an agent
run the failed attempt’s reasoning ends with its
reasoning.done, then comes theprovider.retryevent, then the retried attempt’s reasoning starts again withreasoning.start. The step’s (and the run’s)reasoningis the successful attempt’s only. withFallbacktries each provider in order and rethrows the last error when all fail. By default it falls back on any error except a cancellation (fallbackOnchanges that). Each fallback runs on its owndefaultModel. Every call keeps its own fallback state, so concurrent calls never see each other’s switches.nameanddefaultModelare the first provider’s; the result of a call (and a stream) names the provider and model that served it asservedBy, and the run books that call’s usage and cost under that model inusage.byModel.resilientProvider(provider, { maxRetries, timeout })applies theLLMProviderConfigfields of the same names.withRetryis the only retry layer: the built-in providers send its calls with theaiSDK’s own retries off, whatever their config’smaxRetries. ThatmaxRetries(default 2) is theaiSDK’s retry count for a provider used unwrapped (called directly), and thewithRetry()countcreateAgent()uses for that provider whenretryis unset.- A rate-limited call (a 429) fails, once the retries are used up, with
LOUSHO_PROVIDER_RATE_LIMITED; other failed calls withLOUSHO_PROVIDER_REQUEST_FAILED(see Errors). - Each retry is recorded on the call’s
chatspan aslousho.retry.countandlousho.retry.errors(see Observability).
Rate limits
withRateLimit(provider, limits) queues a provider’s generate() and
stream() calls so they stay under client-side limits, so sub-agent fan-out,
flow waves and eval suites cannot burst unbounded model calls. Every limit is
optional:
- Calls are admitted first in, first out. A call waiting for its turn rejects
with its
signal’s reason as soon as it is aborted, and never starts. tokensPerMinutebooks each call atestimateTokens()of its messages and tool definitions plus itsmaxTokens, then re-books it at the usage the provider reports. A single call larger than the limit still runs, alone in its window.- A
stream()holds itsmaxConcurrentslot until the stream ends. - Invalid limits (not a positive number, or
maxConcurrentnot a whole number) throwLOUSHO_CONFIG_INVALID. - Wrap outside
withRetry()to count a call and its retries as one, or inside to count each attempt. - Pass a
createRateLimiter(limits)instead of the limits to share one budget between several providers.
createAgent({ rateLimit }) takes the same limits (or a limiter). One budget
covers every model call of the agent’s runs, including the sub-agents and
handoff targets a run starts (a sub-agent inherits the lead run’s budget, so
its own provider is queued too). Give several agents the same
createRateLimiter() to share it across them.
createAgent() options
With neither
model nor provider, createAgent() resolves from the
environment: LOUSHO_MODEL (a 'provider/model' string) if set, otherwise
the first provider whose variable is set, checked in this order:
OPENAI_API_KEY (openai/gpt-4o-mini), ANTHROPIC_API_KEY
(anthropic/claude-sonnet-4-5), OPENROUTER_API_KEY
(openrouter/openai/gpt-4o-mini), OLLAMA_BASE_URL (ollama/llama3). If none
is set it throws an error listing exactly which options or variables fix it.
Misconfiguration errors say how to fix themselves: a missing key names the
variable (createAgent: OPENAI_API_KEY is not set. ...), an unknown prefix
lists the supported ones and suggests the closest, and a missing optional peer
dependency prints the exact npm install command.
An option createAgent() does not know is an error (LOUSHO_CONFIG_INVALID),
not silently ignored, so a typo fails from JavaScript or YAML too.
The message suggests the closest option, or the Lousho name for one other SDKs
use: 'maxOutputTokens' is not a known option (did you mean 'modelSettings.maxTokens'?),
and system points to instructions. A key set to undefined is ignored, and
the manifest of a spread claudeProject() result is accepted.
Model settings
modelSettings sets the sampling options of every model call an agent makes.
A send() or stream() call can pass its own, which win key by key over the
agent’s:
maxTokens, temperature, topP, frequencyPenalty,
presencePenalty, stop, seed and toolChoice ('auto', 'required', 'none' or { type: 'function', function: { name } }; not sent on a call without tools). A key you leave out is not sent at all,
so the provider’s own default applies, and so does a value that a wrapping
provider adds to the request. Sub-agents and handoff targets use their own
modelSettings, not the lead’s. An agent directory can set the same object as
modelSettings in its agent.json.
The values are checked before any model call, at createAgent() and at each
send() / stream(): temperature 0 to 2, topP 0 to 1, frequencyPenalty
and presencePenalty -2 to 2, maxTokens a whole number of at least 1, seed
a whole number, stop an array of strings. A value out of range, or an unknown
key (such as the AI SDK’s maxOutputTokens), throws a ConfigurationError
with code LOUSHO_CONFIG_INVALID whose field names the key, e.g.
modelSettings.temperature. A provider with a narrower range (Anthropic’s
temperature is 0 to 1) still rejects a value outside it.
Per-call options
BesidesmodelSettings, a send() or stream() call can set its own
maxSteps (instead of the agent’s; a whole number of at least 1, checked like
createAgent’s) and instructions, which are appended to the agent’s
instructions for that run:
instructions go with every model call of the run (a handoff
target’s too) but are not written to the transcript, so a later call with the
same sessionId runs without them unless it passes them again. A run continued
by agent.approvals.resolve() or agent.resume() uses the agent’s maxSteps
and instructions.
To share options between agents, type them as CreateAgentBase and spread
them into createAgent(). Do not use Partial<CreateAgentConfig>: that type
keeps model / provider and instructions / prompt mutually exclusive,
so TypeScript rejects spreading it next to a literal that sets one of them.
Budgets
limits caps what a run may spend. Set it on createAgent() (every run of the
agent) or on AgentExecutor.execute() / stream():
Limits are checked before every model call (so after every tool batch) and
after a model call that asks for tools;
maxDurationMs also aborts an
in-flight model or tool call through the run’s signal. A limit trips once the
run reaches it. A run that finishes on its own within the step that reached a
limit keeps its own finish reason, like maxSteps.
Sub-agents share their lead’s budget. Usage of sub-agents counts toward
their lead’s limits, and a sub-agent is held to them while it runs: before each
of its model calls (and after a model call that asks for tools) it checks the
lead’s token, cost and duration limits against what the lead, the lead’s other
sub-agents still running, and it itself have spent - on top of its own
limits. Once they are reached the sub-agent stops with 'budget-exceeded'
(always 'stop'; the lead’s onExceeded decides how the lead ends), the
task call reports Sub-agent '<name>' stopped at the <limit> limit, and the
lead stops before its next model call. Parallel sub-agents can still go over by
the model calls they had in flight when the limit was reached (at most one
each), not by a whole run each. A nested sub-agent is held to every lead above
it. A sub-agent resumed after an approval is held to its own limits only.
A spend limit (tokens, cost, duration) is a hard stop: a run with output
that reaches one makes no forced answer call (that call would spend past the
limit), so result.object is unset. What the run’s tool calls returned before
the limit tripped - finished sub-agents’ answers included - stays in
result.messages as tool results. Only running out of steps (maxSteps or
limits.maxSteps) gets the forced answer call.
When a limit trips, the run stops with finishReason: 'budget-exceeded' and
result.budget ({ limit, value, max, scope }). Tool calls the model asked
for in that step get a “cancelled” result, so the transcript stays valid, and
with a checkpoint store it is checkpointed as finished, like 'max-steps'.
stream() emits a budget.exceeded event before run.done. With
onExceeded: 'throw' the run rejects with BudgetExceededError
(LOUSHO_BUDGET_EXCEEDED, with the same budget) instead.
createAgent({ limits }) applies to each run on
its own: every send(), and every turn of a session, starts from zero.
agent.session({ id, limits }) adds limits across all of the session’s turns:
a turn stops once what the session has spent, in all its turns, reaches a
limit (budget.scope is then 'session'), and later turns stop before calling
the model. What the turns spent (tokens, cost, steps and run time) is saved with
the transcript, as metadata.sessionUsage on its last message, so a session
continued from its store keeps its budget. Both apply together; the first limit
reached stops the turn. A turn that was aborted is not counted.
Project instructions
Many repositories keep guidance for coding agents in anAGENTS.md (or
CLAUDE.md) file. createAgent can append it to the agent’s instructions:
## Project instructions (from AGENTS.md). It is read once, when the agent is
created. The lookup walks up from cwd (default process.cwd()) and uses the
nearest directory that has one of files (default ['AGENTS.md', 'CLAUDE.md'],
first match wins), stopping at the nearest directory that contains .git or at
the filesystem root. Content over 32,000 characters is cut with a truncation
marker. If no file is found nothing is added.
This is opt-in on purpose: reading files from disk by default would surprise
people who embed the SDK in a server, where the working directory is not the
project the agent is about. To find the file yourself (for example to show it),
use loadProjectInstructions({ cwd, files, stopAt, maxChars }), which returns
{ path, content } or undefined.
AgentExecutor.execute() options
The options of AgentExecutor.execute(), the lower-level entry point, are listed on the executor API page.
CLI
lousho dev, lousho build, lousho mcp and the other commands, with their
flags, are described in CLI; lousho mcp is also covered in MCP.