@meetsmore-oss/use-ai-client 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  import { z } from 'zod';
2
2
  export { z } from 'zod';
3
- import * as _meetsmore_oss_use_ai_core from '@meetsmore-oss/use-ai-core';
4
- import { ToolAnnotations, ToolDefinition, WorkflowStatus, FeedbackValue, AgentInfo, McpHeadersMap, MultimodalContent, AGUIEvent, Message as Message$1, UseAIClientMessage } from '@meetsmore-oss/use-ai-core';
3
+ import { ToolAnnotations, ToolDefinition, WorkflowStatus, FeedbackValue, AgentInfo, MultimodalContent, UseAIForwardedProps, AGUIEvent, Message as Message$1, UseAIClientMessage, ToolApprovalRequestEvent } from '@meetsmore-oss/use-ai-core';
5
4
  export { AgentInfo, ToolAnnotations, ToolDefinition } from '@meetsmore-oss/use-ai-core';
6
5
  import * as react_jsx_runtime from 'react/jsx-runtime';
7
- import React$1, { ReactNode } from 'react';
6
+ import React$1, { MutableRefObject, RefObject, ReactNode } from 'react';
8
7
 
9
8
  /**
10
9
  * Options for configuring tool behavior.
@@ -941,7 +940,6 @@ declare class UseAIClient {
941
940
  private _tools;
942
941
  private _messages;
943
942
  private _state;
944
- private mcpHeadersProvider?;
945
943
  private _availableAgents;
946
944
  private _defaultAgent;
947
945
  private _selectedAgent;
@@ -982,20 +980,15 @@ declare class UseAIClient {
982
980
  * @param state - The current state object to provide to the AI
983
981
  */
984
982
  updateState(state: unknown): void;
985
- /**
986
- * Sets the MCP headers provider.
987
- * The provider will be called each time a message is sent to get fresh headers.
988
- *
989
- * @param provider - Function that returns MCP headers configuration
990
- */
991
- setMcpHeadersProvider(provider: () => McpHeadersMap | Promise<McpHeadersMap>): void;
992
983
  /**
993
984
  * Sends a user prompt to the AI.
994
985
  *
995
986
  * @param prompt - The user's prompt/question (text part)
996
987
  * @param multimodalContent - Optional multimodal content (text, images, files)
988
+ * @param forwardedProps - Optional props to forward to the server (e.g., telemetryMetadata, mcpHeaders).
989
+ * Internally merged with other forwardedProps.
997
990
  */
