本页还没有译文
本页 23 段还没译成Español,下面显示的是英文原文。UI
还没翻译译自英文(ai-sdk.dev)本页 23 段都还没译
Harness streams are compatible with AI SDK UI message streams. You can use
useChat() on the client and stream HarnessAgent output from a server route.
The important difference from model-based chat routes is session management.
A harness owns its conversation state, so the route should resume or create a
HarnessAgentSession for the chat id instead of replaying the whole UI message
history into a model.
Client
'use client';
import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport } from 'ai';
import { useState } from 'react';
export default function Page() {
const [input, setInput] = useState('');
const { error, messages, sendMessage, status } = useChat({
id: 'example-chat',
transport: new DefaultChatTransport({
api: '/api/chat',
}),
});
return (
<>
{messages.map(message => (
<div key={message.id}>
<strong>{message.role === 'user' ? 'You: ' : 'AI: '}</strong>
{message.parts.map((part, index) => {
if (part.type === 'text') {
return <span key={index}>{part.text}</span>;
}
if (part.type.startsWith('tool-') || part.type === 'dynamic-tool') {
return <pre key={index}>{JSON.stringify(part, null, 2)}</pre>;
}
return null;
})}
</div>
))}
{error && <div>{error.message}</div>}
<form
onSubmit={event => {
event.preventDefault();
if (input.trim()) {
sendMessage({ text: input });
setInput('');
}
}}
>
<input
value={input}
onChange={event => setInput(event.target.value)}
disabled={status !== 'ready'}
/>
<button type="submit" disabled={status !== 'ready'}>
Send
</button>
</form>
</>
);
}Agent
Define the HarnessAgent on the server:
import { HarnessAgent } from '@ai-sdk/harness/agent';
import { claudeCode } from '@ai-sdk/harness-claude-code';
export const agent = new HarnessAgent({
harness: claudeCode,
instructions: 'You are a helpful coding assistant.',
});Session Store
Persist the opaque resume state returned by session.detach(). If the
turn paused for approval or was otherwise interrupted, that resume state carries
the continuation state internally. The chat ID can also be the harness
sessionId. Here we derive a stable sandboxId from that known chat id. If
you do not derive one, persist the returned sandboxSession.id separately.
import type { HarnessAgentResumeSessionState } from '@ai-sdk/harness/agent';
import {
createVercelNetworkSandboxSession,
resumeVercelNetworkSandboxSession,
} from '@ai-sdk/sandbox-vercel';
const states: Record<string, HarnessAgentResumeSessionState | undefined> = {};
export async function resumeOrCreateSession({
agent,
chatId,
}: {
agent: typeof import('./agent').agent;
chatId: string;
}) {
const resumeFrom = states[chatId];
const sandboxId = `harness-${chatId}`;
const sandboxSession = resumeFrom
? await resumeVercelNetworkSandboxSession({ sandboxId })
: await createVercelNetworkSandboxSession({
sandboxId,
runtime: 'node24',
ports: [4000],
template: await agent.getSandboxTemplate(),
});
const session = await agent.createSession({
sessionId: chatId,
resumeFrom,
sandboxSession,
});
return { session, sandboxSession };
}
export async function detachAndPersist({
chatId,
session,
}: {
chatId: string;
session: Awaited<ReturnType<typeof resumeOrCreateSession>>['session'];
}) {
states[chatId] = await session.detach();
}Use durable storage instead of an in-memory map in production. The creator
always creates a new sandbox and fails on a conflicting sandboxId; only the
resume function reattaches an existing one.
Route
Convert UI messages to model messages, run the harness turn, and convert the result stream back to a UI message stream:
import { agent } from './agent';
import { detachAndPersist, resumeOrCreateSession } from './session-store';
import { getHarnessErrorMessage } from '@ai-sdk/harness/agent';
import {
convertToModelMessages,
createUIMessageStream,
createUIMessageStreamResponse,
toUIMessageStream,
type UIMessage,
} from 'ai';
export async function POST(request: Request) {
const body: {
id?: string;
messages: UIMessage[];
} = await request.json();
if (!body.id) {
return new Response('Missing chat ID', { status: 400 });
}
const chatId = body.id;
const messages = await convertToModelMessages(body.messages);
return createUIMessageStreamResponse({
stream: createUIMessageStream({
execute: async ({ writer }) => {
const { session } = await resumeOrCreateSession({ agent, chatId });
const result = await agent.stream({ session, messages });
writer.merge(
toUIMessageStream({
stream: result.stream,
onError: getHarnessErrorMessage,
onEnd: async () => {
await detachAndPersist({ chatId, session });
},
}),
);
},
onError: getHarnessErrorMessage,
}),
});
}Creating the UI message stream before acquiring the session ensures sandbox,
bootstrap, and harness startup failures are sent as UI error parts instead of
becoming generic HTTP errors. getHarnessErrorMessage preserves reviewed,
client-safe harness messages and masks unknown server errors.
Do not use createAgentUIStreamResponse directly with HarnessAgent unless you
wrap the agent to inject the required session. HarnessAgent.stream() requires
session on every call.
Detach or Stop
Use session.detach() when you want to park the harness runtime and keep the
sandbox warm for the next request. Bridge-backed adapters can usually reattach
or replay efficiently. If the turn is unfinished, detach() includes the turn
continuation state in the returned resume state.
session.stop() saves resume state and stops the harness runtime, but does not
stop a supplied sandbox. The caller owns that network session and should call
its destroy() method when the chat ends, not while a later request needs to
reattach. Preserve the chosen sandboxId across processes.
Rendering Harness Parts
Harness output contains the same UI message part shapes used by AI SDK model streams:
textandreasoningparts for generated content.- typed tool parts such as
tool-bash,tool-read, or a host tool liketool-weather. dynamic-toolparts for dynamic events such asfileChangeandcompaction.
Render typed harness built-ins the same way you render normal AI SDK tool
parts. Check part.state for input-streaming, input-available, and
output-available.
Type-Safe Tool Parts
Until HarnessAgent session options are part of the base Agent call
parameters, infer UI tools from agent.tools:
import type { InferUITools, UIMessage } from 'ai';
import { agent } from './agent';
export type HarnessMessage = UIMessage<
unknown,
never,
InferUITools<typeof agent.tools>
>;Then use useChat<HarnessMessage>() on the client.