Agents
Configure and run AI agents with tools, instructions, and model parameters.
Overview
An Agent is a configured LLM instance with a name, system prompt, tools, and model parameters. Agents are stateless blueprints -- the Cogitator runtime handles execution, memory, and lifecycle.
import { Agent } from '@cogitator-ai/core';
const agent = new Agent({
name: 'researcher',
model: 'anthropic/claude-sonnet-5-5',
instructions: 'You are a research assistant. Find accurate information and cite sources.',
});AgentConfig
interface AgentConfig<TDeps = unknown> {
id?: string;
name: string;
description?: string;
model?: string; // default: llm.defaultModel of the Cogitator
provider?: string;
fallbackModels?: Array<string | { model: string; provider?: string }>; // tried when model fails
instructions: string;
tools?: Tool<unknown, unknown, TDeps>[];
skills?: AgentSkillSource[]; // defineSkill() bundles, merged in, or SKILL.md sources (SkillRegistry)
temperature?: number; // default: 0.7
topP?: number;
maxTokens?: number;
stopSequences?: string[];
responseFormat?: ResponseFormat;
reasoning?: ReasoningConfig; // effort and summaries for reasoning models
handoffs?: Array<Agent | Handoff>; // agents it can hand the conversation over to
maxIterations?: number; // default: 10
onIterationLimit?: 'answer' | 'stop'; // default: 'answer'
timeout?: number; // default: limits.defaultTimeout of the Cogitator, else 120000 (2 min)
timeouts?: RunTimeouts; // { totalMs, stepMs, chunkMs, toolMs }, see Stage Timeouts
todos?: boolean; // the write_todos tool and a todo list kept in the thread, default: false
middleware?: RunMiddleware<TDeps>[]; // hooks around its model and tool calls
}Model String Format
The model field uses a provider/model-name convention to route to the correct backend:
model: 'openai/gpt-6.1-sol';
model: 'anthropic/claude-sonnet-5-5';
model: 'ollama/llama3.3:latest';
model: 'google/gemini-3.8-flash';If you omit the provider prefix (or the prefix is not a known provider, backend or plugin), the whole string goes to the defaultProvider from your runtime config, Ollama when unset. If you omit model altogether, the agent runs on llm.defaultModel; a run fails with a CONFIGURATION_ERROR when neither is set. cog.resolveModel(agent) returns the model a run would use.
Provider Override
For OpenAI-compatible APIs (OpenRouter, local vLLM, etc.), use the provider field to explicitly route:
const agent = new Agent({
name: 'openrouter-agent',
model: 'meta-llama/llama-3.3-70b-instruct',
provider: 'openai',
instructions: '...',
});Fallback Models
fallbackModels lists models a turn moves to, in order, when model is down, out of quota, rejects the key or no longer exists. Rate limits and server errors are retried on the same model first. A fallback answers one turn, the next starts from model again, and result.modelUsed names the model of the final answer when it was a fallback:
const agent = new Agent({
name: 'support',
model: 'anthropic/claude-sonnet-5-5',
fallbackModels: ['openai/gpt-6.1-sol', 'google/gemini-3.8-flash'],
instructions: 'Answer support questions.',
});Which errors move a turn, the circuit breakers and streaming are covered in Fallback Models.
Dependencies for Tools
Tools often need things the model must never see: a database client, an API key, the signed-in user. Pass them as deps and read them from the tool's context. Typing the agent with its deps makes the compiler check both sides:
import { Agent, tool, type ToolContext } from '@cogitator-ai/core';
interface AppDeps {
db: Database;
userId: string;
}
const listOrders = tool({
name: 'list_orders',
description: "List the signed-in user's orders",
parameters: z.object({ limit: z.number().default(10) }),
execute: async ({ limit }, { deps }: ToolContext<AppDeps>) =>
deps.db.orders.findMany({ where: { userId: deps.userId }, take: limit }),
});
const agent = new Agent<AppDeps>({ name: 'support', instructions: '...', tools: [listOrders] });
await cog.run(agent, { input: 'Where is my order?', deps: { db, userId: session.userId } });depsreach every tool of the run: tools of agents it hands over to, agents run as tools andcog.invokeTool(tool, args, { deps }).- They never reach the model, the memory, spans, the run result or a paused run's checkpoint. Pass them again to
cog.resume(agent, checkpoint, { deps, decisions }). new Agent<AppDeps>(...)makesdepsrequired inrun()andresume(), and refuses a tool whose deps type is unrelated toAppDeps. TypeScript compares tool methods loosely, so declare inAppDepsevery field the agent's tools read: a tool reading a fieldAppDepslacks still compiles. An agent without a deps type takes any tool, and a tool that readsdepsthen getsundefinedwhen the run passes none.RunOptions.contextis different: it is data for the model, sent as one JSON block in the turn context in front of the input.depsare passed by your own code:cog.run(),cog.resume(),cog.invokeTool()and tools made withagentAsTool. Server adapters, channels, swarms, workflows and the worker start runs without them, so an agent whose tools readdepsruns throughcog.run()of your own for now.
Agent with Tools
import { Agent, tool } from '@cogitator-ai/core';
import { z } from 'zod';
const searchWeb = tool({
name: 'search_web',
description: 'Search the internet for current information',
parameters: z.object({
query: z.string().describe('The search query'),
limit: z.number().default(5),
}),
execute: async ({ query, limit }) => {
const results = await searchAPI.search(query, limit);
return results.map((r) => ({ title: r.title, url: r.url }));
},
});
const researcher = new Agent({
name: 'researcher',
model: 'openai/gpt-6.1-sol',
instructions: 'You are a research assistant. Use tools to find accurate information.',
tools: [searchWeb],
maxIterations: 15,
});The agent loops up to maxIterations times. Each iteration the LLM may call tools or produce a final response. The loop ends when the LLM responds without tool calls. An empty turn (no text and no tool calls) is not taken as the final response: the run asks the model again, up to twice.
When tool calls use up maxIterations before the model answers, the run gets one more turn with toolChoice: 'none' and an instruction to answer from what it has, so it still ends with an answer and structured output can be parsed. Tools the model asks for on that turn are not run. result.iterationLimitReached is true either way, and onIterationLimit: 'stop' ends the run at the last tool turn instead, without an answer.
result.truncated is true when the model's last answer stopped at the output token limit (maxTokens): the output may be cut off, or empty when a reasoning model spent the whole limit thinking. Every provider reports it, so it is the way to tell a cut-off answer from a short one. Tool calls in a turn cut off at the limit never run, since their arguments may be incomplete: the run ends truncated instead.
result.blocked is set when the provider withheld the model's last answer instead of finishing it: 'content_filter' when its safety system filtered the answer (OpenAI and Azure content filters, Gemini SAFETY and similar, Bedrock guardrails), 'refusal' when the model declined (OpenAI and Anthropic refusals). The run still completes, with output holding what the model said before it stopped, the explanation of a refusal or often nothing. The run does not ask again for a blocked answer, and does not ask a blocked structured answer to be corrected.
A turn the provider ends in an error fails the run with LLM_INVALID_RESPONSE instead of passing for an empty answer, with the provider's explanation when it gives one (ChatResponse.finishMessage). An agent with fallback models moves such a turn to the next model first. Gemini, for instance, reports a function call it could not complete, often one cut by maxTokens, as MALFORMED_FUNCTION_CALL: the run fails with that message, and the cut call never runs. Anthropic and Bedrock malformed_tool_use and a failed Responses API answer end the same way.
const result = await cog.run(agent, { input });
if (result.blocked) {
console.warn(`The answer was withheld (${result.blocked}): ${result.output || 'no text'}`);
}Agent with Structured Output
Force the LLM to respond with a specific JSON shape using Zod schemas:
const analyzer = new Agent({
name: 'analyzer',
model: 'openai/gpt-6.1-sol',
instructions: 'Analyze the given text and extract structured information.',
responseFormat: {
type: 'json_schema',
schema: z.object({
summary: z.string(),
sentiment: z.enum(['positive', 'negative', 'neutral']),
keyPoints: z.array(z.string()),
}),
},
});See Structured Outputs for details on json and json_schema modes.
Cloning Agents
Create variations of an agent with clone():
const baseAgent = new Agent({
name: 'coder',
model: 'anthropic/claude-sonnet-5-5',
instructions: 'You are a senior software engineer.',
temperature: 0.3,
});
const creativeAgent = baseAgent.clone({
name: 'creative-coder',
temperature: 0.9,
});
const fastAgent = baseAgent.clone({
model: 'anthropic/claude-haiku-4-5',
});A clone gets a new id unless the overrides set one.
Serialization
Agents can be serialized to JSON for storage and restored later:
import { writeFile } from 'node:fs/promises';
const snapshot = agent.serialize();
await writeFile('agent.json', JSON.stringify(snapshot, null, 2));Restore with the tool implementations:
import { readFile } from 'node:fs/promises';
import { Agent } from '@cogitator-ai/core';
import type { AgentSnapshot } from '@cogitator-ai/types';
const saved = JSON.parse(await readFile('agent.json', 'utf-8')) as AgentSnapshot;
const restored = Agent.deserialize(saved, {
tools: [searchWeb, readUrl],
});Tools are stored by name in the snapshot. During deserialization, each tool name is resolved from toolRegistry (any { get(name) }, such as a ToolRegistry) when given, otherwise from the tools array; a missing tool throws AgentDeserializationError. overrides replaces any config field of the restored agent.
A snapshot keeps the model, fallbackModels, instructions, sampling parameters, reasoning, maxIterations, onIterationLimit, timeout and todos, but not handoffs, skills (their tools are kept by name) or middleware. A json_schema response format is saved by name only, so pass the Zod schema back as overrides.responseFormat. Agent.validateSnapshot(value) checks a parsed snapshot, it rejects snapshots without a model, so give agents you serialize an explicit model.
Sending an agent to another process
agent.serialize() is for storage. To run an agent in another process (a queue job, a workflow job, a distributed swarm turn), use the agent wire format, which keeps every setting but middleware:
import { toAgentWire, fromAgentWire } from '@cogitator-ai/core';
const wire = toAgentWire(agent); // plain JSON
// in the process that runs it
const received = fromAgentWire(JSON.parse(payload), { cogitator, tools: [searchWeb, readUrl] });toAgentWire carries the whole configuration: model and provider, fallback models (up to 16), instructions, sampling, stopSequences, reasoning, responseFormat (a Zod schema as JSON Schema, turned back into one on arrival), maxIterations, onIterationLimit, timeout, todos, the tool schemas and every agent the agent can hand over to (handoff graphs with cycles included). Skills defined in code arrive merged into the tools and instructions. Sources of SKILL.md skills stay behind, since they read folders of the sending side: give the received agent its own. An explicit provider also prefixes the model, so the agent runs on the same route wherever it lands. Pass resolveModel for an agent without a model, e.g. toAgentWire(agent, { resolveModel: (a) => cogitator.resolveModel(a) }). Middleware is code and stays behind, toAgentWire warns when the agent has some: the receiving side runs the agent with its Cogitator's own middleware.
fromAgentWire validates the payload (agentWireSchema, or parseAgentWire alone), refuses keys it does not know instead of dropping them, resolves the tools by name from tools and throws AgentWireError for a missing tool or a provider the receiving Cogitator cannot route to. toAgentWireRunResult(result) and fromAgentWireRunResult(wire, { agentId }) carry a run's outcome the same way: answer, structured output, usage with cost and duration, tool calls with their outputs, and the truncated, blocked and iterationLimitReached flags. @cogitator-ai/worker and distributed swarms use both.
Skills
skills takes two kinds of skills. Skills in the Agent Skills format are folders with a SKILL.md: the model sees their names and descriptions and loads one with the built-in use_skill tool when a task needs it, see Skills.
import { SkillRegistry } from '@cogitator-ai/core';
const agent = new Agent({
name: 'maintainer',
model: 'anthropic/claude-sonnet-5-5',
instructions: 'You maintain this project.',
skills: [new SkillRegistry({ project: process.cwd(), user: true })],
});A skill defined in code bundles tools with the instructions for using them. skills on an agent adds each such skill's tools (unless the agent already has a tool of that name) and appends its instructions to the agent's:
import { defineSkill } from '@cogitator-ai/core';
const weatherSkill = defineSkill({
name: 'weather',
version: '1.0.0',
description: 'Current weather and forecasts',
tools: [getWeather],
instructions: 'Use get_weather for any question about the weather.',
env: ['WEATHER_API_KEY'],
});
const assistant = new Agent({
name: 'assistant',
model: 'openai/gpt-6.1-sol',
instructions: 'You are a helpful assistant.',
skills: [weatherSkill],
});validateSkill(skill) reports missing fields, environment variables and dependencies; the CLI scaffolds and validates skill packages with cogitator skill.
Agents as Tools
Wrap an agent as a tool so other agents can delegate to it:
import { agentAsTool } from '@cogitator-ai/core';
const researchTool = agentAsTool(cogitator, researcher, {
name: 'research',
description: 'Delegate a research task to the research agent',
});
const orchestrator = new Agent({
name: 'orchestrator',
model: 'openai/gpt-6.1-sol',
instructions: 'You coordinate tasks. Use the research tool for information gathering.',
tools: [researchTool],
});The tool takes a single task string and returns { output, success, error? }. includeUsage and includeToolCalls add the inner run's usage and tool calls, and timeout limits it. The inner run inherits the caller's userId, deps and abort signal. Calls of the inner agent that need approval are declined unless you pass onApproval, since nobody can answer them mid-delegation. See Agent as Tool.
Reasoning
Reasoning models think before they answer. reasoning sets how hard, in one vocabulary for every provider, and can ask for a readable summary of the thinking:
const analyst = new Agent({
name: 'analyst',
model: 'anthropic/claude-opus-5-5',
instructions: 'Answer questions about the quarterly numbers.',
reasoning: { effort: 'high', summary: true },
});
const result = await cog.run(analyst, {
input: 'Why did margins drop in Q3?',
stream: true,
onReasoning: (delta) => process.stdout.write(delta), // the summary, while it streams
});
result.reasoning; // the whole summary
result.usage.reasoningTokens; // thinking tokens, billed as outputeffort goes from none to max; a run can override it with cog.run(agent, { reasoning }). How each provider applies it is in LLM Backends.
Handoffs
An agent can hand the conversation over to another one. handoffs lists the agents it may pass to; each becomes a transfer_to_<name> tool described by the target's description. When the model calls it, the rest of the run goes on as the target agent — its instructions, tools, model and reasoning — with the whole conversation so far:
const billing = new Agent({
name: 'billing',
description: 'Invoices, payments and refunds',
model,
instructions,
tools: [lookupInvoice],
});
const support = new Agent({
name: 'tech_support',
description: 'Login problems and outages',
model,
instructions,
tools: [serviceStatus],
});
const triage = new Agent({
name: 'triage',
model,
instructions: 'Greet the customer and hand the conversation to the right specialist.',
handoffs: [billing, support], // or { agent: billing, toolName: 'ask_billing', description: '...' }
});
const result = await cog.run(triage, {
input: 'How much do I owe on INV-204?',
onHandoff: console.log,
});
result.handoffs; // [{ from: 'triage', to: 'billing', reason: '...' }]
result.finalAgent; // 'billing' — send the next message of this thread to itUnlike agents as tools, where a sub-agent answers the caller and the caller keeps the conversation, a handoff gives the conversation away. Unlike swarms, there is no coordinator: each agent decides when to pass on. A run that pauses for approval after a handoff resumes in the agent it was handed to.
Temperature Guidelines
| Use Case | Temperature | Notes |
|---|---|---|
| Code generation | 0.0 -- 0.2 | Deterministic, correct code |
| Planning / classification | 0.2 -- 0.4 | Consistent but flexible |
| General assistant | 0.5 -- 0.7 | Balanced (default: 0.7) |
| Creative writing | 0.8 -- 1.2 | More varied output |
| Brainstorming | 1.0 -- 1.5 | Maximum creativity |
Session Budgets
Limits of money, tokens and tool calls for a session and for each agent in it, with a warning before the limit and a pause instead of a failure when it is reached.
Harness Agent
createHarnessAgent() assembles a coding or assistant agent from the workspace, todos, skills, subagents, commands, project instructions, permissions, compaction and tool search in one call, with presets and every piece overridable.