998
- sendPrompt(prompt: string, multimodalContent?: MultimodalContent[]): Promise<void>;
991
+ sendPrompt(prompt: string, multimodalContent?: MultimodalContent[], forwardedProps?: UseAIForwardedProps): Promise<void>;
999
992
  /**
1000
993
  * Sends the result of a tool execution back to the server.
1001
994
  *
@@ -1150,6 +1143,76 @@ declare class UseAIClient {
1150
1143
  submitFeedback(messageId: string, traceId: string, feedback: FeedbackValue): void;
1151
1144
  }
1152
1145
 
1146
+ interface RegisterToolsOptions {
1147
+ /** Mark component as invisible (no visual state, skip prompt wait) */
1148
+ invisible?: boolean;
1149
+ }
1150
+ /**
1151
+ * Pending tool approval request state.
1152
+ */
1153
+ interface PendingToolApproval {
1154
+ toolCallId: string;
1155
+ toolCallName: string;
1156
+ toolCallArgs: Record<string, unknown>;
1157
+ annotations?: ToolAnnotations;
1158
+ }
1159
+ interface UseToolSystemOptions {
1160
+ /** Reference to the UseAI client for sending responses */
1161
+ clientRef: RefObject<UseAIClient | null>;
1162
+ /** Builds the aggregated state from all registered prompts */
1163
+ buildState: () => unknown;
1164
+ }
1165
+ interface UseToolSystemReturn {
1166
+ /** Registers tools for a specific component */
1167
+ registerTools: (id: string, tools: ToolsDefinition, options?: RegisterToolsOptions) => void;
1168
+ /** Unregisters tools for a specific component */
1169
+ unregisterTools: (id: string) => void;
1170
+ /** Checks if a component is marked as invisible */
1171
+ isInvisible: (id: string) => boolean;
1172
+ /** All tools aggregated from registered components */
1173
+ aggregatedTools: ToolsDefinition;
1174
+ /** Whether any tools are registered */
1175
+ hasTools: boolean;
1176
+ /** Ref to current aggregated tools (for use in closures) */
1177
+ aggregatedToolsRef: MutableRefObject<ToolsDefinition>;
1178
+ /** Signals that a component has completed its registration in useLayoutEffect */
1179
+ signalReady: (id: string) => void;
1180
+ /** Current tool registry version (increments when tools change) */
1181
+ toolRegistryVersion: number;
1182
+ /** Registers a waiter function for a component (called when tool exec needs to wait for re-render) */
1183
+ registerWaiter: (id: string, waiter: () => Promise<void>) => void;
1184
+ /** Unregisters a waiter function */
1185
+ unregisterWaiter: (id: string) => void;
1186
+ /** All pending tool approval requests */
1187
+ pendingApprovals: PendingToolApproval[];
1188
+ /** Handle a tool approval request event from the server */
1189
+ handleApprovalRequest: (event: ToolApprovalRequestEvent) => void;
1190
+ /** Execute a tool call and send the response to the server */
1191
+ executeToolCall: (toolCallId: string, name: string, input: unknown) => Promise<void>;
1192
+ /** Store a tool call as pending approval (deferred execution) */
1193
+ storePendingToolCall: (toolCallId: string, name: string, input: unknown, toolCallData: {
1194
+ name: string;
1195
+ args: string;
1196
+ }) => void;
1197
+ /** Approve all pending tool calls and execute them */
1198
+ approveAll: () => Promise<void>;
1199
+ /** Reject all pending tool calls with optional reason */
1200
+ rejectAll: (reason?: string) => void;
1201
+ }
1202
+ /**
1203
+ * Unified hook for the tool lifecycle: registration, waiter coordination,
1204
+ * and execution (including approval flow).
1205
+ *
1206
+ * Merges what were previously three separate concerns:
1207
+ * - Tool registry (registration, aggregation, ownership tracking)
1208
+ * - Waiters (waiting for component re-renders after tool execution)
1209
+ * - Tool execution (running tools, sending responses, approval flow)
1210
+ *
1211
+ * The only external dependency is `buildState` from prompt management,
1212
+ * which provides the aggregated app state sent alongside tool responses.
1213
+ */
1214
+ declare function useToolSystem({ clientRef, buildState, }: UseToolSystemOptions): UseToolSystemReturn;
1215
+
1153
1216
  /**
1154
1217
  * Options for programmatically sending a message via sendMessage().
1155
1218
  */
@@ -1162,97 +1225,45 @@ interface SendMessageOptions {
1162
1225
  openChat?: boolean;
1163
1226
  /** Metadata to set on the new chat (only used when newChat: true) */
1164
1227
  metadata?: ChatMetadata;
1228
+ /**
1229
+ * Forwarded props for observability and configuration (e.g., telemetryMetadata, mcpHeaders).
1230
+ * This is merged with provider-level forwardedProps (message-level takes precedence).
1231
+ */
1232
+ forwardedProps?: UseAIForwardedProps;
1165
1233
  }
