import { n as ClientToolSchema } from "../client-tools-aIBO0Fk7.js";
import {
  ChatInit,
  ChatTransport,
  JSONSchema7,
  Tool,
  UIMessage,
  UIMessageChunk
} from "ai";
import { UseChatOptions, useChat } from "@ai-sdk/react";

//#region src/chat/ws-chat-transport.d.ts
/**
 * Agent-like interface for sending/receiving WebSocket messages.
 * Matches the shape returned by useAgent from agents/react.
 */
interface AgentConnection {
  send: (data: string) => void;
  addEventListener: (
    type: string,
    listener: (event: MessageEvent) => void,
    options?: {
      signal?: AbortSignal;
    }
  ) => void;
  removeEventListener: (
    type: string,
    listener: (event: MessageEvent) => void
  ) => void;
}
type WebSocketChatTransportOptions<ChatMessage extends UIMessage = UIMessage> =
  {
    /** The agent connection from useAgent */ agent: AgentConnection;
    /**
     * Callback to prepare the request body before sending.
     * Can add custom headers, body fields, or credentials.
     */
    prepareBody?: (options: {
      messages: ChatMessage[];
      trigger: "submit-message" | "regenerate-message";
      messageId?: string;
    }) => Promise<Record<string, unknown>> | Record<string, unknown>;
    /**
     * Optional set to track active request IDs.
     * IDs are added when a request starts and removed when it completes.
     * Used by the onAgentMessage handler to skip messages already handled by the transport.
     */
    activeRequestIds?: Set<string>;
    /**
     * Whether generic client-side abort/cancel lifecycle should cancel the
     * server turn. Explicit cancellation via cancelActiveServerTurn() always
     * sends CF_AGENT_CHAT_REQUEST_CANCEL.
     * @default false
     */
    cancelOnClientAbort?: boolean;
  };
/**
 * ChatTransport that sends messages over WebSocket and returns a
 * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.
 * No fake fetch, no Response reconstruction, no double SSE parsing.
 */
declare class WebSocketChatTransport<
  ChatMessage extends UIMessage = UIMessage
> implements ChatTransport<ChatMessage> {
  agent: AgentConnection;
  private prepareBody?;
  private activeRequestIds?;
  private cancelOnClientAbort;
  private _resumeResolver;
  private _resumeNoneResolver;
  private _onStreamPending;
  private _retryResumeProbe;
  private _expectToolContinuation;
  private _abortToolContinuation;
  private _activeServerTurnId;
  private _cancelAttachedStream;
  private _detachResumeStream;
  constructor(options: WebSocketChatTransportOptions<ChatMessage>);
  /**
   * Point the singleton transport at a new Agent connection. A pending resolver
   * belongs to the old Chat/socket generation and must settle before messages
   * from the replacement connection can be consumed (#1914 review).
   */
  setAgent(agent: AgentConnection): void;
  setCancelOnClientAbort(cancelOnClientAbort: boolean): void;
  /**
   * Explicitly cancel the active server turn, if any.
   * This is separate from generic client-side abort/cancel lifecycle so
   * clients can detach locally without stopping server work.
   */
  cancelActiveServerTurn(): boolean;
  private sendCancelFrame;
  private setActiveServerTurn;
  private clearActiveServerTurn;
  /**
   * Mark that the next reconnectToStream() call should attach to a
   * server-initiated tool continuation rather than a page-load resume.
   */
  expectToolContinuation(): void;
  /**
   * Abort the active client-side tool continuation stream, if one is attached
   * to a server request id.
   */
  abortActiveToolContinuation(): boolean;
  /**
   * True when the transport is waiting for a resume handshake.
   */
  isAwaitingResume(): boolean;
  /**
   * Settle and detach the current handshake without interpreting it as a
   * server-idle response. Used when the owning hook/agent generation changes.
   */
  cancelPendingResume(): boolean;
  /**
   * Invalidate all client-side resume state for an obsolete hook/agent
   * generation without cancelling its durable server turn.
   */
  resetResumeState(): void;
  /**
   * Re-send the active handshake request on the latest socket generation. This
   * preserves one AI SDK resume operation while recovering a request/reply lost
   * with the previous WebSocket.
   */
  retryPendingResume(): boolean;
  /**
   * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUMING.
   * If reconnectToStream is waiting, this handles the resume handshake
   * (ACK + stream creation) and returns true. Otherwise returns false
   * so the caller can use its own fallback path.
   */
  handleStreamResuming(data: { id: string }): boolean;
  /**
   * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUME_NONE.
   * If reconnectToStream is waiting, resolves the promise with null
   * immediately (no 5-second timeout). Returns true if handled.
   */
  handleStreamResumeNone(data?: { probeId?: string }): boolean;
  /**
   * Called by onAgentMessage when it receives CF_AGENT_STREAM_PENDING (#1784):
   * the server accepted a turn but its stream has not started yet. If a resume
   * path is awaiting, extend its probe timeout (so it keeps waiting for the
   * eventual STREAM_RESUMING / STREAM_RESUME_NONE instead of resolving null
   * after the short window). Returns true if a waiting path consumed it.
   */
  handleStreamPending(): boolean;
  /**
   * Called by the hook's shared message handler when a server turn finishes
   * outside the currently attached transport stream, such as after local-only
   * client cleanup.
   */
  handleServerTurnCompleted(requestId: string): void;
  /**
   * Register a server turn that is being rendered outside a transport-owned
   * stream, such as the hook's fallback cross-tab/resume observer path.
   */
  observeServerTurn(requestId: string): void;
  sendMessages(options: {
    chatId: string;
    messages: ChatMessage[];
    abortSignal: AbortSignal | undefined;
    trigger: "submit-message" | "regenerate-message";
    messageId?: string;
    body?: object;
    headers?: Record<string, string> | Headers;
    metadata?: unknown;
  }): Promise<ReadableStream<UIMessageChunk>>;
  reconnectToStream(_options: {
    chatId: string;
  }): Promise<ReadableStream<UIMessageChunk> | null>;
  /**
   * Creates a deferred ReadableStream for client-side tool continuations.
   * The stream is returned immediately so AI SDK status becomes "submitted"
   * right after addToolOutput()/addToolApprovalResponse(), then it waits for
   * the server to announce the continuation via STREAM_RESUMING.
   */
  private _createToolContinuationStream;
  /**
   * Creates a ReadableStream that receives resumed stream chunks
   * and forwards them to useChat as UIMessageChunk objects.
   */
  private _createResumeStream;
}
//#endregion
//#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"> & {
  /** 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;
  /**
   * 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
