页面简介
Create and run AI SDK HarnessAgent sessions.
正文摘录
AI SDK HarnessesMenuHarnessAgentCopy for LLMView MarkdownAsk AI about this pageHarnessAgent is an AI SDK Agent implementation backed by a harness adapter. It gives you generate() and stream() methods that return AI SDK-compatible results while a preconfigured harness powers these results. Installation Install the core harness package, a harness adapter, and a sandbox adapter: pnpmnpmyarnbun$ pnpm add @ai-sdk/harness @ai-sdk/harness-claude-code @ai-sdk/sandbox-vercel Bridge-backed harnesses such as Claude Code and Codex require using a real network sandbox like @ai-sdk/sandbox-vercel. Host-runtime harnesses such as Pi can also run with @ai-sdk/sandbox-just-bash because they do not need a sandbox-exposed port. Create an Agent import { HarnessAgent } from '@ai-sdk/harness/agent'; import { claudeCode } from '@ai-sdk/harness-claude-code'; export const agent = new HarnessAgent({ harness: claudeCode, model: 'claude-sonnet-4-6', instructions: 'You are a careful coding assistant. Prefer small changes and explain tradeoffs.', }); Construct the agent at module scope. It holds configuration, not a live session. Live state belongs to HarnessAgentSession. Create a sandbox session separately and pass it to agent.createSession(): import { createVercelNetworkSandboxSession } from '@ai-sdk/sandbox-vercel'; const sandboxSession = await createVercelNetworkSandboxSession({ runtime: 'node24', ports: [4000], template: await agent.getSandboxTemplate(), }); Set model to select the model that the harness runtime uses. Model identifiers are specific to each harness. When omitted, the harness uses its default model. The model is applied per turn, so prepareCall can replace it between turns. To use this agent, ensure environment variables with sandbox and harness credentials are set. Run a Turn const session = await agent.createSession({ sandboxSession }); let exitCode = 0; try { const result = await agent.generate({ session, prompt: 'Create a short TODO.md for this repository.', }); console.log(result.text); } catch (err) { exitCode = 1; console.error(err); } finally { await session.destroy(); await sandboxSession.destroy(); process.exit(exitCode); } generate() drains the turn and returns a GenerateTextResult. Use stream() for incremental output: const session = await agent.createSession({ sandboxSession }); let exitCode = 0; try { const result = await agent.stream({ session, prompt: 'Create a short TODO.md for this repository.', }); for await (const part of result.stream) { if (part.type === 'text-delta') { process.stdout.write(part.text); } } } catch (err) { exitCode = 1; console.error(err); } finally { await session.destroy(); await sandboxSession.destroy(); process.exit(exitCode); } Image Inputs For harness adapters that support images, you can include an image as a file part in the latest user message. Set mediaType to the image's MIME type: import { readFileSync } from 'node:fs'; const result = await agent.generate({ session, messages: [ { role: 'user', content: [ { type: 'text', text: 'Describe the image in one sentence.', }, { type: 'file', mediaType: 'image/png', data: readFileSync('image.png'), }, ], }, ], }); For image input support, see the adapter capability table. Lifecycle Callbacks Configure lifecycle callbacks on HarnessAgent to observe agent calls, model steps, and tool executions: const agent = new HarnessAgent({ harness: claudeCode, tools: { weather }, onStart: event => console.log('call started', event.callId), onStepStart: event => console.log('step started', event.stepNumber), onLanguageModelCallStart: event => console.log('model call started', event.modelId), onLanguageModelCallEnd: event => console.log('model call ended', event.finishReason), onToolExecutionStart: event => console.log('tool started', event.toolCall.toolName), onToolExecutionEnd: event => console.log('tool ended', event.toolOutput.type), onStepEnd: step => console.log('step ended', step.stepNumber), onEnd: event => console.log('call ended', event.finishReason), }); Callbacks configured on individual generate() and stream() calls are invoked in addition to settings callbacks, with settings callbacks invoked first. Callback errors are ignored and do not change agent execution. Harness runtimes execute their built-in tools internally. For those tools, onToolExecutionStart and onToolExecutionEnd describe the logical tool lifecycle after the runtime reports the result. The callbacks are still delivered before the tool result is published to the result stream. Runtime Context Set runtimeContext on HarnessAgent to make application context available to every turn. Use prepareCall to replace it for each new prompt turn. The prepared context is available through generate() and stream() and remains the same during in-memory continuations with continueGenerate() and continueStream(). Lifecycle callbacks receive the full context, and it is also available on each result's finalStep.runtimeContext. const agent = new HarnessAgent({ harness: claudeCode, runtimeContext: { conversationId: 'conversation-123', userId: 'user-456', }, telemetry: { includeRuntimeContext: { conversationId: true, }, }, onEnd: ({ runtimeContext }) => { console.log(runtimeContext.userId); }, }); Runtime context is excluded from telemetry by default. Use telemetry.includeRuntimeContext to allowlist individual top-level properties; only properties set to true are sent to telemetry integrations. Lifecycle callbacks and results still receive the full context, so avoid storing secrets that those consumers should not access. Generate Structured Output Set output when constructing HarnessAgent to require the same typed output on every turn. The agent converts the output specification to JSON Schema for the harness adapter, validates the completed response, and returns the parsed value through result.output. import { HarnessAgent } from '@ai-sdk/harness/agent'; import { Output } from 'ai'; import { z } from 'zod'; const agent = new HarnessAgent({ harness: claudeCode, output: Output.object({ schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array( z.object({ name: z.string(), amount: z.number(), unit: z.enum(['oz', 'fl oz', 'cup', 'gallon']), }), ), steps: z.array(z.string()), }), }), }), }); const session = await agent.createSession({ sandboxSession }); try { const result = await agent.generate({ session, prompt: 'Generate a lasagna recipe.', }); console.dir(result.output, { depth: Infinity }); } finally { await session.destroy(); } With stream(), read partialOutputStream for incrementally parsed values and await result.output for the validated final value. Structured data also remains available as JSON in the normal text and stream surfaces; adapters do not add it to the finish part. Harness structured output requires a schema. Schema-less Output.json() and adapters or runtime configurations that cannot enforce the schema throw HarnessCapabilityUnsupportedError; see the adapter capability table. Messages and History A harness session owns its native conversation history. When you pass messages or a message-array prompt, HarnessAgent takes the latest user message as the fresh input for the turn. It does not replay the full prior conversation into the harness. A trailing tool message is handled differently: tool approval responses and client-provided tool results continue the unfinished harness turn that produced the corresponding request or tool call. This is different from model calls, where the application usually sends the full message history. In chat routes, persist and resume the harness session instead of relying on message replay. Reading the Runtime's Own History The runtime's conversation can grow outside your process — the same conversation continued interactively in the agent's own CLI, for instance — and the live event stream never sees those exchanges. Adapters that can reach their runtime's store expose them through session.readHistory(): const { messages, cursor } = await session.readHistory(); // Messages use role/content shapes. Adapter-specific details, including the // runtime's raw record, are available under harnessMetadata. // Later: read only what was recorded since. const delta = await session.readHistory({ since: cursor }); History reads are adapter-specific; see the adapter capability table before calling this method. readHistory() throws HarnessCapabilityUnsupportedError when the adapter does not implement history reads, and HarnessHistoryUnavailableError when it does but cannot reach the runtime's store from this environment (for example, the store lives inside a remote sandbox). A conversation with no recorded messages yet is not an error; it resolves to an empty messages array. Session Lifecycle End every session explicitly: session.destroy() stops the runtime and discards resumability. session.detach() parks the runtime, returns resume state, and leaves a supplied sandbox running for a later attach. If the turn is unfinished, the resume state includes the continuation state. session.stop() saves resume state, then stops the runtime. If the turn is unfinished, the resume state includes the continuation state. session.suspendTurn() is for advanced active-turn continuation across a process boundary. session.hasUnfinishedTurn() reports whether the current turn must be continued or suspended before the session accepts a new prompt. Use destroy() for one-off scripts and tests. Use detach() or stop() for HTTP routes that need multi-turn continuity. Change Settings Between Turns Use callOptionsSchema and prepareCall to derive model, skills, instructions, tools, and runtimeContext for each new turn. This follows the same call-options pattern as ToolLoopAgent: import { HarnessAgent } from '@ai-sdk/harness/agent'; import { tool } from 'ai'; import { z } from 'zod'; const getPolicy = tool({ description: 'Look up the active project policy.', inputSchema: z.object({}), execute: async () => 'Keep public APIs backward compatible.', }); const agent = new HarnessA