New harness adapters and Codex steering
HarnessAgent, introduced in AI SDK 7, exposes one API for running established agent runtimes such as Claude Code, Codex, and Pi. Version 7.1 adds five adapters — Cline, Cursor, fx, GitHub Copilot, and Grok Build — each of which normalizes its runtime's sessions, stream events, tools, and usage into the harness contract, so the integration layer stays unchanged when you swap harnesses.
agent.ts
import { HarnessAgent } from '@ai-sdk/harness/agent';
import { cursor } from '@ai-sdk/harness-cursor';
import { createVercelNetworkSandboxSession } from '@ai-sdk/sandbox-vercel';
const agent = new HarnessAgent({
harness: cursor,
model: 'gpt-5.6-luna',
});
const sandboxSession = await createVercelNetworkSandboxSession({
runtime: 'node24',
ports: [4000],
template: await agent.getSandboxTemplate(),
});
const session = await agent.createSession({ sandboxSession });
const result = await agent.generate({
session,
prompt: 'Inspect this project and summarize its purpose.',
});
The Codex adapter now talks to the Codex app-server, which enables mid-turn steering: another user message can be sent while a turn is still running rather than waiting for it to finish. generateText, streamText, and ToolLoopAgent are steered through a separate mechanism described below.
agent.ts
import { codex } from '@ai-sdk/harness-codex';
import { HarnessAgent } from '@ai-sdk/harness/agent';
const agent = new HarnessAgent({ harness: codex });
const result = await agent.stream({
session,
prompt: 'What is the weather in Paris?',
});
// while the turn is running:
await agent.experimental_steer({
session,
text: 'Actually, I meant Paris, Texas.',
});
Provider-independent tools and tool discovery
Three first-party tools work with any model that supports tool calling. @ai-sdk/tool-bash runs shell commands in the sandbox session passed as experimental_sandbox, and @ai-sdk/tool-web-fetch reads web pages and documents by URL, with domain allowlists or blocklists. For agents with large toolsets, toolSearch() lets the model locate the tools it needs instead of loading every definition up front: tools marked deferLoading: true become available on the next step after a search.
agent.ts
import { createJustBashNetworkSandboxSession } from '@ai-sdk/sandbox-just-bash';
import { createBashTool } from '@ai-sdk/tool-bash';
import { createWebFetchTool } from '@ai-sdk/tool-web-fetch';
import { generateText, isStepCount, toolSearch } from 'ai';
const session = await createJustBashNetworkSandboxSession();
const result = await generateText({
model: 'openai/gpt-6.2-astra',
tools: {
search: toolSearch(),
bash: { ...createBashTool(), deferLoading: true },
webFetch: { ...createWebFetchTool(), deferLoading: true },
},
experimental_sandbox: session.restricted(),
stopWhen: isStepCount(5),
prompt:
'Read https://ai-sdk.dev/docs/introduction ' +
'and write a summary to summary.txt.',
});
Typed decisions and background batches
Agents make many small classification calls — ticket owner, severity, whether a refund is wanted — and writing a structured output call per question is repetitive, with answers that need validation before branching. experimental_decide answers a set of named choice, score, boolean, and bounding-box questions about one shared state in a single call. State can be text, JSON, or a mix of text, files, and JSON, and answers are typed: a choice answer is a union of the option keys you declared. Boolean answers carry a probability, the model's estimate that the answer is true, so routing can use a threshold; native decision models may also return probability distributions for choice and score answers. Use a native decision model where a provider offers one and a language model adapter where it does not.
triage.ts
import { experimental_decide as decide } from 'ai';
const result = await decide({
model: 'openai/gpt-6-luna-decisions',
state: { message: ticket.body },
questions: {
department: {
type: 'choice',
instructions: 'Which team should handle this?',
criteria: {
billing: 'Payments and refunds',
support: 'Other requests',
},
},
severity: {
type: 'score',
instructions: 'How severe is the issue?',
criteria: ['Cosmetic', 'Workaround exists', 'Blocking; no workaround'],
},
requestsRefund: {
type: 'boolean',
instructions: 'Is the customer requesting money back?',
},
},
});
result.answers.department.choice; // 'billing' | 'support'
if (result.answers.requestsRefund.probability >= 0.8) {
// route to the refunds queue
}
Long-running jobs — classifying a backlog, summarizing support tickets, generating catalog images — can move to the background. experimental_startBatch submits text or image requests and returns a serializable batch reference; experimental_getBatchStatus and experimental_getBatchResults read status and results later. Where the provider supports them, experimental_cancelBatch cancels, experimental_listBatches lists, and a webhookUrl requests completion notification.
batch.ts
import { anthropic } from '@ai-sdk/anthropic';
import {
experimental_getBatchResults as getBatchResults,
experimental_startBatch as startBatch,
} from 'ai';
const batch = await startBatch({
provider: anthropic,
requests: [
{
id: 'capital-france',
type: 'text',
model: 'claude-haiku-5-5',
prompt: 'What is the capital of France?',
},
{
id: 'capital-germany',
type: 'text',
model: 'claude-haiku-5-5',
prompt: 'What is the capital of Germany?',
},
],
});
// later, when the batch is completed:
for await (const item of getBatchResults({ provider: anthropic, batch })) {
if (item.type === 'text' && item.status === 'succeeded') {
console.log(item.id, item.text);
}
}
Text requests may mix models and include tool definitions, but client tools are not executed inside a batch — tool calls come back to your application. Batch processing is available for AI Gateway, Anthropic, Google, OpenAI, and xAI.
Steering running calls
Previously, a user who spotted a problem mid-run had to wait for the turn to end or abort and restart. Experimental steering corrects generateText, streamText, and ToolLoopAgent while they run: create the steering object with experimental_createSteering() and pass it as experimental_steering. steer() injects a user message at the next step boundary without interrupting running tools, while queue() holds a follow-up until the agent finishes its current task.
agent.ts
import { experimental_createSteering, isStepCount, streamText } from 'ai';
const steering = experimental_createSteering();
const result = streamText({
model: 'openai/gpt-6.2-astra',
tools: { weather },
stopWhen: isStepCount(10),
prompt: 'What is the weather in Paris?',
experimental_steering: steering,
});
// when the user sends a correction while the agent is running:
await steering.steer('I meant Paris, Texas.');
// a follow-up that waits until the current task is finished:
steering.queue('Then compare it with the weather in Austin.');
Both methods resolve with an outcome indicating whether the message was delivered. Passing an id makes retries safe, since resending with the same id returns the first message's outcome. Steering messages arrive as steering-message stream parts, are added to the assistant message by useChat, and are listed on each step so the full conversation can be persisted.
Bounding and recovering agent runs
Production agents need limits on tool execution, step-level settings, and a path back from a provider failure that lands mid-stream. AI SDK 7.1 adds tool concurrency caps, per-step model settings, step error hooks, a first-content timeout, mid-stream retries, and a low-memory streaming mode.
Limiting parallel tool calls
Tool calls within a step run concurrently by default, which breaks down when a later call depends on side effects from an earlier one. The new toolCallConcurrency option on generateText, streamText, and ToolLoopAgent caps how many run in parallel; set it to 1 to execute them sequentially in the order the model generated them.
agent.ts
const result = await generateText({
model,
tools,
prompt: 'Update the file, then read it.',
toolCallConcurrency: 1,
});
Running tool calls one at a time
Model settings per step
prepareStep can now override call settings such as temperature, maxOutputTokens, and reasoning for a single step. One use case: tighter, more deterministic sampling during tool-calling steps than for the final response.
agent.ts
const agent = new ToolLoopAgent({
model,
temperature: 0.7,
tools,
prepareStep: async ({ stepNumber }) => {
if (stepNumber === 0) {
return { temperature: 0, maxOutputTokens: 300 };
}
return {};
},
});
Overriding call settings for the first step
Failed steps and stalled streams
When a step fails before producing a result — a provider request throws, or a stream closes without output — onStepError now fires in place of onStepEnd. Separately, the firstChunkMs timeout aborts any step whose stream opens but delivers no content within the limit.
agent.ts
const result = streamText({
model,
prompt: 'Invent a new holiday and describe its traditions.',
timeout: {
firstChunkMs: 10000, // 10 seconds for first content in each step
},
});
Aborting a step when no content arrives within 10 seconds
Retrying after streaming starts
maxRetries covers only failures that occur before a response begins streaming. For provider errors that surface mid-stream, streamText gains an opt-in streamRetries option. Each retry reruns only the failed model step; earlier completed steps, their tool results, and output already emitted to the stream are kept.
app.ts
const result = streamText({
model,
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
streamRetries: 2,
});
Retrying provider errors after streaming has started
Low-memory streaming
By default streamText keeps a copy of the stream for replay and holds onto the final output, overhead that long single-pass streams don't need. experimental_streamTextLowMemory takes the same options without the replay buffer, and for plain text streaming it also avoids retaining the full generated text.
app.ts
import { experimental_streamTextLowMemory as streamTextLowMemory } from 'ai';
const result = streamTextLowMemory({
model,
prompt: 'Describe the history of astronomy.',
});
for await (const delta of result.textStream) {
process.stdout.write(delta);
}
console.log(await result.totalUsage);
Streaming a long response without a replay buffer
WorkflowAgent across process boundaries
WorkflowAgent now supports non-streaming execution through generate(), and gains an OpenTelemetry bridge that presents suspend-and-resume runs as a single trace.
Durable execution without a stream
Previously WorkflowAgent could only stream. generate() returns the completed result for durable execution, running the same durable tool loop as stream().
workflow.ts
export async function summarize(modelId: string, text: string) {
'use workflow';
const agent = new WorkflowAgent({
model: modelId,
instructions: 'Summarize the text briefly.',
});
const result = await agent.generate({ prompt: text });
return { text: result.text, usage: result.usage };
}
Running a durable agent without streaming
Stitching a split run into one trace
A WorkflowAgent run may suspend and resume in different processes, which makes the full execution hard to read as one trace. The durable OpenTelemetry bridge joins those segments into a single agent operation and keeps the original timestamps on every model and tool span.
instrumentation.ts
import { OpenTelemetry, OpenTelemetryIdGenerator } from '@ai-sdk/otel';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { registerTelemetry } from 'ai';
const durable = new OpenTelemetryIdGenerator();
new NodeSDK({ idGenerator: durable, sampler: durable }).start();
registerTelemetry(new OpenTelemetry({ durable }));
Reporting a durable WorkflowAgent run as one trace
Installing AI SDK 7.1
pnpm i ai