1166
- interface UseChatManagementOptions {
1167
- /** Chat repository for persistence */
1168
- repository: ChatRepository;
1169
- /** Reference to the UseAIClient (can be null during initialization) */
1170
- clientRef: React.MutableRefObject<UseAIClient | null>;
1171
- /** Current messages state (owned by provider) */
1172
- messages: Message[];
1173
- /** Setter for messages state (owned by provider) */
1174
- setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
1175
- /** Callback to send a message (from UseAIProvider) */
1176
- onSendMessage?: (message: string, attachments?: FileAttachment[]) => Promise<void>;
1234
+ interface UseMessageQueueOptions {
1235
+ /** The function that actually sends a message (the provider's handleSendMessage) */
1236
+ sendFn: (message: string, attachments?: FileAttachment[], forwardedProps?: UseAIForwardedProps) => Promise<void>;
1237
+ /** Creates a new chat */
1238
+ createNewChat: (options?: CreateChatOptions) => Promise<string>;
1177
1239
  /** Callback to open/close the chat panel */
1178
1240
  setOpen?: (open: boolean) => void;
1179
1241
  /** Whether the client is connected */
1180
- connected?: boolean;
1181
- /** Whether the AI is currently loading/processing a response */
1182
- loading?: boolean;
1242
+ connected: boolean;
1243
+ /** Whether the AI is currently loading/processing */
1244
+ loading: boolean;
1183
1245
  /** Whether there's a pending tool approval blocking the queue */
1184
- hasPendingApproval?: boolean;
1246
+ hasPendingApproval: boolean;
1185
1247
  }
1186
- interface UseChatManagementReturn {
1187
- /** Current active chat ID where AI responses are saved */
1188
- currentChatId: string | null;
1189
- /** Chat loaded for viewing but not yet active for AI responses */
1190
- pendingChatId: string | null;
1191
- /** The displayed chat ID (pending or current) */
1192
- displayedChatId: string | null;
1193
- /** Creates a new chat and switches to it */
1194
- createNewChat: (options?: CreateChatOptions) => Promise<string>;
1195
- /** Loads an existing chat by ID */
1196
- loadChat: (chatId: string) => Promise<void>;
1197
- /** Deletes a chat by ID */
1198
- deleteChat: (chatId: string) => Promise<void>;
1199
- /** Lists all available chats */
1200
- listChats: () => Promise<Array<Omit<Chat, 'messages'>>>;
1201
- /** Clears the current chat messages */
1202
- clearCurrentChat: () => Promise<void>;
1203
- /** Activates the pending chat (called when user sends first message) */
1204
- activatePendingChat: () => string | null;
1205
- /** Saves a user message to storage and reloads messages */
1206
- saveUserMessage: (chatId: string, content: PersistedMessageContent) => Promise<boolean>;
1207
- /** Saves an AI response to storage and optionally reloads messages */
1208
- saveAIResponse: (content: string, displayMode?: 'default' | 'error', traceId?: string) => Promise<void>;
1209
- /** Reloads messages from storage for the given chat ID */
1210
- reloadMessages: (chatId: string) => Promise<void>;
1248
+ interface UseMessageQueueReturn {
1211
1249
  /**
1212
1250
  * Programmatically send a message to the chat.
1213
- * Throws on failure (e.g., not connected, no onSendMessage callback).
1251
+ * Messages are queued and processed one at a time.
1252
+ * Throws on failure (e.g., not connected, no sendFn).
1214
1253
  */
1215
1254
  sendMessage: (message: string, options?: SendMessageOptions) => Promise<void>;
1216
- /** Get the current chat object. Metadata is frozen to prevent accidental mutation. */
1217
- getCurrentChat: () => Promise<Chat | null>;
1218
- /** Update metadata for the current chat */
1219
- updateMetadata: (metadata: ChatMetadata, overwrite?: boolean) => Promise<void>;
1220
- /** Snapshot refs for use in event handlers */
1221
- currentChatIdSnapshot: React.MutableRefObject<string | null>;
1222
- pendingChatIdSnapshot: React.MutableRefObject<string | null>;
1223
1255
  }
1224
1256
  /**
1225
- * Hook for managing chat lifecycle operations.
1226
- *
1227
- * Features:
1228
- * - Creates, loads, deletes chats
1229
- * - Manages pending/active chat state machine
1230
- * - Saves user messages and AI responses
1231
- * - Auto-generates chat titles
1232
- * - Initializes with most recent chat or creates new one
1257
+ * Hook for queuing and sending programmatic messages.
1233
1258
  *
1234
- * @example
1235
- * ```typescript
1236
- * const {
1237
- * currentChatId,
1238
- * pendingChatId,
1239
- * createNewChat,
1240
- * loadChat,
1241
- * deleteChat,
1242
- * listChats,
1243
- * clearCurrentChat,
1244
- * activatePendingChat,
1245
- * saveUserMessage,
1246
- * saveAIResponse,
1247
- * } = useChatManagement({
1248
- * repository: chatRepository,
1249
- * clientRef,
1250
- * messages,
1251
- * setMessages,
1252
- * });
1253
- * ```
1259
+ * Handles:
1260
+ * - Message queuing (one at a time)
1261
+ * - Waiting for loading + approval to complete between messages
1262
+ * - Creating new chats before sending
1263
+ * - Opening the chat panel after sending
1264
+ * - Converting File[] to FileAttachment[]
1254
1265
  */
1255
- declare function useChatManagement({ repository, clientRef, messages, setMessages, onSendMessage, setOpen, connected, loading, hasPendingApproval, }: UseChatManagementOptions): UseChatManagementReturn;
1266
+ declare function useMessageQueue({ sendFn, createNewChat, setOpen, connected, loading, hasPendingApproval, }: UseMessageQueueOptions): UseMessageQueueReturn;
1256
1267
 
1257
1268
  /**
1258
1269
  * Chat management context (from useChatManagement hook).
@@ -1313,15 +1324,19 @@ interface CommandContextValue {
1313
1324
  delete: (id: string) => Promise<void>;
1314
1325
  }
1315
1326
  /**
1316
- * Tool registry context (from useToolRegistry hook).
1327
+ * Tool system context (from useToolSystem hook).
1317
1328
  */
1318
1329
  interface ToolRegistryContextValue {
1319
1330
  /** Registers tools for a specific component */
1320
- register: (id: string, tools: ToolsDefinition, options?: {
1321
- invisible?: boolean;
1322
- }) => void;
1331
+ register: (id: string, tools: ToolsDefinition, options?: RegisterToolsOptions) => void;
1323
1332
  /** Unregisters tools for a specific component */
1324
1333
  unregister: (id: string) => void;
1334
+ /** Signals that a component has completed registration in useLayoutEffect */
1335
+ signalReady: (id: string) => void;
1336
+ /** Registers a waiter function for a component */
1337
+ registerWaiter: (id: string, waiter: () => Promise<void>) => void;
1338
+ /** Unregisters a waiter function */
1339
+ unregisterWaiter: (id: string) => void;
1325
1340
  }
1326
1341
  /**
1327
1342
  * Prompt management context.
@@ -1329,10 +1344,6 @@ interface ToolRegistryContextValue {
1329
1344
  interface PromptsContextValue {
1330
1345
  /** Updates the prompt and suggestions for a specific component */
1331
1346
  update: (id: string, prompt?: string, suggestions?: string[]) => void;
1332
- /** Registers a waiter function for a component */
1333
- registerWaiter: (id: string, waiter: () => Promise<void>) => void;
1334
- /** Unregisters a waiter function */
1335
- unregisterWaiter: (id: string) => void;
1336
1347
  }
1337
1348
  /**
1338
1349
  * Context value provided by UseAIProvider.
@@ -1345,15 +1356,15 @@ interface UseAIContextValue {
1345
1356
  connected: boolean;
1346
1357
  /** The underlying WebSocket client instance */
1347
1358
  client: UseAIClient | null;
1348
- /** Tool registry (from useToolRegistry hook) */
1359
+ /** Tool system (registry, waiters, execution) */
1349
1360
  tools: ToolRegistryContextValue;
1350
1361
  /** Prompt management */
1351
1362
  prompts: PromptsContextValue;
1352
- /** Chat management (from useChatManagement hook) */
1363
+ /** Chat management */
1353
1364
  chat: ChatContextValue;
1354
- /** Agent selection (from useAgentSelection hook) */
1365
+ /** Agent selection */
1355
1366
  agents: AgentContextValue;
1356
- /** Command management (from useCommandManagement hook) */
1367
+ /** Command management */
1357
1368
  commands: CommandContextValue;
1358
1369
  }
