UNPKG

agents

Version:

A home for your AI agents

466 lines (464 loc) 17 kB
import { n as ClientToolSchema } from "../client-tools-aIBO0Fk7.js"; import { n as WebSocketChatTransport, r as WebSocketChatTransportOptions, t as AgentConnection } from "../ws-chat-transport-UNRIS2xl.js"; import { ChatInit, JSONSchema7, Tool, UIMessage } from "ai"; import { UseChatOptions, useChat } from "@ai-sdk/react"; //#region src/chat/react.d.ts type AgentConnectionErrorLike = Error & { code: number; reason: string; wasClean: boolean; }; /** * JSON Schema type for tool parameters. * Re-exported from the AI SDK for convenience. * @deprecated Import JSONSchema7 directly from "ai" instead. Will be removed in the next major version. */ type JSONSchemaType = JSONSchema7; /** * Definition for a tool that can be executed on the client. * Tools with an `execute` function are automatically registered with the server. * * **For most apps**, define tools on the server with `tool()` from `"ai"` — * you get full Zod type safety and simpler code. Use `onToolCall` in * `useAgentChat` for tools that need browser-side execution. * * **For SDKs and platforms** where the tool surface is determined dynamically * by the embedding application at runtime, this type lets the client register * tools the server does not know about at deploy time. * * Note: Uses `parameters` (JSONSchema7) because client tools must be * serializable for the wire format. Zod schemas cannot be serialized. */ type AITool<Input = unknown, Output = unknown> = { /** Human-readable description of what the tool does */ description?: Tool["description"] /** JSON Schema defining the tool's input parameters */; parameters?: JSONSchema7; /** * @deprecated Use `parameters` instead. Will be removed in a future version. */ inputSchema?: JSONSchema7; /** * Function to execute the tool on the client. * If provided, the tool schema is automatically sent to the server. */ execute?: (input: Input) => Output | Promise<Output>; }; /** * Extracts tool schemas from tools that have client-side execute functions. * These schemas are automatically sent to the server with each request. * * Called internally by `useAgentChat` when `tools` are provided. * Most apps do not need to call this directly. * * @param tools - Record of tool name to tool definition * @returns Array of tool schemas to send to server, or undefined if none */ declare function extractClientToolSchemas( tools?: Record<string, AITool<unknown, unknown>> ): ClientToolSchema[] | undefined; /** * Map internal tool part states to simplified UI-relevant states. * * @example * ```tsx * import { isToolUIPart } from "ai"; * import { getToolPartState } from "@cloudflare/ai-chat/react"; * * if (isToolUIPart(part)) { * const state = getToolPartState(part); * if (state === "complete") { ... } * if (state === "waiting-approval") { ... } * } * ``` */ declare function getToolPartState( part: UIMessage["parts"][number] ): | "loading" | "streaming" | "waiting-approval" | "approved" | "complete" | "error" | "denied"; /** Get the tool call ID from a tool UI part. */ declare function getToolCallId(part: UIMessage["parts"][number]): string; /** Get the tool input from a tool UI part (if available). */ declare function getToolInput( part: UIMessage["parts"][number] ): unknown | undefined; /** Get the tool output from a tool UI part (if available). */ declare function getToolOutput( part: UIMessage["parts"][number] ): unknown | undefined; /** Get the approval info from a tool UI part (if in approval state). */ declare function getToolApproval(part: UIMessage["parts"][number]): | { id: string; approved?: boolean; } | undefined; /** * Fetch messages from an agent's `/get-messages` HTTP endpoint. * * Use in framework route loaders to prefetch messages before the component * tree mounts, or anywhere you need messages outside a React hook. * * @example Standard routing * ```typescript * import { getAgentMessages } from "@cloudflare/ai-chat/react"; * * const messages = await getAgentMessages({ * host: "https://my-app.workers.dev", * agent: "ChatAgent", * name: "session-123" * }); * ``` * * @example With basePath (custom URL) * ```typescript * const messages = await getAgentMessages({ * url: "https://my-app.workers.dev/custom/path/get-messages" * }); * ``` */ declare function getAgentMessages<M extends UIMessage = UIMessage>( options: | { host: string; agent: string; name: string; credentials?: RequestCredentials; headers?: HeadersInit; } | { url: string; credentials?: RequestCredentials; headers?: HeadersInit; } ): Promise<M[]>; type GetInitialMessagesOptions = { agent: string; name: string; url?: string; }; type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> & UseChatOptions<M>; /** * Options for preparing the send messages request. * Used by prepareSendMessagesRequest callback. */ type PrepareSendMessagesRequestOptions< ChatMessage extends UIMessage = UIMessage > = { /** The chat ID */ id: string /** Messages to send */; messages: ChatMessage[] /** What triggered this request */; trigger: | "submit-message" | "regenerate-message" /** ID of the message being sent (if applicable) */; messageId?: string /** Request metadata */; requestMetadata?: unknown /** Current body (if any) */; body?: Record<string, unknown> /** Current credentials (if any) */; credentials?: RequestCredentials /** Current headers (if any) */; headers?: HeadersInit /** API endpoint */; api?: string; }; /** * Return type for prepareSendMessagesRequest callback. * Allows customizing headers, body, and credentials for each request. * All fields are optional; only specify what you need to customize. */ type PrepareSendMessagesRequestResult = { /** Custom headers to send with the request */ headers?: HeadersInit /** Custom body data to merge with the request */; body?: Record<string, unknown> /** Custom credentials option */; credentials?: RequestCredentials /** Custom API endpoint */; api?: string; }; /** * Options for addToolOutput function */ type AddToolOutputOptions = { /** The ID of the tool call to provide output for */ toolCallId: string /** The name of the tool (optional, for type safety) */; toolName?: string /** The output to provide */; output?: unknown /** Override the tool part state (e.g. "output-error" for custom denial) */; state?: | "output-available" | "output-error" /** Error message when state is "output-error" */; errorText?: string; }; /** * Callback for handling client-side tool execution. * Called when a tool without server-side execute is invoked. */ type OnToolCallCallback = (options: { /** The tool call that needs to be handled */ toolCall: { toolCallId: string; toolName: string; input: unknown; } /** Function to provide the tool output (or signal an error/denial) */; addToolOutput: (options: Omit<AddToolOutputOptions, "toolName">) => void; }) => void | Promise<void>; /** * Options for the useAgentChat hook */ type UseAgentChatOptions< State = unknown, ChatMessage extends UIMessage = UIMessage > = Omit< UseChatParams<ChatMessage>, "fetch" | "onToolCall" | "throttle" | "experimental_throttle" > & { /** Agent connection from useAgent (accepts both typed and untyped agents) */ agent: AgentConnection & { agent: string; name: string; path?: ReadonlyArray<{ agent: string; name: string; }>; connectionError?: AgentConnectionErrorLike | null; getHttpUrl: () => string; }; getInitialMessages?: | undefined | null | (( options: GetInitialMessagesOptions ) => Promise<ChatMessage[]>) /** Request credentials */; credentials?: RequestCredentials /** Request headers */; headers?: HeadersInit; /** * Milliseconds to coalesce chat state updates before re-rendering, * defaulting to 50. * * Streaming writes chat state once per chunk, so without a throttle a fast * burst of chunks renders once per chunk. The first chunk is never delayed. * Pass `false` to render every chunk as it arrives. */ throttle?: number | false /** @deprecated Use `throttle`. */; experimental_throttle?: number; /** * Callback for handling client-side tool execution. * Called when a tool without server-side `execute` is invoked by the LLM. * * Use this for: * - Tools that need browser APIs (geolocation, camera, etc.) * - Tools that need user interaction before providing a result * - Tools requiring approval before execution * * @example * ```typescript * onToolCall: async ({ toolCall, addToolOutput }) => { * if (toolCall.toolName === 'getLocation') { * const position = await navigator.geolocation.getCurrentPosition(); * addToolOutput({ * toolCallId: toolCall.toolCallId, * output: { lat: position.coords.latitude, lng: position.coords.longitude } * }); * } * } * ``` */ onToolCall?: OnToolCallCallback; /** * @deprecated Use `onToolCall` callback instead for automatic tool execution. * @description Whether to automatically resolve tool calls that do not require human interaction. * @experimental */ experimental_automaticToolResolution?: boolean; /** * Tools that can be executed on the client. Tool schemas are automatically * sent to the server and tool calls are routed back for client execution. * * **For most apps**, define tools on the server with `tool()` from `"ai"` * and handle client-side execution via `onToolCall`. This gives you full * Zod type safety and keeps tool definitions in one place. * * **For SDKs and platforms** where tools are defined dynamically by the * embedding application at runtime, this option lets the client register * tools the server does not know about at deploy time. */ tools?: Record<string, AITool<unknown, unknown>>; /** * @deprecated Use `needsApproval` on server-side tools instead. * @description Manual override for tools requiring confirmation. * If not provided, will auto-detect from tools object (tools without execute require confirmation). */ toolsRequiringConfirmation?: string[]; /** * When true (default), the server automatically continues the conversation * after receiving client-side tool results or approvals, similar to how * server-executed tools work with maxSteps in streamText. The continuation * is merged into the same assistant message. * * When false, the client must call sendMessage() after tool results * to continue the conversation, which creates a new assistant message. * * @default true */ autoContinueAfterToolResult?: boolean; /** * @deprecated Use `sendAutomaticallyWhen` from AI SDK instead. * * When true (default), automatically sends the next message only after * all pending confirmation-required tool calls have been resolved. * When false, sends immediately after each tool result. * * Only applies when `autoContinueAfterToolResult` is false. * * @default true */ autoSendAfterAllConfirmationsResolved?: boolean; /** * Set to false to disable automatic stream resumption. * @default true */ resume?: boolean; /** * Whether generic client-side stream abort/cleanup should cancel the server * turn. By default, client cleanup is local-only so the server turn can * continue and be resumed on reconnect. Explicit stop() always cancels the * server turn. * * @default false */ cancelOnClientAbort?: boolean; /** * Whether `setMessages` should also send the full client transcript to the * server as `CF_AGENT_CHAT_MESSAGES`. This is useful for flat transcript * stores such as `AIChatAgent`, but should be disabled for server-authoritative * hosts whose client messages are only a projection of richer storage. * * @default true */ syncMessagesToServer?: boolean; /** * Custom data to include in every chat request body. * Accepts a static object or a function that returns one (for dynamic values). * These fields are available in `onChatMessage` via `options.body`. * * @example * ```typescript * // Static * body: { timezone: "America/New_York", userId: "abc" } * * // Dynamic (called on each send) * body: () => ({ token: getAuthToken(), timestamp: Date.now() }) * ``` */ body?: | Record<string, unknown> | (() => Record<string, unknown> | Promise<Record<string, unknown>>); /** * Callback to customize the request before sending messages. * For most cases, use the `body` option instead. * Use this for advanced scenarios that need access to the messages or trigger type. * * Note: Client tool schemas are automatically sent when tools have `execute` functions. * This callback can add additional data alongside the auto-extracted schemas. */ prepareSendMessagesRequest?: ( options: PrepareSendMessagesRequestOptions<ChatMessage> ) => | PrepareSendMessagesRequestResult | Promise<PrepareSendMessagesRequestResult>; }; /** * React hook for building AI chat interfaces using an Agent * @param options Chat options including the agent connection * @returns Chat interface controls and state with added clearHistory method */ /** * Automatically detects which tools require confirmation based on their configuration. * Tools require confirmation if they have no execute function AND are not server-executed. * @param tools - Record of tool name to tool definition * @returns Array of tool names that require confirmation * * @deprecated Use `needsApproval` on server-side tools instead. */ declare function detectToolsRequiringConfirmation( tools?: Record<string, AITool<unknown, unknown>> ): string[]; declare function useAgentChat< State = unknown, ChatMessage extends UIMessage = UIMessage >( options: UseAgentChatOptions<State, ChatMessage> ): Omit<ReturnType<typeof useChat<ChatMessage>>, "addToolOutput"> & { clearHistory: () => void; /** * Provide output for a tool call. Use this for tools that require user interaction * or client-side execution. */ addToolOutput: (opts: AddToolOutputOptions) => void; /** * Whether a server-initiated stream (e.g. from `saveMessages`, * auto-continuation, or another tab) is currently active, OR a * client-side tool call is awaiting resolution via `onToolCall`. * Covers the full "turn-in-progress" window from the consumer's * perspective, including the gap between the model emitting a * client-tool call and the server pushing a continuation after * `addToolOutput`. This is independent of the AI SDK's `status` * which only tracks client-initiated request/response cycles. */ isServerStreaming: boolean; /** * Convenience flag: `true` when either the client-initiated stream * (`status === "streaming"`) or a server-initiated stream is active. * Use this for showing a universal streaming indicator. */ isStreaming: boolean; /** * `true` while a durable chat turn is being recovered (interrupted by a * deploy/eviction or a stream-stall watchdog abort and now resuming, #1620). * Distinct from `isStreaming` — a recovering turn isn't producing tokens yet, * so a client can show a "recovering…" hint instead of looking frozen. Most * UIs treat `isStreaming || isRecovering` as "busy". Driven by the server's * `CF_AGENT_CHAT_RECOVERING` frames (also replayed on connect for * `@cloudflare/think`); cleared automatically on the next stream or terminal. */ isRecovering: boolean; /** * `true` when the current `status`/`isServerStreaming` activity is * driven by a server-pushed tool continuation (i.e. the server is * auto-continuing the conversation after `addToolOutput` or * `addToolApprovalResponse`) rather than a fresh user submission. * * Use this to disambiguate "user just sent a new message, awaiting * first token" from "mid-turn tool round-trip" — e.g. when you want * a typing indicator only for the former: * * ```tsx * const showTypingIndicator = status === "submitted" && !isToolContinuation; * ``` * * See issue #1365. */ isToolContinuation: boolean; connectionError: AgentConnectionErrorLike | null; }; //#endregion export { AITool, type AgentConnection, type ClientToolSchema, JSONSchemaType, OnToolCallCallback, PrepareSendMessagesRequestOptions, PrepareSendMessagesRequestResult, UseAgentChatOptions, WebSocketChatTransport, type WebSocketChatTransportOptions, detectToolsRequiringConfirmation, extractClientToolSchemas, getAgentMessages, getToolApproval, getToolCallId, getToolInput, getToolOutput, getToolPartState, useAgentChat }; //# sourceMappingURL=react.d.ts.map