diff --git a/apps/docs/mint.json b/apps/docs/mint.json
index 0a76a8a1..2d7dfa9e 100644
--- a/apps/docs/mint.json
+++ b/apps/docs/mint.json
@@ -27,11 +27,6 @@
},
"anchors": [
- {
- "name": "Documentation",
- "icon": "book-open-cover",
- "url": "https://docs.copilotkit.ai"
- },
{
"name": "Community",
"icon": "slack",
@@ -50,7 +45,35 @@
},
{
"group": "API Reference",
- "pages": ["reference/copilotkit-core"]
+ "pages": [
+ {
+ "group": "Core",
+ "pages": [
+ "reference/copilotkit-core",
+ "reference/proxied-copilot-runtime-agent",
+ "reference/frontend-tool"
+ ]
+ },
+ {
+ "group": "React",
+ "pages": [
+ {
+ "group": "Providers",
+ "pages": [
+ "reference/copilotkit-provider",
+ "reference/copilot-chat-configuration-provider"
+ ]
+ },
+ {
+ "group": "Hooks",
+ "pages": [
+ "reference/use-copilot-kit",
+ "reference/use-agent"
+ ]
+ }
+ ]
+ }
+ ]
}
],
"footerSocials": {
diff --git a/apps/docs/reference/copilot-chat-configuration-provider.mdx b/apps/docs/reference/copilot-chat-configuration-provider.mdx
new file mode 100644
index 00000000..8348daee
--- /dev/null
+++ b/apps/docs/reference/copilot-chat-configuration-provider.mdx
@@ -0,0 +1,179 @@
+---
+title: CopilotChatConfigurationProvider
+description: "CopilotChatConfigurationProvider API Reference"
+---
+
+`CopilotChatConfigurationProvider` is a React context provider that manages configuration for chat UI components,
+including labels, agent ID, and thread ID. It enables customization of all text labels in the chat interface and
+provides context for chat components to access configuration values.
+
+## What is CopilotChatConfigurationProvider?
+
+The CopilotChatConfigurationProvider:
+
+- Manages UI labels for all chat components (placeholders, button labels, etc.), allowing for localization or
+ customization of the chat interface.
+- Lets you to access the current `agentId` and `threadId`
+- Supports nested configuration with proper inheritance
+
+## Basic Usage
+
+Wrap your chat components with the provider to customize configuration:
+
+```tsx
+import { CopilotChatConfigurationProvider } from "@copilotkitnext/react";
+
+function App() {
+ return (
+
+ {/* Your chat components */}
+
+ );
+}
+```
+
+## Props
+
+### threadId
+
+`string` **(required)**
+
+A unique identifier for the conversation thread. This is used to maintain conversation history and context.
+
+```tsx
+{children}
+```
+
+### agentId
+
+`string` **(optional)**
+
+The ID of the agent to use for this chat context. If not provided, defaults to `"default"`.
+
+```tsx
+
+ {children}
+
+```
+
+### labels
+
+`Partial` **(optional)**
+
+Custom labels for chat UI elements. Any labels not provided will use the default values.
+
+```tsx
+
+ {children}
+
+```
+
+### children
+
+`ReactNode` **(required)**
+
+The React components that will have access to the chat configuration context.
+
+## Using with CopilotChat
+
+The `CopilotChat` component automatically creates its own `CopilotChatConfigurationProvider` internally. When using
+`CopilotChat`, you can pass configuration directly as props:
+
+```tsx
+
+```
+
+### Priority System
+
+When `CopilotChat` is used within an existing `CopilotChatConfigurationProvider`, values are merged with the following
+priority (highest to lowest):
+
+1. Props passed directly to `CopilotChat`
+2. Values from the outer `CopilotChatConfigurationProvider`
+3. Default values
+
+Example:
+
+```tsx
+
+
+
+```
+
+## Accessing Configuration
+
+Use the `useCopilotChatConfiguration` hook to access configuration values in your components:
+
+```tsx
+import { useCopilotChatConfiguration } from "@copilotkitnext/react";
+
+function MyComponent() {
+ const config = useCopilotChatConfiguration();
+
+ if (!config) {
+ // No provider found
+ return null;
+ }
+
+ return (
+
+
Agent: {config.agentId}
+
Thread: {config.threadId}
+
Labels: {JSON.stringify(config.labels)}
+
+ );
+}
+```
+
+Note: The hook returns `null` if no provider is found in the component tree.
+
+## Localization Example
+
+The provider is ideal for implementing localization:
+
+```tsx
+import { useTranslation } from "react-i18next";
+
+function LocalizedChat() {
+ const { t } = useTranslation();
+
+ return (
+
+
+
+ );
+}
+```
diff --git a/apps/docs/reference/copilot-chat.mdx b/apps/docs/reference/copilot-chat.mdx
new file mode 100644
index 00000000..656c6267
--- /dev/null
+++ b/apps/docs/reference/copilot-chat.mdx
@@ -0,0 +1,116 @@
+---
+title: CopilotChat
+description: "CopilotChat Component API Reference"
+---
+
+`CopilotChat` is a React component that provides a complete chat interface for interacting with AI agents. It handles
+message display, user input, tool execution rendering, and agent communication automatically.
+
+## What is CopilotChat?
+
+The CopilotChat component:
+
+- Provides a complete chat UI out of the box
+- Manages conversation threads and message history
+- Automatically connects to agents and handles message routing
+- Renders tool executions with visual feedback
+- Supports customization through props and slots
+- Handles auto-scrolling and responsive layouts
+
+## Basic Usage
+
+```tsx
+import { CopilotChat, CopilotKitProvider } from "@copilotkitnext/react";
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## Props
+
+### agentId
+
+`string` **(optional)**
+
+The ID of the agent to connect to. Defaults to `"default"`.
+
+```tsx
+
+```
+
+### threadId
+
+`string` **(optional)**
+
+The conversation thread ID. If not provided, a new thread ID is automatically generated.
+
+```tsx
+
+```
+
+### labels
+
+`Partial` **(optional)**
+
+Customize the text labels used throughout the chat interface.
+
+```tsx
+
+```
+
+### autoScroll
+
+`boolean` **(optional, default: true)**
+
+Automatically scroll to the bottom when new messages appear.
+
+```tsx
+
+```
+
+### className
+
+`string` **(optional)**
+
+CSS class name for the root container.
+
+```tsx
+
+```
+
+### Component Slots
+
+CopilotChat supports slot customization for various parts of the UI:
+
+```tsx
+
+```
+
+## Auto-scrolling Behavior
+
+CopilotChat automatically scrolls to the bottom when:
+
+- New messages are added
+- The user is already near the bottom
+- `autoScroll` prop is true (default)
+
+The scroll-to-bottom button appears when the user scrolls up and new content is available.
diff --git a/apps/docs/reference/copilotkit-core.mdx b/apps/docs/reference/copilotkit-core.mdx
index c8db2aea..2fffd078 100644
--- a/apps/docs/reference/copilotkit-core.mdx
+++ b/apps/docs/reference/copilotkit-core.mdx
@@ -4,47 +4,86 @@ description: "CopilotKitCore API Reference"
---
`CopilotKitCore` is the client-side cross-framework orchestration layer that coordinates communication between your
-application's UI, the remote Copilot runtime and using locally defined agents for development.
+application's UI, agents abd the remote Copilot runtime.
+
+## Architecture Overview
+
+```mermaid
+graph TB
+ subgraph Framework["Framework Layer"]
+ React["**CopilotKit React** Components & Hooks"]
+ Angular["**CopilotKit Angular** Directives & Services"]
+ Vue["**CopilotKit ...** Future frameworks"]
+ end
+
+ subgraph CoreLayer["Core Layer"]
+ Core["**CopilotKitCore** Cross-framework Orchestration State Management & Agent Coordination"]
+ end
+
+ subgraph RuntimeLayer["Runtime Layer"]
+ Runtime["**CopilotRuntime** AI Agent Execution Backend Services"]
+ end
+
+ React --> Core
+ Angular --> Core
+ Vue -.-> Core
+ Core <--> Runtime
+```
## What does CopilotKitCore do?
CopilotKitCore solves several complex challenges in building AI-powered applications:
-1. **Tool Execution Orchestration**: When agents need to call frontend tools (like updating UI or accessing browser
- APIs), CopilotKitCore handles the entire lifecycle - parsing arguments, executing handlers, and automatically
- re-running agents with tool results
-2. **Unified Agent Management**: It manages remote server-side agents in production, while allowing you to define local
- agents for development.
-3. **State Synchronization**: It maintains consistent state across your application, ensuring all components have access
- to the latest agents, tools, and context
+1. **Agent Orchestration**: Handles the entire lifecycle of running AI agents, from starting the agent and executing
+ tools, to providing tool results, handling follow-ups and handling streaming updates to the UI.
+2. **Runtime Connection**: Manages connecting to and synchronizing with the remote `CopilotRuntime`.
+3. **State Synchronization**: Maintains consistent state across your application, ensuring all components have access to
+ the latest agents, tools, and context
4. **Framework Independence**: Works with any frontend framework, providing a consistent API whether you're using React,
Angular, Vue, or vanilla JavaScript
-At its heart, CopilotKitCore maintains the authoritative state for three critical elements:
+At its heart, CopilotKitCore maintains the authoritative state for these critical elements:
- **Agents**: Both local and remote AI agents that power your application's intelligence
+- **Context**: Additional information that agents can use to make more informed decisions
- **Frontend Tools**: Functions that agents can call to interact with your UI
+- **Properties and Headers**: Application-specific data forwarded to agents as additional properties or HTTP headers
- **Runtime Metadata**: Connection status, versioning, and configuration details
## Creating a CopilotKitCore Instance
-When you instantiate CopilotKitCore, you're setting up the foundation for all AI interactions in your application. Here
-are the configuration options you can provide:
+
+ In most applications, you don’t need to create a `CopilotKitCore` instance yourself—CopilotKit initializes and manages
+ it behind the scenes.
+
-- `runtimeUrl?`: `string` The endpoint where your CopilotRuntime server is hosted. When provided, CopilotKitCore will
- automatically connect and discover available remote agents.
+Instantiate `CopilotKitCore` to initialize the client that manages runtime connections, agents, and tools.
-- `headers?`: `Record` Custom HTTP headers to include with every request. Useful for authentication
- tokens or tracking headers.
+```typescript
+new CopilotKitCore(config?: CopilotKitCoreConfig)
+````
-- `properties?`: `Record` Application-specific data that gets forwarded to agents as context. This
- might include user preferences, application state, or feature flags.
+#### Parameters
-- `agents?`: `Record` Local agents that run directly in the browser. The key becomes the agent's
- identifier.
+```typescript
+interface CopilotKitCoreConfig {
+ runtimeUrl?: string; // The endpoint where your CopilotRuntime server is hosted
+ headers?: Record; // Custom HTTP headers to include with every request
+ properties?: Record; // Application-specific data forwarded to agents as context
+ agents__unsafe_dev_only?: Record; // Local agents for development only - production requires CopilotRuntime
+ tools?: FrontendTool[]; // Frontend functions that agents can invoke
+}
+```
-- `tools?`: `FrontendTool[]` Frontend functions that agents can invoke, such as updating UI elements or fetching
- client-side data.
+Configuration details:
+
+- `runtimeUrl`: When provided, CopilotKitCore will automatically connect and discover available remote agents.
+- `headers`: Headers to include with every request.
+- `properties`: Properties forwarded to agents as `forwardedProps`.
+- `tools`: Frontend tools that agents can invoke.
+- `agents__unsafe_dev_only`: **Development only** - This property is intended solely for rapid prototyping during
+ development. Production deployments require the security, reliability, and performance guarantees that only the
+ CopilotRuntime can provide. The key becomes the agent's identifier.
## Core Properties
@@ -63,84 +102,194 @@ Once initialized, CopilotKitCore exposes several properties that provide insight
### State Management
-- `headers`: `Record` The current request headers. You can modify these directly to update
- authentication or add new headers on the fly.
+- `headers`: `Readonly>` The current request headers sent with every request.
-- `properties`: `Record` The application properties being forwarded to agents. Update these when your
- application state changes.
+- `properties`: `Readonly>` The application properties being forwarded to agents.
-- `agents`: `Readonly>` A combined view of all available agents, merging local agents with
- those discovered from the runtime. This is read-only to prevent accidental modifications.
+- `agents`: `Readonly>` A combined view of all available agents, merging local development
+ agents with those discovered from the runtime.
-- `tools`: `Readonly[]>` The complete list of registered frontend tools available to agents.
+- `tools`: `Readonly[]>` The list of registered frontend tools available to agents.
- `context`: `Readonly>` Contextual information that agents can use to make more informed
decisions.
-## Working with Configuration
+## Understanding Runtime Connections
-These methods allow you to dynamically update CopilotKitCore's configuration after initialization:
+When you provide a `runtimeUrl`, CopilotKitCore initiates a connection to your CopilotRuntime server. Here's what
+happens behind the scenes:
-### `setRuntimeUrl(runtimeUrl: string | undefined): void`
+1. CopilotKitCore sends a GET request to `{runtimeUrl}/info`
+2. The runtime responds with available agents and metadata
+3. For each remote agent, `CopilotKitCore` creates a `ProxiedCopilotRuntimeAgent` instance
+4. These remote agents are merged with your local agents
+5. Subscribers are notified of the connection status and agent availability
-Changes the runtime endpoint and manages the connection lifecycle. This is useful when switching between different
-environments or disconnecting from the runtime entirely.
+### Runtime Connection States
-### `setHeaders(headers: Record): void`
+The connection to your runtime can be in one of four states:
-Replaces all HTTP headers. Subscribers are notified so they can react to authentication changes or other header updates.
+- `Disconnected`: No runtime URL is configured, or the connection was intentionally closed
+- `Connecting`: Actively attempting to establish a connection with the runtime
+- `Connected`: Successfully connected and remote agents are available
+- `Error`: The connection attempt failed, but CopilotKitCore will continue with local agents only
-### `setProperties(properties: Record): void`
+## Event Subscription System
-Updates the properties forwarded to agents. Use this when your application state changes in ways that might affect agent
-behavior.
+CopilotKitCore implements a robust event system that allows you to react to state changes and agent activities:
-## Managing Agents
+### subscribe()
-Agents are the AI-powered components that process requests and generate responses. CopilotKitCore provides several
-methods to manage them:
+Registers a subscriber to receive events. The returned function can be called to unsubscribe, making cleanup
+straightforward.
-### `setAgents(agents: Record): void`
+```typescript
+subscribe(subscriber: CopilotKitCoreSubscriber): () => void
+```
-Replaces all local agents while preserving remote agents from the runtime. This is useful for completely reconfiguring
-your local agent setup.
+### unsubscribe()
-### `addAgent(params: CopilotKitCoreAddAgentParams): void`
+Manually removes a subscriber if you prefer explicit cleanup over using the returned function.
-Adds a single agent to your application. The agent is immediately available for use.
+```typescript
+unsubscribe(subscriber: CopilotKitCoreSubscriber): void
+```
-- `params.id`: A unique identifier for the agent
-- `params.agent`: The agent instance to add
+## Subscribing to Events
-### `removeAgent(id: string): void`
+The event subscription system allows you to build reactive UIs that respond to CopilotKitCore's state changes. Each
+event provides both the CopilotKitCore instance and relevant data:
-Removes a local agent by its identifier. Remote agents from the runtime cannot be removed this way.
+### onRuntimeConnectionStatusChanged()
-### `getAgent(id: string): AbstractAgent | undefined`
+Notified whenever the connection to the runtime changes state. Use this to show connection indicators in your UI.
-Retrieves an agent by its identifier. Returns `undefined` if the agent doesn't exist or if the runtime is still
-connecting.
+```typescript
+onRuntimeConnectionStatusChanged?: (event: {
+ copilotkit: CopilotKitCore;
+ status: CopilotKitCoreRuntimeConnectionStatus;
+}) => void | Promise
+```
-### `connectAgent(params: CopilotKitCoreConnectAgentParams): Promise`
+### onToolExecutionStart()
-Establishes a live connection with an agent, restoring any existing conversation history and subscribing to real-time
-events. This method is particularly useful when:
+Fired when an agent begins executing a tool. Useful for showing loading states or activity indicators.
-- Reconnecting to an agent that's already running (displays new events as they occur)
-- Restoring conversation history after a page refresh
-- Setting up an agent that will receive updates from background processes
+```typescript
+onToolExecutionStart?: (event: {
+ copilotkit: CopilotKitCore;
+ toolCallId: string;
+ agentId: string;
+ toolName: string;
+ args: unknown;
+}) => void | Promise
+```
-The connection process:
+### onToolExecutionEnd()
-1. Provides the agent with current properties and available tools
-2. Sets up error event subscribers for proper error handling
-3. Restores any existing message history
-4. Returns immediately without triggering a new agent run
+Fired when tool execution completes, whether successfully or with an error. Use this to update your UI based on the
+results.
+
+```typescript
+onToolExecutionEnd?: (event: {
+ copilotkit: CopilotKitCore;
+ toolCallId: string;
+ agentId: string;
+ toolName: string;
+ result: string;
+ error?: string;
+}) => void | Promise
+```
+
+### onAgentsChanged()
+
+Notified when agents are added, removed, or updated. This includes both local changes and runtime discovery.
+
+```typescript
+onAgentsChanged?: (event: {
+ copilotkit: CopilotKitCore;
+ agents: Readonly>;
+}) => void | Promise
+```
+
+### onContextChanged()
+
+Fired when context items are added or removed. Use this to keep UI elements in sync with available context.
+
+```typescript
+onContextChanged?: (event: {
+ copilotkit: CopilotKitCore;
+ context: Readonly>;
+}) => void | Promise
+```
+
+### onPropertiesChanged()
+
+Notified when application properties are updated. Useful for debugging or showing current configuration.
+
+```typescript
+onPropertiesChanged?: (event: {
+ copilotkit: CopilotKitCore;
+ properties: Readonly>;
+}) => void | Promise
+```
-- `params.agent`: The agent to connect
-- `params.agentId?`: Override the agent's default identifier
+### onHeadersChanged()
-### `runAgent(params: CopilotKitCoreRunAgentParams): Promise`
+Fired when HTTP headers are modified. Important for tracking authentication state changes.
+
+```typescript
+onHeadersChanged?: (event: {
+ copilotkit: CopilotKitCore;
+ headers: Readonly>;
+}) => void | Promise
+```
+
+### onError()
+
+The central error handler for all CopilotKitCore operations. Every error includes a code and contextual information to
+help with debugging.
+
+```typescript
+onError?: (event: {
+ copilotkit: CopilotKitCore;
+ error: Error;
+ code: CopilotKitCoreErrorCode;
+ context: Record;
+}) => void | Promise
+```
+
+## Error Handling
+
+CopilotKitCore provides detailed error information through typed error codes, making it easier to handle different
+failure scenarios appropriately:
+
+### Understanding Error Codes
+
+Each error is categorized with a specific code that indicates what went wrong:
+
+- `RUNTIME_INFO_FETCH_FAILED`: The attempt to fetch runtime information failed. This might indicate network issues or an
+ incorrect runtime URL.
+
+- `AGENT_CONNECT_FAILED`: Failed to establish a connection with an agent. Check that the agent is properly configured.
+
+- `AGENT_RUN_FAILED`: The agent execution failed. This could be due to invalid messages or agent-side errors.
+
+- `AGENT_RUN_FAILED_EVENT`: The agent reported a failure through its event stream.
+
+- `AGENT_RUN_ERROR_EVENT`: The agent emitted an error event during execution.
+
+- `TOOL_ARGUMENT_PARSE_FAILED`: The arguments provided to a tool couldn't be parsed. This usually indicates a mismatch
+ between expected and actual parameters.
+
+- `TOOL_HANDLER_FAILED`: A tool's handler function threw an error during execution.
+
+## Running Agents
+
+CopilotKitCore provides two primary methods for executing agents: `runAgent` for immediate execution with message
+handling, and `connectAgent` for establishing live connections to existing agent sessions.
+
+### runAgent()
Executes an agent and intelligently handles the complete request-response cycle, including automatic tool execution and
follow-up runs.
@@ -164,65 +313,137 @@ Key behaviors:
gracefully
- **Wildcard Tools**: Supports a special "\*" tool that can handle any undefined tool request
-- `params.agent`: The agent to execute
-- `params.withMessages?`: Initial messages to send to the agent
-- `params.agentId?`: Override the agent's default identifier
+```typescript
+runAgent(params: CopilotKitCoreRunAgentParams): Promise
+```
+
+#### Parameters
+
+```typescript
+interface CopilotKitCoreRunAgentParams {
+ agent: AbstractAgent; // The agent to execute
+ withMessages?: Message[]; // Initial messages to send to the agent
+ agentId?: string; // Override the agent's default identifier
+}
+```
+
+### connectAgent()
+
+Establishes a live connection with an agent, restoring any existing conversation history and subscribing to real-time
+events. This method is particularly useful when:
+
+- Reconnecting to an agent that's already running (displays new events as they occur)
+- Restoring conversation history after a page refresh
+- Setting up an agent that will receive updates from background processes
+
+The connection process:
+
+1. Provides the agent with current properties and available tools
+2. Sets up error event subscribers for proper error handling
+3. Restores any existing message history
+4. Returns immediately without triggering a new agent run
+
+```typescript
+connectAgent(params: CopilotKitCoreConnectAgentParams): Promise
+```
+
+#### Parameters
+
+```typescript
+interface CopilotKitCoreConnectAgentParams {
+ agent: AbstractAgent; // The agent to connect
+ agentId?: string; // Override the agent's default identifier
+}
+```
+
+### getAgent()
+
+Retrieves an agent by its identifier. Returns `undefined` if the agent doesn't exist or if the runtime is still
+connecting.
+
+```typescript
+getAgent(id: string): AbstractAgent | undefined
+```
## Managing Context
Context provides agents with additional information about the current state of your application:
-### `addContext(context: Context): string`
+### addContext()
Adds contextual information that agents can reference. Returns a unique identifier for later removal.
-- `context.description`: A human-readable description of what this context represents
-- `context.value`: The actual context data
+```typescript
+addContext(context: Context): string
+```
-### `removeContext(id: string): void`
+#### Parameters
+
+```typescript
+interface Context {
+ description: string; // A human-readable description of what this context represents
+ value: any; // The actual context data
+}
+```
+
+### removeContext()
Removes previously added context using its identifier.
+```typescript
+removeContext(id: string): void
+```
+
## Managing Tools
Tools are functions that agents can call to interact with your application:
-### `addTool(tool: FrontendTool): void`
+### addTool()
Registers a new frontend tool. If a tool with the same name and agent scope already exists, the registration is skipped
to prevent duplicates.
-### `removeTool(id: string, agentId?: string): void`
+```typescript
+addTool(tool: FrontendTool): void
+```
+
+### removeTool()
Removes a tool from the registry. You can remove tools globally or for specific agents:
- When `agentId` is provided, removes the tool only for that agent
- When `agentId` is omitted, removes only global tools with the matching name
-### `getTool(params: CopilotKitCoreGetToolParams): FrontendTool | undefined`
+```typescript
+removeTool(id: string, agentId?: string): void
+```
+
+### getTool()
Retrieves a tool by name, with intelligent fallback behavior:
-- `params.toolName`: The tool's name
-- `params.agentId?`: Look for agent-specific tools first
- If an agent-specific tool isn't found, it falls back to global tools
-### `setTools(tools: FrontendTool[]): void`
-
-Replaces all tools at once. Useful for completely reconfiguring available tools.
-
-## Event Subscription System
+```typescript
+getTool(params: CopilotKitCoreGetToolParams): FrontendTool | undefined
+```
-CopilotKitCore implements a robust event system that allows you to react to state changes and agent activities:
+#### Parameters
-### `subscribe(subscriber: CopilotKitCoreSubscriber): () => void`
+```typescript
+interface CopilotKitCoreGetToolParams {
+ toolName: string; // The tool's name
+ agentId?: string; // Look for agent-specific tools first
+}
+```
-Registers a subscriber to receive events. The returned function can be called to unsubscribe, making cleanup
-straightforward.
+### setTools()
-### `unsubscribe(subscriber: CopilotKitCoreSubscriber): void`
+Replaces all tools at once. Useful for completely reconfiguring available tools.
-Manually removes a subscriber if you prefer explicit cleanup over using the returned function.
+```typescript
+setTools(tools: FrontendTool[]): void
+```
## Tool Execution Lifecycle
@@ -262,169 +483,77 @@ By default, after tool execution completes:
- This continues until no more tools are requested
- You can disable follow-up by setting `followUp: false` on specific tools
-## Understanding Runtime Connections
-
-When you provide a `runtimeUrl`, CopilotKitCore initiates a connection to your CopilotRuntime server. Here's what
-happens behind the scenes:
-
-1. CopilotKitCore sends a GET request to `{runtimeUrl}/info`
-2. The runtime responds with available agents and metadata
-3. For each remote agent, CopilotKitCore creates a ProxiedCopilotRuntimeAgent instance
-4. These remote agents are merged with your local agents
-5. Subscribers are notified of the connection status and agent availability
-
-## Runtime Connection States
-
-The connection to your runtime can be in one of four states:
-
-- `Disconnected`: No runtime URL is configured, or the connection was intentionally closed
-- `Connecting`: Actively attempting to establish a connection with the runtime
-- `Connected`: Successfully connected and remote agents are available
-- `Error`: The connection attempt failed, but CopilotKitCore will continue with local agents only
-
-## Subscribing to Events
-
-The event subscription system allows you to build reactive UIs that respond to CopilotKitCore's state changes. Each
-event provides both the CopilotKitCore instance and relevant data:
-
-### `onRuntimeConnectionStatusChanged`
-
-Notified whenever the connection to the runtime changes state. Use this to show connection indicators in your UI.
+## Working with Configuration
-```typescript
-onRuntimeConnectionStatusChanged?: (event: {
- copilotkit: CopilotKitCore;
- status: CopilotKitCoreRuntimeConnectionStatus;
-}) => void | Promise;
-```
+These methods allow you to dynamically update CopilotKitCore's configuration after initialization:
-### `onToolExecutionStart`
+### setRuntimeUrl()
-Fired when an agent begins executing a tool. Useful for showing loading states or activity indicators.
+Changes the runtime endpoint and manages the connection lifecycle. This is useful when switching between different
+environments or disconnecting from the runtime entirely.
```typescript
-onToolExecutionStart?: (event: {
- copilotkit: CopilotKitCore;
- toolCallId: string;
- agentId: string;
- toolName: string;
- args: unknown;
-}) => void | Promise;
+setRuntimeUrl(runtimeUrl: string | undefined): void
```
-### `onToolExecutionEnd`
+### setHeaders()
-Fired when tool execution completes, whether successfully or with an error. Use this to update your UI based on the
-results.
+Replaces all HTTP headers. Subscribers are notified so they can react to authentication changes or other header updates.
```typescript
-onToolExecutionEnd?: (event: {
- copilotkit: CopilotKitCore;
- toolCallId: string;
- agentId: string;
- toolName: string;
- result: string;
- error?: string;
-}) => void | Promise;
+setHeaders(headers: Record): void
```
-### `onAgentsChanged`
+### setProperties()
-Notified when agents are added, removed, or updated. This includes both local changes and runtime discovery.
+Updates the properties forwarded to agents. Use this when your application state changes in ways that might affect agent
+behavior.
```typescript
-onAgentsChanged?: (event: {
- copilotkit: CopilotKitCore;
- agents: Readonly>;
-}) => void | Promise;
+setProperties(properties: Record): void
```
-### `onContextChanged`
+## Managing Local Agents
-Fired when context items are added or removed. Use this to keep UI elements in sync with available context.
+
+ In production applications, agents must be managed through the CopilotRuntime, which provides proper isolation,
+ monitoring, and scalability. The local agent methods below are marked `__unsafe_dev_only` as they're intended solely
+ for rapid prototyping during development. Production deployments require the security and performance guarantees that
+ only the CopilotRuntime can provide.
+
-```typescript
-onContextChanged?: (event: {
- copilotkit: CopilotKitCore;
- context: Readonly>;
-}) => void | Promise;
-```
+Agents are the AI-powered components that process requests and generate responses. CopilotKitCore provides several
+methods to manage them locally during development:
-### `onPropertiesChanged`
+### setAgents\_\_unsafe_dev_only()
-Notified when application properties are updated. Useful for debugging or showing current configuration.
+Replaces all local development agents while preserving remote agents from the runtime.
```typescript
-onPropertiesChanged?: (event: {
- copilotkit: CopilotKitCore;
- properties: Readonly>;
-}) => void | Promise;
+setAgents__unsafe_dev_only(agents: Record): void
```
-### `onHeadersChanged`
+### addAgent\_\_unsafe_dev_only()
-Fired when HTTP headers are modified. Important for tracking authentication state changes.
+Adds a single agent for development testing.
```typescript
-onHeadersChanged?: (event: {
- copilotkit: CopilotKitCore;
- headers: Readonly>;
-}) => void | Promise;
+addAgent__unsafe_dev_only(params: CopilotKitCoreAddAgentParams): void
```
-### `onError`
-
-The central error handler for all CopilotKitCore operations. Every error includes a code and contextual information to
-help with debugging.
+#### Parameters
```typescript
-onError?: (event: {
- copilotkit: CopilotKitCore;
- error: Error;
- code: CopilotKitCoreErrorCode;
- context: Record;
-}) => void | Promise;
+interface CopilotKitCoreAddAgentParams {
+ id: string; // A unique identifier for the agent
+ agent: AbstractAgent; // The agent instance to add
+}
```
-## Error Handling
-
-CopilotKitCore provides detailed error information through typed error codes, making it easier to handle different
-failure scenarios appropriately:
-
-### Understanding Error Codes
+### removeAgent\_\_unsafe_dev_only()
-Each error is categorized with a specific code that indicates what went wrong:
-
-- `RUNTIME_INFO_FETCH_FAILED`: The attempt to fetch runtime information failed. This might indicate network issues or an
- incorrect runtime URL.
-
-- `AGENT_CONNECT_FAILED`: Failed to establish a connection with an agent. Check that the agent is properly configured.
-
-- `AGENT_RUN_FAILED`: The agent execution failed. This could be due to invalid messages or agent-side errors.
-
-- `AGENT_RUN_FAILED_EVENT`: The agent reported a failure through its event stream.
-
-- `AGENT_RUN_ERROR_EVENT`: The agent emitted an error event during execution.
-
-- `TOOL_ARGUMENT_PARSE_FAILED`: The arguments provided to a tool couldn't be parsed. This usually indicates a mismatch
- between expected and actual parameters.
-
-- `TOOL_HANDLER_FAILED`: A tool's handler function threw an error during execution.
-
-## TypeScript Types and Interfaces
-
-CopilotKitCore is fully typed to provide excellent IDE support and catch errors at compile time:
-
-### `CopilotKitCoreConfig`
-
-The configuration object used when creating a new CopilotKitCore instance:
+Removes a local development agent by its identifier. Remote agents from the runtime cannot be removed this way.
```typescript
-interface CopilotKitCoreConfig {
- runtimeUrl?: string;
- agents?: Record;
- headers?: Record;
- properties?: Record;
- tools?: FrontendTool[];
-}
+removeAgent__unsafe_dev_only(id: string): void
```
diff --git a/apps/docs/reference/copilotkit-provider.mdx b/apps/docs/reference/copilotkit-provider.mdx
new file mode 100644
index 00000000..cc7bd58f
--- /dev/null
+++ b/apps/docs/reference/copilotkit-provider.mdx
@@ -0,0 +1,245 @@
+---
+title: CopilotKitProvider
+description: "CopilotKitProvider API Reference"
+---
+
+`CopilotKitProvider` is the React context provider that initializes and manages `CopilotKitCore` for your React
+application. It provides all child components with access to agents, tools, and copilot functionality through React's
+context API.
+
+## What is CopilotKitProvider?
+
+The CopilotKitProvider is the root component that:
+
+- Creates and manages a `CopilotKitCore` instance
+- Provides React-specific features like hooks and render components
+- Manages tool rendering and human-in-the-loop interactions
+- Handles state synchronization between your React app and AI agents
+
+## Basic Usage
+
+Typically you would wrap your application with `CopilotKitProvider` at the root level:
+
+```tsx
+import { CopilotKitProvider } from "@copilotkitnext/react";
+
+function App() {
+ return (
+
+ {/* Your app components */}
+
+ );
+}
+```
+
+## Props
+
+### runtimeUrl
+
+`string` **(optional)**
+
+The URL of your CopilotRuntime server. The provider will automatically connect to the runtime and discover available
+agents.
+
+```tsx
+{children}
+```
+
+### headers
+
+`Record` **(optional)**
+
+Custom HTTP headers to include with every request to the runtime. Useful for authentication and custom metadata.
+
+```tsx
+
+ {children}
+
+```
+
+### properties
+
+`Record` **(optional)**
+
+Application-specific data that gets forwarded to agents as additional context. Agents receive these as `forwardedProps`.
+
+```tsx
+
+ {children}
+
+```
+
+### agents\_\_unsafe_dev_only
+
+`Record` **(optional, development only)**
+
+
+ This property is intended solely for rapid prototyping during development. Production deployments require the
+ security, reliability, and performance guarantees that only the CopilotRuntime can provide.
+
+
+Local agents for development testing. The key becomes the agent's identifier.
+
+```tsx
+import { HttpAgent } from "@ag-ui/client";
+
+const devAgent = new HttpAgent({
+ url: "http://localhost:8000",
+});
+
+
+ {children}
+;
+```
+
+### renderToolCalls
+
+`ReactToolCallRender[]` **(optional)**
+
+A static list of components to render when specific tools are called. Enables visual feedback for tool execution.
+
+```tsx
+const renderToolCalls = [
+ {
+ name: "searchProducts",
+ args: z.object({
+ query: z.string(),
+ }),
+ render: ({ args }) =>
Searching for: {args.query}
,
+ },
+];
+
+{children};
+```
+
+
+ The `renderToolCalls` array must be stable across renders. Define it outside your component or use `useMemo`. For
+ dynamic tool rendering, use the `useRenderToolCall` hook instead.
+
+
+### frontendTools
+
+`ReactFrontendTool[]` **(optional)**
+
+A static list of frontend tools that agents can invoke. These are React-specific wrappers around the base `FrontendTool`
+type with additional rendering capabilities.
+
+```tsx
+const tools = [
+ {
+ name: "showNotification",
+ description: "Display a notification to the user",
+ parameters: z.object({
+ message: z.string(),
+ type: z.enum(["info", "success", "warning", "error"]),
+ }),
+ handler: async ({ message, type }) => {
+ toast[type](message);
+ return "Notification displayed";
+ },
+ },
+];
+
+{children};
+```
+
+
+ The `frontendTools` array must be stable across renders. For dynamically adding/removing tools, use the
+ `useFrontendTool` hook.
+
+
+### humanInTheLoop
+
+`ReactHumanInTheLoop[]` **(optional)**
+
+Tools that require human interaction or approval before execution. These tools pause agent execution until the user
+responds.
+
+```tsx
+const humanInTheLoop = [
+ {
+ name: "confirmAction",
+ description: "Request user confirmation for an action",
+ parameters: z.object({
+ action: z.string(),
+ details: z.string(),
+ }),
+ render: ({ args, resolve }) => (
+ resolve({ confirmed: true })}
+ onCancel={() => resolve({ confirmed: false })}
+ />
+ ),
+ },
+];
+
+{children};
+```
+
+### children
+
+`ReactNode` **(required)**
+
+The React components that will have access to the CopilotKit context.
+
+## Context Value
+
+The provider makes a `CopilotKitContextValue` available to child components through React context:
+
+```typescript
+interface CopilotKitContextValue {
+ copilotkit: CopilotKitCore;
+ renderToolCalls: ReactToolCallRender[];
+ currentRenderToolCalls: ReactToolCallRender[];
+ setCurrentRenderToolCalls: React.Dispatch[]>>;
+}
+```
+
+Access this context using the `useCopilotKit` hook:
+
+```tsx
+import { useCopilotKit } from "@copilotkitnext/react";
+
+function MyComponent() {
+ const { copilotkit } = useCopilotKit();
+
+ // Access CopilotKitCore instance
+ const agent = copilotkit.getAgent("assistant");
+}
+```
+
+## Considerations
+
+### Server-Side Rendering (SSR)
+
+The provider is compatible with SSR but won't fetch runtime information during server-side rendering. The runtime
+connection is established only on the client side to prevent blocking SSR.
+
+### Dynamic Updates
+
+You can dynamically update the following props:
+
+- `runtimeUrl`: Changing this will disconnect from the current runtime and connect to the new one
+- `headers`: Updates are applied to all future requests
+- `properties`: Changes are immediately available to agents
diff --git a/apps/docs/reference/frontend-tool.mdx b/apps/docs/reference/frontend-tool.mdx
new file mode 100644
index 00000000..4dd32964
--- /dev/null
+++ b/apps/docs/reference/frontend-tool.mdx
@@ -0,0 +1,150 @@
+---
+title: FrontendTool
+description: "FrontendTool API Reference"
+---
+
+`FrontendTool` is a cross-platform type that defines tools (functions) that AI agents can invoke in your frontend
+application. These tools enable agents to interact the user, retrieve data, perform actions, and integrate with your
+application's functionality.
+
+## What is a FrontendTool?
+
+A FrontendTool represents a capability you expose to AI agents, allowing them to:
+
+- Interact with the user
+- Fetch or manipulate application data
+- Trigger application workflows
+
+Frontend tools are framework-agnostic and work consistently across all frameworks through `CopilotKitCore`.
+
+## Type Definition
+
+```typescript
+type FrontendTool = Record> = {
+ name: string;
+ description?: string;
+ parameters?: z.ZodType;
+ handler?: (args: T, toolCall: ToolCall) => Promise;
+ followUp?: boolean;
+ agentId?: string;
+};
+```
+
+## Properties
+
+### name
+
+`string` **(required)**
+
+A unique identifier for the tool. This is the name agents will use to request this tool's execution. Avoid spaces and
+special characters.
+
+```typescript
+{
+ name: "searchProducts";
+}
+```
+
+A special wildcard tool is available with the name `*`. This tool will handle any unmatched tool requests.
+
+### description
+
+`string` **(optional)**
+
+A human-readable description that helps agents understand when and how to use this tool. This description is sent to the
+LLM to guide its decision-making.
+
+```typescript
+{
+ name: "searchProducts",
+ description: "Search for products in the catalog by name, category, or price range"
+}
+```
+
+### parameters
+
+`z.ZodType` **(optional)**
+
+A Zod schema that defines and validates the tool's input parameters. This ensures type safety and provides automatic
+validation of agent-provided arguments.
+
+```typescript
+import { z } from "zod";
+
+{
+ name: "updateUserProfile",
+ parameters: z.object({
+ firstName: z.string().optional(),
+ lastName: z.string().optional(),
+ email: z.string().email().optional(),
+ preferences: z.object({
+ theme: z.enum(["light", "dark"]).optional(),
+ notifications: z.boolean().optional()
+ }).optional()
+ })
+}
+```
+
+### handler
+
+`(args: T, toolCall: ToolCall) => Promise` **(optional)**
+
+The async function that executes when the agent invokes this tool. It receives the validated arguments and a ToolCall
+object containing metadata about the invocation.
+
+```typescript
+{
+ name: "addToCart",
+ parameters: z.object({
+ productId: z.string(),
+ quantity: z.number().min(1)
+ }),
+ handler: async ({productId, quantity}) => {
+ // Add product to cart
+ const result = await cartService.addItem(productId, quantity);
+
+ // Return a string or serializable object
+ return {
+ success: true,
+ cartTotal: result.total,
+ itemCount: result.itemCount
+ };
+ }
+}
+```
+
+### followUp
+
+`boolean` **(optional, default: true)**
+
+Controls whether the agent should be automatically re-run after this tool completes. When `true`, the tool's result is
+added to the conversation and the agent continues processing. Disable follow-up for final actions that complete a
+workflow.
+
+```typescript
+{
+ name: "saveDocument",
+ handler: async (args) => {
+ await documentService.save(args);
+ return "Document saved successfully";
+ },
+ followUp: false // Don't re-run agent after saving
+}
+```
+
+### agentId
+
+`string` **(optional)**
+
+Restricts this tool to a specific agent. When set, only the specified agent can invoke this tool.
+
+```typescript
+{
+ name: "adminAction",
+ agentId: "admin-assistant",
+ handler: async (args) => {
+ // Only the admin-assistant agent can call this
+ return await performAdminAction(args);
+ }
+}
+```
diff --git a/apps/docs/reference/proxied-copilot-runtime-agent.mdx b/apps/docs/reference/proxied-copilot-runtime-agent.mdx
new file mode 100644
index 00000000..475f22f1
--- /dev/null
+++ b/apps/docs/reference/proxied-copilot-runtime-agent.mdx
@@ -0,0 +1,80 @@
+---
+title: ProxiedCopilotRuntimeAgent
+description: "ProxiedCopilotRuntimeAgent API Reference"
+---
+
+`ProxiedCopilotRuntimeAgent` is a specialized HTTP agent that acts as a proxy between your client application and remote
+agents hosted on the `CopilotRuntime` server. It extends the base `HttpAgent` class to provide seamless communication
+with runtime-hosted agents.
+
+## Architecture Overview
+
+```mermaid
+graph LR
+ subgraph Client["Client Application"]
+ Core[CopilotKitCore]
+ PRA1[ProxiedCopilotRuntimeAgent customer-support]
+ PRA2[ProxiedCopilotRuntimeAgent code-assistant]
+ PRA3[ProxiedCopilotRuntimeAgent data-analyst]
+
+ Core --> PRA1
+ Core --> PRA2
+ Core --> PRA3
+ end
+
+ subgraph Server["CopilotRuntime Server"]
+ Runtime[Runtime API]
+ Agent1[Agent: customer-support]
+ Agent2[Agent: code-assistant]
+ Agent3[Agent: data-analyst]
+
+ Runtime --> Agent1
+ Runtime --> Agent2
+ Runtime --> Agent3
+ end
+
+ PRA1 -.-> Runtime
+ PRA2 -.-> Runtime
+ PRA3 -.-> Runtime
+```
+
+## What is ProxiedCopilotRuntimeAgent?
+
+When `CopilotKitCore` connects to a `CopilotRuntime` server, it discovers available remote agents. For each remote
+agent, it creates a `ProxiedCopilotRuntimeAgent` instance that handles all communication with that specific agent
+through the runtime's API endpoints.
+
+Key characteristics:
+
+- **Remote Agent Communication**: Handles communication with the remote agent through the runtime's API endpoints
+- **Header and Property Forwarding**: Inherits and forwards authentication headers and properties from `CopilotKitCore`
+- **Connection and History Management**: Handles loading history and reconnecting to existing live agent sessions
+
+## How does it work?
+
+`CopilotKitCore` automatically creates `ProxiedCopilotRuntimeAgent` instances during runtime discovery:
+
+1. `CopilotKitCore` fetches `/info` from the runtime
+2. The runtime responds with available agents
+3. For each agent, `CopilotKitCore` creates a `ProxiedCopilotRuntimeAgent`
+4. These agents are merged with any local agents
+5. The agents become available through `copilotKit.getAgent()`
+
+## Creating a ProxiedCopilotRuntimeAgent
+
+
+ In typical usage, you don't create `ProxiedCopilotRuntimeAgent` instances directly. `CopilotKitCore` automatically
+ creates them when discovering agents from the runtime.
+
+
+```typescript
+import { ProxiedCopilotRuntimeAgent } from "@copilotkitnext/core";
+
+const agent = new ProxiedCopilotRuntimeAgent({
+ runtimeUrl: "https://your-runtime.example.com",
+ agentId: "my-agent",
+ headers: {
+ Authorization: "Bearer your-token",
+ },
+});
+```
diff --git a/apps/docs/reference/use-agent-context.mdx b/apps/docs/reference/use-agent-context.mdx
new file mode 100644
index 00000000..7bebffdb
--- /dev/null
+++ b/apps/docs/reference/use-agent-context.mdx
@@ -0,0 +1,384 @@
+---
+title: useAgentContext
+description: "useAgentContext Hook API Reference"
+---
+
+`useAgentContext` is a React hook that provides contextual information to AI agents during their execution. It allows
+you to dynamically add relevant data that agents can use to make more informed decisions and provide better responses.
+
+## What is useAgentContext?
+
+The useAgentContext hook:
+
+- Provides contextual information to agents
+- Automatically manages context lifecycle (add on mount, remove on unmount)
+- Updates context when values change
+- Helps agents understand application state and user data
+
+## Basic Usage
+
+```tsx
+import { useAgentContext } from "@copilotkitnext/react";
+
+function UserPreferences() {
+ const userSettings = {
+ theme: "dark",
+ language: "en",
+ timezone: "UTC-5",
+ };
+
+ useAgentContext({
+ description: "User preferences and settings",
+ value: userSettings,
+ });
+
+ return
User preferences loaded
;
+}
+```
+
+## Parameters
+
+The hook accepts a single `Context` object with the following properties:
+
+### description
+
+`string` **(required)**
+
+A clear description of what this context represents. This helps agents understand how to use the provided information.
+
+```tsx
+useAgentContext({
+ description: "Current shopping cart contents",
+ value: cartItems,
+});
+```
+
+### value
+
+`any` **(required)**
+
+The actual data to provide as context. Can be any serializable value including objects, arrays, strings, or numbers.
+
+```tsx
+useAgentContext({
+ description: "Current form validation state",
+ value: {
+ hasErrors: false,
+ touchedFields: ["email", "name"],
+ dirtyFields: ["email"],
+ isSubmitting: false,
+ },
+});
+```
+
+## Examples
+
+### User Preferences Context
+
+```tsx
+import { useAgentContext } from "@copilotkitnext/react";
+import { useUserPreferences } from "./hooks/useUserPreferences";
+
+function UserPreferencesContext() {
+ const { preferences, isLoading } = useUserPreferences();
+
+ useAgentContext({
+ description: "User display preferences and settings",
+ value: {
+ theme: preferences?.theme || "light",
+ language: preferences?.language || "en",
+ timezone: preferences?.timezone || "UTC",
+ displayDensity: preferences?.displayDensity || "comfortable",
+ isLoading,
+ },
+ });
+
+ return null; // Context-only component
+}
+```
+
+### Form State Context
+
+```tsx
+import { useAgentContext } from "@copilotkitnext/react";
+import { useState } from "react";
+
+function ContactForm() {
+ const [formData, setFormData] = useState({
+ name: "",
+ email: "",
+ subject: "",
+ message: "",
+ });
+
+ // Provide form state to agent for assistance
+ useAgentContext({
+ description: "Contact form current state",
+ value: {
+ formData,
+ hasUnsavedChanges: Object.values(formData).some((v) => v !== ""),
+ isValid: formData.email.includes("@") && formData.name.length > 0,
+ },
+ });
+
+ return (
+
+ );
+}
+```
+
+### Application State Context
+
+```tsx
+import { useAgentContext } from "@copilotkitnext/react";
+import { useLocation } from "react-router-dom";
+
+function AppStateContext() {
+ const location = useLocation();
+ const currentTime = new Date().toISOString();
+
+ useAgentContext({
+ description: "Current application state and navigation",
+ value: {
+ currentPath: location.pathname,
+ queryParams: Object.fromEntries(new URLSearchParams(location.search)),
+ timestamp: currentTime,
+ },
+ });
+
+ return null;
+}
+```
+
+### Dynamic Data Context
+
+```tsx
+import { useAgentContext } from "@copilotkitnext/react";
+import { useEffect, useState } from "react";
+
+function DynamicDataContext() {
+ const [data, setData] = useState(null);
+
+ useEffect(() => {
+ const fetchData = async () => {
+ const response = await fetch("/api/context-data");
+ setData(await response.json());
+ };
+ fetchData();
+ }, []);
+
+ // Context updates automatically when data changes
+ useAgentContext({
+ description: "Dynamic application data",
+ value: data || { loading: true },
+ });
+
+ return null;
+}
+```
+
+### Multiple Contexts
+
+```tsx
+import { useAgentContext } from "@copilotkitnext/react";
+
+function MultipleContexts() {
+ const userContext = { id: "123", name: "John" };
+ const appContext = { version: "1.0.0", features: ["chat", "search"] };
+
+ // Use multiple hooks for different contexts
+ useAgentContext({
+ description: "User information",
+ value: userContext,
+ });
+
+ useAgentContext({
+ description: "Application configuration",
+ value: appContext,
+ });
+
+ return
+ );
+}
+```
diff --git a/apps/docs/reference/use-agent.mdx b/apps/docs/reference/use-agent.mdx
new file mode 100644
index 00000000..92bd7971
--- /dev/null
+++ b/apps/docs/reference/use-agent.mdx
@@ -0,0 +1,502 @@
+---
+title: useAgent
+description: "useAgent Hook API Reference"
+---
+
+`useAgent` is a React hook that provides access to [AG-UI](https://ag-ui.com) agents and subscribes to their state
+changes. It enables components to interact with agents, access their messages, and respond to updates in real-time.
+
+## What is useAgent?
+
+The useAgent hook:
+
+- Retrieves an agent by ID from the CopilotKit context
+- Subscribes to agent state changes (messages, state, run status)
+- Automatically triggers component re-renders when the agent updates
+- Handles cleanup of subscriptions when the component unmounts
+
+## Basic Usage
+
+```tsx
+import { useAgent } from "@copilotkitnext/react";
+
+function ChatComponent() {
+ const { agent } = useAgent({ agentId: "assistant" });
+
+ if (!agent) {
+ return
Loading agent...
;
+ }
+
+ return (
+
+
Agent: {agent.id}
+
Messages: {agent.messages.length}
+
Running: {agent.isRunning ? "Yes" : "No"}
+
+ );
+}
+```
+
+## Parameters
+
+### agentId
+
+`string` **(optional)**
+
+The ID of the agent to retrieve. If not provided, defaults to `"default"`.
+
+```tsx
+const { agent } = useAgent({ agentId: "customer-support" });
+```
+
+### updates
+
+`UseAgentUpdate[]` **(optional)**
+
+An array of update types to subscribe to. This allows you to optimize re-renders by only subscribing to specific
+changes.
+
+```tsx
+import { useAgent, UseAgentUpdate } from "@copilotkitnext/react";
+
+const { agent } = useAgent({
+ agentId: "assistant",
+ updates: [UseAgentUpdate.OnMessagesChanged],
+});
+```
+
+Available update types:
+
+- `UseAgentUpdate.OnMessagesChanged` - Updates when messages are added or modified
+- `UseAgentUpdate.OnStateChanged` - Updates when agent state changes
+- `UseAgentUpdate.OnRunStatusChanged` - Updates when agent starts or stops running
+
+If `updates` is not provided, the hook subscribes to all update types by default.
+
+## Return Value
+
+The hook returns an object with a single property:
+
+### agent
+
+`AbstractAgent | undefined`
+
+The agent instance if found, or `undefined` if:
+
+- The agent with the specified ID doesn't exist
+- The runtime is still connecting
+- No agents are available
+
+## Accessing Agent Messages
+
+The agent's message history is available through the `messages` property. You can read messages and add new ones to
+create interactive conversations.
+
+### Reading Messages
+
+```tsx
+function SimpleChat() {
+ const { agent } = useAgent();
+
+ if (!agent) {
+ return
No agent available
;
+ }
+
+ return (
+
+ {agent.messages.map((message) => (
+
+ {message.role}: {message.content}
+
+ ))}
+
+ );
+}
+```
+
+### Sending Messages
+
+To send a message, add it to the agent and then run the agent:
+
+```tsx
+import { useAgent } from "@copilotkitnext/react";
+import { useCopilotKit } from "@copilotkitnext/react";
+
+function MessageSender() {
+ const { agent } = useAgent({ agentId: "assistant" });
+ const { copilotkit } = useCopilotKit();
+
+ const sendMessage = async (content: string) => {
+ if (!agent) return;
+
+ // Add message to agent
+ agent.addMessage({
+ id: crypto.randomUUID(),
+ role: "user",
+ content,
+ });
+
+ // Run the agent to get a response
+ await copilotkit.runAgent({
+ agent,
+ agentId: "assistant",
+ });
+ };
+
+ return (
+
+
+
+ );
+}
+```
+
+## Accessing and Updating Shared State
+
+Shared state enables real-time collaboration between users and agents. Both can read and modify the state, creating a
+synchronized workspace for interactive features.
+
+### Understanding Shared State
+
+The agent's state is a shared data structure that:
+
+- Can be read by both your application and the agent
+- Can be modified by both parties
+- Automatically triggers re-renders when changed
+- Persists throughout the conversation
+
+State updates cause re-renders when:
+
+- You call `agent.setState()` from your application
+- The agent modifies the state during execution
+- Any state change occurs, regardless of source
+
+### Reading State
+
+```tsx
+function StateDisplay() {
+ const { agent } = useAgent({
+ updates: [UseAgentUpdate.OnStateChanged], // Subscribe to state changes
+ });
+
+ if (!agent) return null;
+
+ return (
+
+
Current State
+
{JSON.stringify(agent.state, null, 2)}
+
+ );
+}
+```
+
+### Updating State
+
+```tsx
+function StateController() {
+ const { agent } = useAgent({
+ updates: [UseAgentUpdate.OnStateChanged],
+ });
+
+ const updateState = (key: string, value: any) => {
+ if (!agent) return;
+
+ // Update the shared state
+ agent.setState({
+ ...agent.state,
+ [key]: value,
+ });
+
+ // This will trigger re-renders for all components
+ // subscribed to OnStateChanged
+ };
+
+ return (
+
+
+
+ );
+}
+```
+
+### Collaborative Features
+
+Shared state enables collaborative features where users and agents work together:
+
+```tsx
+function CollaborativeTodo() {
+ const { agent } = useAgent({
+ updates: [UseAgentUpdate.OnStateChanged],
+ });
+ const { copilotkit } = useCopilotKit();
+
+ if (!agent) return null;
+
+ const todos = agent.state.todos || [];
+
+ const addTodo = (text: string) => {
+ agent.setState({
+ ...agent.state,
+ todos: [...todos, { id: crypto.randomUUID(), text, done: false }],
+ });
+ };
+
+ const toggleTodo = (id: string) => {
+ agent.setState({
+ ...agent.state,
+ todos: todos.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo)),
+ });
+ };
+
+ const askAgentToOrganize = async () => {
+ // Add a message asking the agent to organize todos
+ agent.addMessage({
+ id: crypto.randomUUID(),
+ role: "user",
+ content: "Please organize my todos by priority",
+ });
+
+ // The agent can read and modify the todos in agent.state
+ await copilotkit.runAgent({ agent });
+
+ // After the agent runs, the state will be updated
+ // and the component will re-render automatically
+ };
+
+ return (
+
+
+ {showTool && } {/* Tool only available when mounted */}
+
+ );
+}
+```
+
+### Cleanup on Unmount
+
+Tools are automatically removed when components unmount, but their renderers persist to maintain chat history:
+
+```tsx
+function TemporaryTool() {
+ useFrontendTool({
+ name: "tempAction",
+ handler: async () => "Temporary action",
+ render: ({ status }) =>
Temp tool: {status}
,
+ });
+
+ // When this component unmounts:
+ // - The tool handler is removed (agent can't call it anymore)
+ // - The renderer persists (previous executions still visible in chat)
+
+ return null;
+}
+```
+
+### Tool Override Warning
+
+If a tool with the same name already exists, it will be overridden with a console warning:
+
+```tsx
+// First registration
+useFrontendTool({
+ name: "search",
+ handler: async () => "Search v1",
+});
+
+// Second registration (overrides first)
+useFrontendTool({
+ name: "search", // Same name - will override with warning
+ handler: async () => "Search v2",
+});
+```
diff --git a/apps/docs/reference/use-human-in-the-loop.mdx b/apps/docs/reference/use-human-in-the-loop.mdx
new file mode 100644
index 00000000..dbdbb5db
--- /dev/null
+++ b/apps/docs/reference/use-human-in-the-loop.mdx
@@ -0,0 +1,194 @@
+---
+title: useHumanInTheLoop
+description: "useHumanInTheLoop Hook API Reference"
+---
+
+`useHumanInTheLoop` is a React hook that creates interactive tools requiring human approval or input before the agent
+can proceed. It enables you to build approval workflows, confirmation dialogs, and interactive decision points where
+human oversight is needed.
+
+## What is useHumanInTheLoop?
+
+The useHumanInTheLoop hook:
+
+- Creates tools that pause execution until human input is received
+- Manages status transitions (InProgress → Executing → Complete)
+- Provides a `respond` callback for user interactions
+- Automatically handles promise resolution for agent continuation
+- Renders interactive UI components in the chat interface
+
+## Basic Usage
+
+```tsx
+import { useHumanInTheLoop } from "@copilotkitnext/react";
+import { ToolCallStatus } from "@copilotkitnext/core";
+import { z } from "zod";
+
+function ApprovalComponent() {
+ useHumanInTheLoop({
+ name: "requireApproval",
+ description: "Requires human approval before proceeding",
+ parameters: z.object({
+ action: z.string(),
+ reason: z.string(),
+ }),
+ render: ({ status, args, respond }) => {
+ if (status === ToolCallStatus.Executing && respond) {
+ return (
+
+
Approve action: {args.action}
+
Reason: {args.reason}
+
+
+
+ );
+ }
+ return
Status: {status}
;
+ },
+ });
+
+ return
Approval system active
;
+}
+```
+
+## Parameters
+
+The hook accepts a single `ReactHumanInTheLoop` object with the following properties:
+
+### name
+
+`string` **(required)**
+
+A unique identifier for the human-in-the-loop tool.
+
+```tsx
+useHumanInTheLoop({
+ name: "confirmDeletion",
+ // ...
+});
+```
+
+### description
+
+`string` **(optional)**
+
+Describes the tool's purpose to help agents understand when human approval is needed.
+
+```tsx
+useHumanInTheLoop({
+ name: "sensitiveAction",
+ description: "Requires human confirmation for sensitive operations",
+ // ...
+});
+```
+
+### parameters
+
+`z.ZodType` **(optional)**
+
+A Zod schema defining the parameters the agent will provide when requesting human input.
+
+```tsx
+import { z } from "zod";
+
+useHumanInTheLoop({
+ name: "reviewChanges",
+ parameters: z.object({
+ changes: z.array(z.string()),
+ impact: z.enum(["low", "medium", "high"]),
+ estimatedTime: z.number(),
+ }),
+ // ...
+});
+```
+
+### render
+
+`React.ComponentType` **(required)**
+
+A React component that renders the interactive UI. It receives different props based on the current status:
+
+#### Status: InProgress
+
+Initial state when the tool is called but not yet executing:
+
+```tsx
+{
+ name: string;
+ description: string;
+ args: Partial; // Partial arguments as they're being streamed
+ status: ToolCallStatus.InProgress;
+ result: undefined;
+ respond: undefined;
+}
+```
+
+#### Status: Executing
+
+Active state where user interaction is required:
+
+```tsx
+{
+ name: string;
+ description: string;
+ args: T; // Complete arguments
+ status: ToolCallStatus.Executing;
+ result: undefined;
+ respond: (result: unknown) => Promise; // Callback to provide response
+}
+```
+
+#### Status: Complete
+
+Final state after user has responded:
+
+```tsx
+{
+ name: string;
+ description: string;
+ args: T; // Complete arguments
+ status: ToolCallStatus.Complete;
+ result: string; // The response provided via respond()
+ respond: undefined;
+}
+```
+
+### followUp
+
+`boolean` **(optional, default: true)**
+
+Controls whether the agent continues after receiving the human response. Provided for completeness, but typically you
+would want the agent to continue (default behavior).
+
+```tsx
+useHumanInTheLoop({
+ name: "finalConfirmation",
+ followUp: false, // Don't continue after confirmation
+ // ...
+});
+```
+
+### agentId
+
+`string` **(optional)**
+
+Restricts this tool to a specific agent.
+
+```tsx
+useHumanInTheLoop({
+ name: "adminApproval",
+ agentId: "admin-assistant",
+ // ...
+});
+```
+
+## Differences from useFrontendTool
+
+While `useFrontendTool` executes immediately and returns results, `useHumanInTheLoop`:
+
+- Pauses execution until human input is received
+- Provides a `respond` callback during the Executing state
+- Manages status transitions automatically
+- Is designed specifically for approval workflows and interactive decisions
+
+Choose `useHumanInTheLoop` when you need human oversight, and `useFrontendTool` for automated tool execution.
diff --git a/apps/docs/reference/use-render-tool-call.mdx b/apps/docs/reference/use-render-tool-call.mdx
new file mode 100644
index 00000000..3cb49f32
--- /dev/null
+++ b/apps/docs/reference/use-render-tool-call.mdx
@@ -0,0 +1,262 @@
+---
+title: useRenderToolCall
+description: "useRenderToolCall Hook API Reference"
+---
+
+
+ You would use this hook if you use the headless functionality of CopilotKit, rendering your own chat UI instead of the
+ default `CopilotChat`. If you are using `CopilotChat`, you don't need to use this hook.
+
+
+`useRenderToolCall` is a React hook that provides a function to render visual representations of tool calls in the chat
+interface. It manages the rendering of tool execution states (InProgress, Executing, Complete) based on configured
+render functions.
+
+## What is useRenderToolCall?
+
+The useRenderToolCall hook:
+
+- Returns a render function for tool calls
+- Automatically determines the appropriate status (InProgress, Executing, or Complete)
+- Manages tool execution state transitions
+- Supports agent-specific and wildcard renderers
+- Integrates with CopilotKit's tool rendering system
+
+## Basic Usage
+
+```tsx
+import { useRenderToolCall } from "@copilotkitnext/react";
+import { ToolCall } from "@ag-ui/core";
+
+function ToolCallDisplay({ toolCall, toolMessage }) {
+ const renderToolCall = useRenderToolCall();
+
+ return
{renderToolCall({ toolCall, toolMessage })}
;
+}
+```
+
+## Return Value
+
+The hook returns a function with the following signature:
+
+```tsx
+(props: UseRenderToolCallProps) => React.ReactElement | null;
+```
+
+### UseRenderToolCallProps
+
+```tsx
+interface UseRenderToolCallProps {
+ toolCall: ToolCall; // The tool call to render
+ toolMessage?: ToolMessage; // Optional result message
+}
+```
+
+## How It Works
+
+### Status Determination
+
+The render function automatically determines the tool's status:
+
+1. **Complete**: When a `toolMessage` is provided
+2. **Executing**: When the tool is currently running (tracked internally)
+3. **InProgress**: Default state when neither complete nor executing
+
+### Renderer Selection
+
+The function selects renderers based on priority:
+
+1. **Exact match** with matching agentId
+2. **Exact match** without agentId (global)
+3. **Exact match** (any agentId)
+4. **Wildcard** renderer (`*`)
+5. **No render** (returns null)
+
+## Examples
+
+### Basic Tool Call Rendering
+
+```tsx
+import { useRenderToolCall } from "@copilotkitnext/react";
+import { AssistantMessage } from "@ag-ui/core";
+
+function ChatMessage({ message }: { message: AssistantMessage }) {
+ const renderToolCall = useRenderToolCall();
+
+ if (!message.toolCalls) {
+ return