1359
1370
  /**
@@ -1407,33 +1418,41 @@ interface UseAIProviderProps extends UseAIConfig {
1407
1418
  */
1408
1419
  chatRepository?: ChatRepository;
1409
1420
  /**
1410
- * Callback to provide HTTP headers for MCP endpoints.
1411
- * Called each time AI is invoked by use-ai.
1412
- * Returns a mapping of MCP endpoint patterns to header configurations.
1413
- *
1414
- * Patterns can be:
1415
- * - Constant strings: `https://api.example.com` - Exact match
1416
- * - Glob patterns: `https://*.meetsmore.com` - Wildcard matching using picomatch
1421
+ * Provider function for forwarded props (telemetry metadata, MCP headers, etc.).
1422
+ * Called before each message is sent. Can be sync or async.
1423
+ * Props from this provider are merged with message-level forwardedProps,
1424
+ * with message-level taking precedence.
1417
1425
  *
1418
1426
  * @example
1419
- * ```typescript
1420
- * mcpHeadersProvider={() => ({
1421
- * // Exact match
1422
- * 'https://api.example.com': {
1423
- * headers: { 'Authorization': `Bearer ${userToken}` }
1424
- * },
1425
- * // Wildcard subdomain
1426
- * 'https://*.meetsmore.com': {
1427
- * headers: { 'X-API-Key': apiKey }
1428
- * },
1429
- * // Multiple wildcards
1430
- * '*://*.example.com': {
1431
- * headers: { 'X-Custom': 'value' }
1432
- * }
1433
- * })}
1427
+ * ```tsx
1428
+ * <UseAIProvider
1429
+ * serverUrl="wss://your-server.com"
1430
+ * forwardedPropsProvider={() => ({
1431
+ * mcpHeaders: {
1432
+ * // Exact match
1433
+ * 'https://api.example.com': {
1434
+ * headers: { 'Authorization': `Bearer ${userToken}` }
1435
+ * },
1436
+ * // Wildcard subdomain
1437
+ * 'https://*.meetsmore.com': {
1438
+ * headers: { 'X-API-Key': apiKey }
1439
+ * },
1440
+ * // Multiple wildcards
1441
+ * '*://*.example.com': {
1442
+ * headers: { 'X-Custom': 'value' }
1443
+ * },
1444
+ * },
1445
+ * telemetryMetadata: {
1446
+ * userId: currentUser.id,
1447
+ * tenantId: tenant.id,
1448
+ * },
1449
+ * })}
1450
+ * >
1451
+ * <App />
1452
+ * </UseAIProvider>
1434
1453
  * ```
1435
1454
  */
1436
- mcpHeadersProvider?: () => _meetsmore_oss_use_ai_core.McpHeadersMap | Promise<_meetsmore_oss_use_ai_core.McpHeadersMap>;
1455
+ forwardedPropsProvider?: () => UseAIForwardedProps | Promise<UseAIForwardedProps>;
1437
1456
  /**
1438
1457
  * Configuration for file uploads.
1439
1458
  * File upload is enabled by default with EmbedFileUploadBackend, 10MB max size,
@@ -1547,22 +1566,10 @@ interface UseAIProviderProps extends UseAIConfig {
1547
1566
  * }
1548
1567
  * ```
1549
1568
  */
1550
- declare function UseAIProvider({ serverUrl, children, systemPrompt, CustomButton, CustomChat, chatRepository, mcpHeadersProvider, fileUploadConfig: fileUploadConfigProp, commandRepository, renderChat, theme: customTheme, strings: customStrings, visibleAgentIds, onOpenChange, }: UseAIProviderProps): react_jsx_runtime.JSX.Element;
1569
+ declare function UseAIProvider({ serverUrl, children, systemPrompt, CustomButton, CustomChat, chatRepository, forwardedPropsProvider, fileUploadConfig: fileUploadConfigProp, commandRepository, renderChat, theme: customTheme, strings: customStrings, visibleAgentIds, onOpenChange, }: UseAIProviderProps): react_jsx_runtime.JSX.Element;
1551
1570
  /**
1552
1571
  * Hook to access the UseAI context.
1553
1572
  * When used outside a UseAIProvider, returns a no-op context and logs a warning.
1554
- * This allows components with useAI hooks to render even when UseAIProvider
1555
- * is conditionally not rendered (e.g., feature flagged).
1556
- *
1557
- * @returns The UseAI context value (or no-op if provider is missing)
1558
- *
1559
- * @example
1560
- * ```typescript
1561
- * function MyComponent() {
1562
- * const { connected, client } = useAIContext();
1563
- * return <div>Connected: {connected}</div>;
1564
- * }
1565
- * ```
1566
1573
  */
1567
1574
  declare function useAIContext(): UseAIContextValue;
1568
1575
 
@@ -2012,6 +2019,63 @@ interface UseSlashCommandsReturn {
2012
2019
  */
2013
2020
  declare function useSlashCommands({ commands, onCommandSelect, onSaveCommand, onRenameCommand, onDeleteCommand, }: UseSlashCommandsOptions): UseSlashCommandsReturn;
2014
2021
 
2022
+ interface UseChatManagementOptions {
2023
+ /** Chat repository for persistence */
2024
+ repository: ChatRepository;
2025
+ /** Reference to the UseAIClient (can be null during initialization) */
2026
+ clientRef: React.MutableRefObject<UseAIClient | null>;
2027
+ /** Current messages state (owned by provider) */
2028
+ messages: Message[];
2029
+ /** Setter for messages state (owned by provider) */
2030
+ setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
2031
+ /** Whether the client is connected */
2032
+ connected?: boolean;
2033
+ }
2034
+ interface UseChatManagementReturn {
2035
+ /** Current active chat ID where AI responses are saved */
2036
+ currentChatId: string | null;
2037
+ /** Chat loaded for viewing but not yet active for AI responses */
2038
+ pendingChatId: string | null;
2039
+ /** The displayed chat ID (pending or current) */
2040
+ displayedChatId: string | null;
2041
+ /** Creates a new chat and switches to it */
2042
+ createNewChat: (options?: CreateChatOptions) => Promise<string>;
2043
+ /** Loads an existing chat by ID */
2044
+ loadChat: (chatId: string) => Promise<void>;
2045
+ /** Deletes a chat by ID */
2046
+ deleteChat: (chatId: string) => Promise<void>;
2047
+ /** Lists all available chats */
2048
+ listChats: () => Promise<Array<Omit<Chat, 'messages'>>>;
2049
+ /** Clears the current chat messages */
2050
+ clearCurrentChat: () => Promise<void>;
2051
+ /** Activates the pending chat (called when user sends first message) */
2052
+ activatePendingChat: () => string | null;
2053
+ /** Saves a user message to storage and reloads messages */
2054
+ saveUserMessage: (chatId: string, content: PersistedMessageContent) => Promise<boolean>;
2055
+ /** Saves an AI response to storage and optionally reloads messages */
2056
+ saveAIResponse: (content: string, displayMode?: 'default' | 'error', traceId?: string) => Promise<void>;
2057
+ /** Reloads messages from storage for the given chat ID */
2058
+ reloadMessages: (chatId: string) => Promise<void>;
2059
+ /** Get the current chat object. Metadata is frozen to prevent accidental mutation. */
2060
+ getCurrentChat: () => Promise<Chat | null>;
2061
+ /** Update metadata for the current chat */
2062
+ updateMetadata: (metadata: ChatMetadata, overwrite?: boolean) => Promise<void>;
2063
+ /** Snapshot refs for use in event handlers */
2064
+ currentChatIdSnapshot: React.MutableRefObject<string | null>;
2065
+ pendingChatIdSnapshot: React.MutableRefObject<string | null>;
2066
+ }
2067
+ /**
2068
+ * Hook for managing chat lifecycle operations.
2069
+ *
2070
+ * Features:
2071
+ * - Creates, loads, deletes chats
2072
+ * - Manages pending/active chat state machine
2073
+ * - Saves user messages and AI responses
2074
+ * - Auto-generates chat titles
2075
+ * - Initializes with most recent chat or creates new one
2076
+ */
2077
+ declare function useChatManagement({ repository, clientRef, messages, setMessages, connected, }: UseChatManagementOptions): UseChatManagementReturn;
2078
+
2015
2079
  interface UseAgentSelectionOptions {
2016
2080
  /** Reference to the UseAIClient (can be null during initialization) */
2017
2081
  clientRef: React.MutableRefObject<UseAIClient | null>;
@@ -2119,33 +2183,6 @@ interface UseCommandManagementReturn {
2119
2183
  */
2120
2184
  declare function useCommandManagement({ repository, }?: UseCommandManagementOptions): UseCommandManagementReturn;
2121
2185
 
2122
- interface RegisterToolsOptions {
2123
- /** Mark component as invisible (no visual state, skip prompt wait) */
2124
- invisible?: boolean;
2125
- }
2126
- interface UseToolRegistryReturn {
2127
- /** Registers tools for a specific component */
2128
- registerTools: (id: string, tools: ToolsDefinition, options?: RegisterToolsOptions) => void;
2129
- /** Unregisters tools for a specific component */
2130
- unregisterTools: (id: string) => void;
2131
- /** Checks if a component is marked as invisible */
2132
- isInvisible: (id: string) => boolean;
2133
- /** All tools aggregated from registered components */
2134
- aggregatedTools: ToolsDefinition;
2135
- /** Whether any tools are registered */
2136
- hasTools: boolean;
2137
- /** Ref to current aggregated tools (for use in closures) */
2138
- aggregatedToolsRef: React.MutableRefObject<ToolsDefinition>;
2139
- /** Ref mapping tool names to component IDs */
2140
- toolOwnershipRef: React.MutableRefObject<Map<string, string>>;
2141
- }
2142
- /**
2143
- * Hook for managing tool registration and aggregation.
2144
- *
2145
- * Only handles tools - prompt management is handled separately.
2146
- */
2147
- declare function useToolRegistry(): UseToolRegistryReturn;
2148
-
2149
2186
  interface UsePromptStateOptions {
2150
2187
  /** System prompt to include in state */
2151
2188
  systemPrompt?: string;
@@ -2157,16 +2194,12 @@ interface UsePromptStateOptions {
2157
2194
  interface UsePromptStateReturn {
2158
2195
  /** Updates the prompt and suggestions for a specific component */
2159
2196
  updatePrompt: (id: string, prompt?: string, suggestions?: string[]) => void;
2160
- /** Registers a waiter function for a component */
2161
- registerWaiter: (id: string, waiter: () => Promise<void>) => void;
2162
- /** Unregisters a waiter function */
2163
- unregisterWaiter: (id: string) => void;
2164
- /** Gets the waiter function for a component */
2165
- getWaiter: (id: string) => (() => Promise<void>) | undefined;
2166
2197
  /** All suggestions aggregated from registered components */
2167
2198
  aggregatedSuggestions: string[];
2168
- /** Ref mapping component IDs to prompts */
2169
- promptsRef: React.MutableRefObject<Map<string, string>>;
2199
+ /** Builds the aggregated state from all registered prompts */
2200
+ buildStateFromPrompts: () => {
2201
+ context: string;
2202
+ } | null;
2170
2203
  }
2171
2204
  /**
2172
2205
  * Hook for managing prompt state across multiple useAI hooks.
@@ -2174,11 +2207,56 @@ interface UsePromptStateReturn {
2174
2207
  * Handles:
2175
2208
  * - Storing prompts and suggestions per component
2176
2209
  * - Updating client state when prompts change
2177
- * - Managing waiter functions for prompt change notifications
2178
2210
  * - Aggregating suggestions from all components
2179
2211
  */
2180
2212
  declare function usePromptState({ systemPrompt, clientRef, connected, }: UsePromptStateOptions): UsePromptStateReturn;
2181
2213
 
2214
+ interface UseServerEventsOptions {
2215
+ /** Tool system for executing tools and looking up tool metadata */
2216
+ toolSystem: UseToolSystemReturn;
2217
+ /** Saves an AI response to chat storage */
2218
+ saveAIResponse: (content: string, displayMode?: 'default' | 'error', traceId?: string) => Promise<void>;
2219
+ /** UI strings for error messages and tool execution fallbacks */
2220
+ strings: UseAIStrings;
2221
+ }
2222
+ interface ExecutingToolDisplay {
2223
+ displayText: string;
2224
+ }
2225
+ interface UseServerEventsReturn {
2226
+ /** Whether the AI is currently loading/processing a response */
2227
+ loading: boolean;
2228
+ /** Set the loading state (e.g., when sending a message) */
2229
+ setLoading: React.Dispatch<React.SetStateAction<boolean>>;
2230
+ /** Current streaming text from the AI response */
2231
+ streamingText: string;
2232
+ /** Clear streaming text (e.g., when starting a new message) */
2233
+ clearStreamingText: () => void;
2234
+ /** Currently executing tool info for UI display, or null */
2235
+ executingTool: ExecutingToolDisplay | null;
2236
+ /** Ref tracking which chat the current streaming text belongs to */
2237
+ streamingChatIdRef: React.MutableRefObject<string | null>;
2238
+ /**
2239
+ * Handles a server event. Called from the provider's client subscription.
2240
+ * Takes the client instance so it can access client-internal state
2241
+ * (currentToolCalls, currentMessageContent).
2242
+ */
2243
+ handleServerEvent: (client: UseAIClient, event: AGUIEvent) => Promise<void>;
2244
+ }
2245
+ /**
2246
+ * Hook that owns all server event handling state and logic.
2247
+ *
2248
+ * Manages:
2249
+ * - Loading state (set on message send, cleared on RUN_FINISHED/RUN_ERROR)
2250
+ * - Streaming text accumulation (TEXT_MESSAGE_CONTENT/END events)
2251
+ * - Executing tool display (TOOL_CALL_START/END events)
2252
+ * - Tool execution dispatch (delegates to toolSystem)
2253
+ * - Error handling (RUN_ERROR events)
2254
+ *
2255
+ * The provider creates the client and subscribes `handleServerEvent` to it.
2256
+ * This hook doesn't manage the client lifecycle — only the event handling.
2257
+ */
2258
+ declare function useServerEvents({ toolSystem, saveAIResponse, strings, }: UseServerEventsOptions): UseServerEventsReturn;
2259
+
2182
2260
  interface UseFeedbackOptions {
2183
2261
  /** Reference to the UseAIClient */
2184
2262
  clientRef: React.MutableRefObject<UseAIClient | null>;
@@ -2298,4 +2376,4 @@ interface UseDropdownStateOptions {
2298
2376
  */
2299
2377
  declare function useDropdownState(options?: UseDropdownStateOptions): UseDropdownStateReturn;
2300
2378
 
2301
- export { type AgentContextValue, type Chat, type ChatContextValue, type ChatMetadata, type ChatPanelProps, type ChatRepository, CloseButton, type CommandContextValue, type CommandRepository, type CreateChatOptions, type CreateCommandOptions, DEFAULT_MAX_FILE_SIZE, type DefinedTool, type DropZoneProps, EmbedFileUploadBackend, type FileAttachment, type FileProcessingState, type FileProcessingStatus, type FileTransformer, type FileTransformerContext, type FileTransformerMap, type FileUploadBackend, type FileUploadConfig, type FloatingButtonProps, type InlineSaveProps, type ListChatsOptions, type ListCommandsOptions, LocalStorageChatRepository, LocalStorageCommandRepository, type Message, type PersistedContentPart, type PersistedFileContent, type PersistedFileMetadata, type PersistedMessage, type PersistedMessageContent, type PersistedTextContent, type ProcessAttachmentsConfig, type PromptsContextValue, type RegisterToolsOptions, type SavedCommand, type SendMessageOptions, type ToolOptions, type ToolRegistryContextValue, type ToolsDefinition, type TriggerWorkflowOptions, UseAIChat, UseAIChatPanel, type UseAIChatPanelProps, type UseAIChatPanelStrings, type UseAIChatPanelTheme, type UseAIChatProps, UseAIClient, type UseAIConfig, type UseAIContextValue, UseAIFloatingButton, UseAIFloatingChatWrapper, type UseAIOptions, UseAIProvider, type UseAIProviderProps, type UseAIResult, type UseAIStrings, type UseAITheme, type UseAIWorkflowResult, type UseAgentSelectionOptions, type UseAgentSelectionReturn, type UseChatManagementOptions, type UseChatManagementReturn, type UseCommandManagementOptions, type UseCommandManagementReturn, type UseDropdownStateOptions, type UseDropdownStateReturn, type UseFeedbackOptions, type UseFeedbackReturn, type UseFileUploadOptions, type UseFileUploadReturn, type UsePromptStateOptions, type UsePromptStateReturn, type UseSlashCommandsOptions, type UseSlashCommandsReturn, type UseToolRegistryReturn, type WorkflowProgress, clearTransformationCache, convertToolsToDefinitions, defaultStrings, defaultTheme, defineTool, executeDefinedTool, findTransformerPattern, generateChatId, generateCommandId, generateMessageId, matchesMimeType, processAttachments, useAI, useAIContext, useAIWorkflow, useAgentSelection, useChatManagement, useCommandManagement, useDropdownState, useFeedback, useFileUpload, usePromptState, useSlashCommands, useStableTools, useStrings, useTheme, useToolRegistry, validateCommandName };
2379
+ export { type AgentContextValue, type Chat, type ChatContextValue, type ChatMetadata, type ChatPanelProps, type ChatRepository, CloseButton, type CommandContextValue, type CommandRepository, type CreateChatOptions, type CreateCommandOptions, DEFAULT_MAX_FILE_SIZE, type DefinedTool, type DropZoneProps, EmbedFileUploadBackend, type ExecutingToolDisplay, type FileAttachment, type FileProcessingState, type FileProcessingStatus, type FileTransformer, type FileTransformerContext, type FileTransformerMap, type FileUploadBackend, type FileUploadConfig, type FloatingButtonProps, type InlineSaveProps, type ListChatsOptions, type ListCommandsOptions, LocalStorageChatRepository, LocalStorageCommandRepository, type Message, type PendingToolApproval, type PersistedContentPart, type PersistedFileContent, type PersistedFileMetadata, type PersistedMessage, type PersistedMessageContent, type PersistedTextContent, type ProcessAttachmentsConfig, type PromptsContextValue, type RegisterToolsOptions, type SavedCommand, type SendMessageOptions, type ToolOptions, type ToolRegistryContextValue, type ToolsDefinition, type TriggerWorkflowOptions, UseAIChat, UseAIChatPanel, type UseAIChatPanelProps, type UseAIChatPanelStrings, type UseAIChatPanelTheme, type UseAIChatProps, UseAIClient, type UseAIConfig, type UseAIContextValue, UseAIFloatingButton, UseAIFloatingChatWrapper, type UseAIOptions, UseAIProvider, type UseAIProviderProps, type UseAIResult, type UseAIStrings, type UseAITheme, type UseAIWorkflowResult, type UseAgentSelectionOptions, type UseAgentSelectionReturn, type UseChatManagementOptions, type UseChatManagementReturn, type UseCommandManagementOptions, type UseCommandManagementReturn, type UseDropdownStateOptions, type UseDropdownStateReturn, type UseFeedbackOptions, type UseFeedbackReturn, type UseFileUploadOptions, type UseFileUploadReturn, type UseMessageQueueOptions, type UseMessageQueueReturn, type UsePromptStateOptions, type UsePromptStateReturn, type UseServerEventsOptions, type UseServerEventsReturn, type UseSlashCommandsOptions, type UseSlashCommandsReturn, type UseToolSystemOptions, type UseToolSystemReturn, type WorkflowProgress, clearTransformationCache, convertToolsToDefinitions, defaultStrings, defaultTheme, defineTool, executeDefinedTool, findTransformerPattern, generateChatId, generateCommandId, generateMessageId, matchesMimeType, processAttachments, useAI, useAIContext, useAIWorkflow, useAgentSelection, useChatManagement, useCommandManagement, useDropdownState, useFeedback, useFileUpload, useMessageQueue, usePromptState, useServerEvents, useSlashCommands, useStableTools, useStrings, useTheme, useToolSystem, validateCommandName };