@ash-cloud/ash-ui 0.1.0 → 0.1.1

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,11 +1,11 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { NormalizedToolCall, NormalizedEntry, ToolDisplayConfig, WidgetRenderFunction, WidgetAction, RichContentRenderers, LogEntry, ToolDisplayMode, TodoItem, ToolStatus, ActionType, RichContent } from './types.js';
3
- export { AgentToolAction, AssistantMessageEntry, CommandRunAction, CommandRunResult, ComponentRenderProps, DEFAULT_DISPLAY_CONFIG, ErrorEntry, FileAttachment, FileEditAction, FileReadAction, FileWriteAction, GenericToolAction, GlobAction, LogCategory, LogLevel, McpToolAction, MentionRenderProps, NormalizedEntryType, RichComponentSegment, RichContentSegment, RichMentionSegment, RichTextSegment, SearchAction, ThinkingEntry, TodoStatus, TodoWriteAction, ToolCallEntry, ToolExecutionGroup as ToolExecutionGroupType, ToolResult, UserMessageEntry, WebFetchAction, WebSearchAction, WidgetEntry, WidgetRenderProps, isAgentToolAction, isCommandRunAction, isErrorEntry, isFileEditAction, isFileReadAction, isFileWriteAction, isGenericToolAction, isGlobAction, isMcpToolAction, isSearchAction, isTodoWriteAction, isToolCallEntry, isWebFetchAction, isWebSearchAction, isWidgetEntry } from './types.js';
2
+ import { NormalizedToolCall, NormalizedEntry, ToolDisplayConfig, WidgetRenderFunction, WidgetAction, RichContentRenderers, MessageVariant, TypographyScale, MarkdownComponents, RenderMetadataFunction, MessageMetadata, LogEntry, ToolDisplayMode, TodoItem, ToolStatus, ActionType, RichContent } from './types.js';
3
+ export { AgentToolAction, AssistantMessageEntry, CommandRunAction, CommandRunResult, ComponentRenderProps, DEFAULT_DISPLAY_CONFIG, DEFAULT_STYLE_CONFIG, ErrorEntry, FileAttachment, FileEditAction, FileReadAction, FileWriteAction, GenericToolAction, GlobAction, LogCategory, LogLevel, McpToolAction, MentionRenderProps, MessageRole, MessageStyleConfig, NormalizedEntryType, RichComponentSegment, RichContentSegment, RichMentionSegment, RichTextSegment, SearchAction, ThinkingEntry, TodoStatus, TodoWriteAction, ToolCallEntry, ToolExecutionGroup as ToolExecutionGroupType, ToolResult, UserMessageEntry, WebFetchAction, WebSearchAction, WidgetEntry, WidgetRenderProps, isAgentToolAction, isCommandRunAction, isErrorEntry, isFileEditAction, isFileReadAction, isFileWriteAction, isGenericToolAction, isGlobAction, isMcpToolAction, isSearchAction, isTodoWriteAction, isToolCallEntry, isWebFetchAction, isWebSearchAction, isWidgetEntry } from './types.js';
4
4
  import { ReactNode, DragEvent, ChangeEvent, ClipboardEvent } from 'react';
5
5
  import { ParsedOption } from './utils.js';
6
6
  export { GroupedEntry, ParsedOptionsResult, ToolUseInput, cn, createToolCall, extractTextContent, extractToolCallsFromGroup, formatElapsedTime, formatFileSize, formatTimestamp, formatToolName, generateToolSummary, getActionIcon, getActionLabel, groupEntriesForCompactMode, mapToolToActionType, normalizeToolResult, parseCommandResult, parseMcpToolName, parseOptionsFromContent, truncate, updateToolCallWithResult } from './utils.js';
7
- export { AlertCircleIcon, AlertTriangleIcon, BotIcon, BrainIcon, BugIcon, CheckCircleIcon, CheckIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, ChevronUpIcon, CircleIcon, ClipboardListIcon, ClockIcon, CodeIcon, CopyIcon, EditIcon, ErrorIcon, FileIcon, FilePlusIcon, FolderSearchIcon, GlobeIcon, IconProps, InfoIcon, ListChecksIcon, LoaderIcon, MessageSquareIcon, MoonIcon, PaperclipIcon, PlugIcon, SearchIcon, SendIcon, SparklesIcon, SpinnerIcon, StopCircleIcon, SunIcon, TerminalIcon, ToolIcon, UserIcon, XCircleIcon, XIcon } from './icons.js';
8
- export { BorderRadius, Colors, Keyframes, Shadows, Spacing, Transitions, Typography, Widget, ZIndex, allKeyframesCss, borderRadius, colors, inlineStyles, keyframes, keyframesCss, shadows, spacing, tokensToCssVariables, transitions, typography, widget, zIndex } from './design-tokens.js';
7
+ export { AlertCircleIcon, AlertTriangleIcon, ArrowUpIcon, BotIcon, BrainIcon, BugIcon, CheckCircleIcon, CheckIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, ChevronUpIcon, CircleIcon, ClipboardListIcon, ClockIcon, CodeIcon, CopyIcon, EditIcon, ErrorIcon, FileIcon, FilePlusIcon, FolderSearchIcon, GlobeIcon, HomeIcon, IconProps, InfoIcon, ListChecksIcon, LoaderIcon, MessageSquareIcon, MicrophoneIcon, MoonIcon, PaperclipIcon, PlugIcon, SearchIcon, SendIcon, SparklesIcon, SpinnerIcon, StopCircleIcon, SunIcon, TerminalIcon, ToolIcon, UserIcon, XCircleIcon, XIcon } from './icons.js';
8
+ export { BorderRadius, Colors, CssVars, Keyframes, Shadows, Spacing, Transitions, Typography, Widget, ZIndex, allKeyframesCss, borderRadius, colors, cssVars, inlineStyles, keyframes, keyframesCss, shadows, spacing, tokensToCssVariables, transitions, typography, widget, zIndex } from './design-tokens.js';
9
9
 
10
10
  interface ToolCallCardProps {
11
11
  toolCall: NormalizedToolCall;
@@ -123,6 +123,66 @@ interface MessageListProps {
123
123
  * ```
124
124
  */
125
125
  richContentRenderers?: RichContentRenderers;
126
+ /**
127
+ * Visual variant for user messages
128
+ * @default 'bubble'
129
+ */
130
+ userVariant?: MessageVariant;
131
+ /**
132
+ * Visual variant for assistant messages
133
+ * @default 'bubble'
134
+ */
135
+ assistantVariant?: MessageVariant;
136
+ /**
137
+ * Typography/density scale
138
+ * @default 'compact'
139
+ */
140
+ scale?: TypographyScale;
141
+ /**
142
+ * Show avatar icons next to messages
143
+ * @default true
144
+ */
145
+ showAvatars?: boolean;
146
+ /**
147
+ * Show timestamps on messages
148
+ * @default true
149
+ */
150
+ showTimestamp?: boolean;
151
+ /**
152
+ * Custom markdown component overrides
153
+ *
154
+ * @example
155
+ * ```tsx
156
+ * <MessageList
157
+ * entries={entries}
158
+ * markdownComponents={{
159
+ * h2: ({ children }) => <h2 className="custom-h2">{children}</h2>,
160
+ * code: ({ children, className }) => <CustomCode className={className}>{children}</CustomCode>,
161
+ * }}
162
+ * />
163
+ * ```
164
+ */
165
+ markdownComponents?: MarkdownComponents;
166
+ /**
167
+ * Custom metadata renderer for messages
168
+ *
169
+ * @example
170
+ * ```tsx
171
+ * <MessageList
172
+ * entries={entries}
173
+ * renderMetadata={({ entry, metadata }) => (
174
+ * <div className="text-xs text-gray-500">
175
+ * {metadata?.model} · {entry.timestamp}
176
+ * </div>
177
+ * )}
178
+ * />
179
+ * ```
180
+ */
181
+ renderMetadata?: RenderMetadataFunction;
182
+ /**
183
+ * Metadata to display with messages (e.g., model name)
184
+ */
185
+ metadata?: MessageMetadata;
126
186
  /** Additional class names */
127
187
  className?: string;
128
188
  }
@@ -146,65 +206,105 @@ interface MessageListProps {
146
206
  * <MessageList entries={entries} displayConfig={{ mode: 'compact' }} />
147
207
  * ```
148
208
  */
149
- declare function MessageList({ entries, loading, streamingContent, displayConfig: displayConfigProp, onOptionSelect, renderWidget, onWidgetAction, autoScroll, richContentRenderers, className, }: MessageListProps): react_jsx_runtime.JSX.Element;
209
+ declare function MessageList({ entries, loading, streamingContent, displayConfig: displayConfigProp, onOptionSelect, renderWidget, onWidgetAction, autoScroll, richContentRenderers, userVariant, assistantVariant, scale, showAvatars, showTimestamp, markdownComponents, renderMetadata, metadata, className, }: MessageListProps): react_jsx_runtime.JSX.Element;
150
210
 
151
211
  interface UserMessageProps {
152
212
  entry: NormalizedEntry;
213
+ /** Visual style variant */
214
+ variant?: MessageVariant;
215
+ /** Typography scale */
216
+ scale?: TypographyScale;
217
+ /** Show avatar */
218
+ showAvatar?: boolean;
219
+ /** Show timestamp */
220
+ showTimestamp?: boolean;
221
+ /** Custom metadata renderer */
222
+ renderMetadata?: RenderMetadataFunction;
223
+ /** Additional metadata to display */
224
+ metadata?: MessageMetadata;
153
225
  className?: string;
154
226
  }
155
227
  /**
156
228
  * UserMessage - Display a user message with optional file attachments
157
229
  *
158
- * Uses glassmorphism styling with animated entry.
230
+ * ChatGPT-style: Blue/purple rounded bubbles on right, avatar hidden by default
159
231
  */
160
- declare function UserMessage({ entry, className }: UserMessageProps): react_jsx_runtime.JSX.Element;
232
+ declare function UserMessage({ entry, variant, scale, showAvatar, // Hidden by default for ChatGPT style
233
+ showTimestamp, renderMetadata, metadata, className, }: UserMessageProps): react_jsx_runtime.JSX.Element;
161
234
  interface AssistantMessageProps {
162
235
  entry: NormalizedEntry;
236
+ /** Visual style variant */
237
+ variant?: MessageVariant;
238
+ /** Typography scale */
239
+ scale?: TypographyScale;
240
+ /** Show avatar */
241
+ showAvatar?: boolean;
242
+ /** Show timestamp */
243
+ showTimestamp?: boolean;
163
244
  /** Callback when user selects an option */
164
245
  onOptionSelect?: (optionText: string) => void;
165
246
  /** Custom renderers for rich content segments */
166
247
  richContentRenderers?: RichContentRenderers;
248
+ /** Custom markdown component overrides */
249
+ markdownComponents?: MarkdownComponents;
250
+ /** Custom metadata renderer */
251
+ renderMetadata?: RenderMetadataFunction;
252
+ /** Additional metadata to display */
253
+ metadata?: MessageMetadata;
167
254
  className?: string;
168
255
  }
169
256
  /**
170
257
  * AssistantMessage - Display an assistant message with markdown rendering
171
258
  *
172
- * Uses glassmorphism styling with bot avatar and animated entry.
259
+ * ChatGPT-style: Dark charcoal background with circular green avatar
260
+ * Supports multiple visual variants and custom markdown components.
173
261
  * Automatically detects and renders interactive options when present.
174
262
  * Supports rich content segments for inline rendering of mentions and custom components.
175
263
  */
176
- declare function AssistantMessage({ entry, onOptionSelect, richContentRenderers, className, }: AssistantMessageProps): react_jsx_runtime.JSX.Element;
264
+ declare function AssistantMessage({ entry, variant, scale, showAvatar, showTimestamp, onOptionSelect, richContentRenderers, markdownComponents, renderMetadata, metadata, className, }: AssistantMessageProps): react_jsx_runtime.JSX.Element;
177
265
  interface ThinkingMessageProps {
178
266
  entry: NormalizedEntry;
267
+ /** Typography scale */
268
+ scale?: TypographyScale;
269
+ /** Show avatar */
270
+ showAvatar?: boolean;
179
271
  className?: string;
180
272
  }
181
273
  /**
182
274
  * ThinkingMessage - Display thinking/reasoning content (extended thinking)
183
275
  *
184
- * Uses glassmorphism styling with purple accent for thinking mode.
276
+ * Compact styling with purple accent for thinking mode.
185
277
  */
186
- declare function ThinkingMessage({ entry, className }: ThinkingMessageProps): react_jsx_runtime.JSX.Element;
278
+ declare function ThinkingMessage({ entry, scale, showAvatar, className }: ThinkingMessageProps): react_jsx_runtime.JSX.Element;
187
279
  interface ToolCallMessageProps {
188
280
  entry: NormalizedEntry;
281
+ /** Typography scale */
282
+ scale?: TypographyScale;
283
+ /** Show avatar */
284
+ showAvatar?: boolean;
189
285
  defaultExpanded?: boolean;
190
286
  className?: string;
191
287
  }
192
288
  /**
193
289
  * ToolCallMessage - Display a tool call entry using ToolCallCard
194
290
  *
195
- * Uses glassmorphism styling with animated entry.
291
+ * Compact styling with animated entry.
196
292
  */
197
- declare function ToolCallMessage({ entry, defaultExpanded, className }: ToolCallMessageProps): react_jsx_runtime.JSX.Element | null;
293
+ declare function ToolCallMessage({ entry, scale, showAvatar, defaultExpanded, className }: ToolCallMessageProps): react_jsx_runtime.JSX.Element | null;
198
294
  interface ErrorMessageProps {
199
295
  entry: NormalizedEntry;
296
+ /** Typography scale */
297
+ scale?: TypographyScale;
298
+ /** Show avatar */
299
+ showAvatar?: boolean;
200
300
  className?: string;
201
301
  }
202
302
  /**
203
303
  * ErrorMessage - Display an error entry
204
304
  *
205
- * Uses glassmorphism styling with red accent for errors.
305
+ * Compact styling with red accent for errors.
206
306
  */
207
- declare function ErrorMessage({ entry, className }: ErrorMessageProps): react_jsx_runtime.JSX.Element | null;
307
+ declare function ErrorMessage({ entry, scale, showAvatar, className }: ErrorMessageProps): react_jsx_runtime.JSX.Element | null;
208
308
  interface MessageEntryProps {
209
309
  entry: NormalizedEntry;
210
310
  /** Callback when user selects an option from assistant message */
@@ -213,22 +313,43 @@ interface MessageEntryProps {
213
313
  defaultExpanded?: boolean;
214
314
  /** Custom renderers for rich content segments */
215
315
  richContentRenderers?: RichContentRenderers;
316
+ /** Custom markdown component overrides */
317
+ markdownComponents?: MarkdownComponents;
318
+ /** Visual variant for user messages */
319
+ userVariant?: MessageVariant;
320
+ /** Visual variant for assistant messages */
321
+ assistantVariant?: MessageVariant;
322
+ /** Typography scale */
323
+ scale?: TypographyScale;
324
+ /** Show avatars */
325
+ showAvatars?: boolean;
326
+ /** Show timestamps */
327
+ showTimestamp?: boolean;
328
+ /** Custom metadata renderer */
329
+ renderMetadata?: RenderMetadataFunction;
330
+ /** Additional metadata to display */
331
+ metadata?: MessageMetadata;
216
332
  className?: string;
217
333
  }
218
334
  /**
219
335
  * MessageEntry - Render a normalized entry based on its type
220
336
  *
221
337
  * This is a convenience component that routes to the appropriate
222
- * entry type component.
338
+ * entry type component. Supports data-message-role attributes for
339
+ * easy CSS targeting.
223
340
  *
224
341
  * @example
225
342
  * ```tsx
226
343
  * {entries.map(entry => (
227
344
  * <MessageEntry key={entry.id} entry={entry} onOptionSelect={handleSelect} />
228
345
  * ))}
346
+ *
347
+ * // CSS targeting
348
+ * [data-message-role="user"] { background: #1a1a1a; }
349
+ * [data-message-role="assistant"] { border-left: 2px solid var(--accent); }
229
350
  * ```
230
351
  */
231
- declare function MessageEntry({ entry, onOptionSelect, defaultExpanded, richContentRenderers, className, }: MessageEntryProps): react_jsx_runtime.JSX.Element | null;
352
+ declare function MessageEntry({ entry, onOptionSelect, defaultExpanded, richContentRenderers, markdownComponents, userVariant, assistantVariant, scale, showAvatars, showTimestamp, renderMetadata, metadata, className, }: MessageEntryProps): react_jsx_runtime.JSX.Element | null;
232
353
 
233
354
  interface LogsPanelProps {
234
355
  logs: LogEntry[];
@@ -620,7 +741,8 @@ interface CodeBlockProps {
620
741
  /**
621
742
  * CodeBlock - Display code with syntax-aware styling and expand/collapse
622
743
  *
623
- * Uses glassmorphism dark theme styling with accent-colored expand button.
744
+ * Uses glassmorphism dark theme styling with ChatGPT-style header containing
745
+ * language label and copy button.
624
746
  *
625
747
  * @example
626
748
  * ```tsx
@@ -696,6 +818,8 @@ interface LazyMarkdownProps {
696
818
  children: string;
697
819
  /** Fallback content to show while loading */
698
820
  fallback?: ReactNode;
821
+ /** Custom component overrides for markdown elements */
822
+ components?: MarkdownComponents;
699
823
  className?: string;
700
824
  }
701
825
  /**
@@ -707,9 +831,19 @@ interface LazyMarkdownProps {
707
831
  * @example
708
832
  * ```tsx
709
833
  * <LazyMarkdown>{markdownContent}</LazyMarkdown>
834
+ *
835
+ * // With custom components
836
+ * <LazyMarkdown
837
+ * components={{
838
+ * h2: ({ children }) => <h2 className="custom-h2">{children}</h2>,
839
+ * code: ({ children, className }) => <CustomCode className={className}>{children}</CustomCode>,
840
+ * }}
841
+ * >
842
+ * {markdownContent}
843
+ * </LazyMarkdown>
710
844
  * ```
711
845
  */
712
- declare function LazyMarkdown({ children, fallback, className }: LazyMarkdownProps): react_jsx_runtime.JSX.Element;
846
+ declare function LazyMarkdown({ children, fallback, components, className }: LazyMarkdownProps): react_jsx_runtime.JSX.Element;
713
847
 
714
848
  interface RichContentRendererProps {
715
849
  /** Rich content segments to render */
@@ -1054,6 +1188,113 @@ interface UseFileUploadReturn {
1054
1188
  declare function useFileUpload({ maxFileSize, // 100MB
1055
1189
  maxFiles, onValidationError, }?: UseFileUploadOptions): UseFileUploadReturn;
1056
1190
 
1191
+ /**
1192
+ * Middleware utilities for useAgentChat
1193
+ *
1194
+ * Provides composable request and event transformation capabilities.
1195
+ * Middleware functions are called in order, and each can transform or filter
1196
+ * the request/event before passing it to the next middleware.
1197
+ *
1198
+ * @example
1199
+ * ```tsx
1200
+ * const loggingMiddleware: ChatMiddleware = {
1201
+ * onRequest: (request) => {
1202
+ * console.log('Sending:', request.prompt);
1203
+ * return request;
1204
+ * },
1205
+ * onEvent: (event) => {
1206
+ * console.log('Received:', event.type);
1207
+ * return event;
1208
+ * },
1209
+ * };
1210
+ *
1211
+ * const { send } = useAgentChat({
1212
+ * middleware: [loggingMiddleware],
1213
+ * // ...
1214
+ * });
1215
+ * ```
1216
+ */
1217
+
1218
+ /**
1219
+ * Request object passed through middleware chain
1220
+ */
1221
+ interface MiddlewareRequest {
1222
+ /** The user's prompt */
1223
+ prompt: string;
1224
+ /** Current session ID (if resuming a conversation) */
1225
+ sessionId: string | null;
1226
+ /** Additional metadata to send with the request */
1227
+ metadata?: Record<string, unknown>;
1228
+ /** Additional context to prepend to the session */
1229
+ sessionContext?: string;
1230
+ }
1231
+ /**
1232
+ * Result returned from request middleware
1233
+ * Return void or omit fields to keep original values
1234
+ */
1235
+ interface MiddlewareRequestResult {
1236
+ /** Modified prompt */
1237
+ prompt?: string;
1238
+ /** Modified metadata (merged with existing) */
1239
+ metadata?: Record<string, unknown>;
1240
+ /** Modified session context */
1241
+ sessionContext?: string;
1242
+ /** If set, cancels the request and shows this error */
1243
+ error?: string;
1244
+ }
1245
+ /**
1246
+ * Middleware interface for composable request/event transforms
1247
+ */
1248
+ interface ChatMiddleware {
1249
+ /** Called before the request is sent. Can modify request or return error to cancel. */
1250
+ onRequest?: (request: MiddlewareRequest) => Promise<MiddlewareRequestResult | void> | MiddlewareRequestResult | void;
1251
+ /** Called for each event. Return null to filter out the event. */
1252
+ onEvent?: (event: StreamEvent) => Promise<StreamEvent | null> | StreamEvent | null;
1253
+ /** Called when the stream completes successfully */
1254
+ onComplete?: (sessionId: string) => void | Promise<void>;
1255
+ /** Called when an error occurs */
1256
+ onError?: (error: string) => void | Promise<void>;
1257
+ }
1258
+ /**
1259
+ * Apply request middleware chain
1260
+ *
1261
+ * Executes each middleware's onRequest handler in order.
1262
+ * Each middleware can modify the request or return an error to cancel.
1263
+ *
1264
+ * @param middlewares - Array of middleware to apply
1265
+ * @param request - Initial request object
1266
+ * @returns Modified request and optional error
1267
+ */
1268
+ declare function applyRequestMiddleware(middlewares: ChatMiddleware[], request: MiddlewareRequest): Promise<{
1269
+ request: MiddlewareRequest;
1270
+ error?: string;
1271
+ }>;
1272
+ /**
1273
+ * Apply event middleware chain
1274
+ *
1275
+ * Executes each middleware's onEvent handler in order.
1276
+ * If any middleware returns null, the event is filtered out.
1277
+ *
1278
+ * @param middlewares - Array of middleware to apply
1279
+ * @param event - Stream event to process
1280
+ * @returns Processed event or null if filtered
1281
+ */
1282
+ declare function applyEventMiddleware(middlewares: ChatMiddleware[], event: StreamEvent): Promise<StreamEvent | null>;
1283
+ /**
1284
+ * Call completion handlers on all middleware
1285
+ *
1286
+ * @param middlewares - Array of middleware
1287
+ * @param sessionId - Completed session ID
1288
+ */
1289
+ declare function callMiddlewareComplete(middlewares: ChatMiddleware[], sessionId: string): Promise<void>;
1290
+ /**
1291
+ * Call error handlers on all middleware
1292
+ *
1293
+ * @param middlewares - Array of middleware
1294
+ * @param error - Error message
1295
+ */
1296
+ declare function callMiddlewareError(middlewares: ChatMiddleware[], error: string): Promise<void>;
1297
+
1057
1298
  /**
1058
1299
  * useAgentChat - A React hook for streaming agent conversations
1059
1300
  *
@@ -1128,12 +1369,70 @@ interface StreamEvent {
1128
1369
  * Async generator that yields StreamEvent objects
1129
1370
  */
1130
1371
  type StreamGenerator = AsyncGenerator<StreamEvent, void, unknown>;
1372
+ /**
1373
+ * Options passed to CreateStreamFn
1374
+ */
1375
+ interface CreateStreamOptions {
1376
+ /** AbortSignal to cancel the request */
1377
+ signal?: AbortSignal;
1378
+ /** Additional metadata from onBeforeSend/middleware */
1379
+ metadata?: Record<string, unknown>;
1380
+ /** Session context from onBeforeSend/middleware */
1381
+ sessionContext?: string;
1382
+ }
1131
1383
  /**
1132
1384
  * Function that creates a stream of events
1133
1385
  * This matches the signature of client.agents.run() and client.sessions.send()
1134
- * The optional signal parameter allows cancellation via AbortController
1386
+ *
1387
+ * @example
1388
+ * ```tsx
1389
+ * createStream: (prompt, sessionId, options) => {
1390
+ * if (sessionId) {
1391
+ * return client.sessions.send(sessionId, prompt, {
1392
+ * signal: options?.signal,
1393
+ * sessionContext: options?.sessionContext,
1394
+ * metadata: options?.metadata,
1395
+ * });
1396
+ * }
1397
+ * return client.agents.run(agentId, prompt, {
1398
+ * signal: options?.signal,
1399
+ * sessionContext: options?.sessionContext,
1400
+ * metadata: options?.metadata,
1401
+ * });
1402
+ * }
1403
+ * ```
1135
1404
  */
1136
- type CreateStreamFn = (prompt: string, sessionId?: string, signal?: AbortSignal) => StreamGenerator;
1405
+ type CreateStreamFn = (prompt: string, sessionId?: string, options?: CreateStreamOptions) => StreamGenerator;
1406
+ /**
1407
+ * Function that subscribes to an existing session's events
1408
+ * This is used for auto-reconnection when the primary stream is interrupted
1409
+ */
1410
+ type SubscribeToSessionFn = (sessionId: string, signal?: AbortSignal) => StreamGenerator;
1411
+ /**
1412
+ * Context passed to onBeforeSend hook
1413
+ */
1414
+ interface BeforeSendContext {
1415
+ /** The user's prompt */
1416
+ prompt: string;
1417
+ /** Current session ID (null for new conversations) */
1418
+ sessionId: string | null;
1419
+ /** Current entries in the conversation */
1420
+ entries: NormalizedEntry[];
1421
+ }
1422
+ /**
1423
+ * Result returned from onBeforeSend hook
1424
+ * Return void or omit fields to keep original values
1425
+ */
1426
+ interface BeforeSendResult {
1427
+ /** Modified prompt to send */
1428
+ prompt?: string;
1429
+ /** Additional metadata to include with the request */
1430
+ metadata?: Record<string, unknown>;
1431
+ /** Additional context to prepend to the session */
1432
+ sessionContext?: string;
1433
+ /** If true, cancels the send operation */
1434
+ cancel?: boolean;
1435
+ }
1137
1436
  /**
1138
1437
  * Options for useAgentChat
1139
1438
  */
@@ -1153,6 +1452,18 @@ interface UseAgentChatOptions {
1153
1452
  * ```
1154
1453
  */
1155
1454
  createStream: CreateStreamFn;
1455
+ /**
1456
+ * Function to subscribe to an existing session for reconnection.
1457
+ * If provided, enables auto-reconnection when the stream is interrupted.
1458
+ *
1459
+ * @example
1460
+ * ```tsx
1461
+ * subscribeToSession: (sessionId, signal) => {
1462
+ * return client.sessions.subscribe(sessionId, { signal });
1463
+ * }
1464
+ * ```
1465
+ */
1466
+ subscribeToSession?: SubscribeToSessionFn;
1156
1467
  /**
1157
1468
  * Initial session ID (for resuming a conversation)
1158
1469
  */
@@ -1177,6 +1488,71 @@ interface UseAgentChatOptions {
1177
1488
  * Callback for sandbox log events
1178
1489
  */
1179
1490
  onSandboxLog?: (entry: NonNullable<StreamEvent['entry']>) => void;
1491
+ /**
1492
+ * Callback when reconnection is attempted
1493
+ */
1494
+ onReconnect?: (attempt: number, sessionId: string) => void;
1495
+ /**
1496
+ * Maximum number of reconnection attempts (default: 3)
1497
+ */
1498
+ maxReconnectAttempts?: number;
1499
+ /**
1500
+ * Base delay for exponential backoff in ms (default: 1000)
1501
+ */
1502
+ reconnectBaseDelay?: number;
1503
+ /**
1504
+ * Called before each message is sent.
1505
+ * Use for pre-flight work like file synchronization, validation, or adding context.
1506
+ * Return { cancel: true } to prevent the message from being sent.
1507
+ *
1508
+ * @example
1509
+ * ```tsx
1510
+ * onBeforeSend: async ({ prompt, sessionId }) => {
1511
+ * await syncFilesToSandbox(sessionId);
1512
+ * return {
1513
+ * sessionContext: `Current file: ${currentFile}`,
1514
+ * metadata: { version: '1.0' },
1515
+ * };
1516
+ * }
1517
+ * ```
1518
+ */
1519
+ onBeforeSend?: (context: BeforeSendContext) => Promise<BeforeSendResult | void> | BeforeSendResult | void;
1520
+ /**
1521
+ * Called for every raw stream event before internal processing.
1522
+ * Use for logging, analytics, or detecting specific events.
1523
+ *
1524
+ * @example
1525
+ * ```tsx
1526
+ * onEvent: (event) => {
1527
+ * if (event.type === 'tool_result' && event.toolName === 'browser_navigate') {
1528
+ * updatePreview(event.toolResult?.url);
1529
+ * }
1530
+ * }
1531
+ * ```
1532
+ */
1533
+ onEvent?: (event: StreamEvent) => void | Promise<void>;
1534
+ /**
1535
+ * Array of middleware for composable request/event transforms.
1536
+ * Middleware are executed in order. Each can modify requests,
1537
+ * transform events, or filter events by returning null.
1538
+ *
1539
+ * @example
1540
+ * ```tsx
1541
+ * middleware: [
1542
+ * {
1543
+ * onRequest: async (req) => ({
1544
+ * metadata: { ...req.metadata, timestamp: Date.now() },
1545
+ * }),
1546
+ * onEvent: (event) => {
1547
+ * // Filter out sandbox_log events
1548
+ * if (event.type === 'sandbox_log') return null;
1549
+ * return event;
1550
+ * },
1551
+ * },
1552
+ * ]
1553
+ * ```
1554
+ */
1555
+ middleware?: ChatMiddleware[];
1180
1556
  }
1181
1557
  /**
1182
1558
  * Return type for useAgentChat
@@ -1191,6 +1567,10 @@ interface UseAgentChatReturn {
1191
1567
  * Whether a message is currently being streamed
1192
1568
  */
1193
1569
  isStreaming: boolean;
1570
+ /**
1571
+ * Whether the hook is attempting to reconnect after a stream interruption
1572
+ */
1573
+ isReconnecting: boolean;
1194
1574
  /**
1195
1575
  * Current error message (if any)
1196
1576
  */
@@ -1328,4 +1708,4 @@ interface UseLongTextConversionReturn {
1328
1708
  */
1329
1709
  declare function useLongTextConversion({ threshold, filenameTemplate, onConversion, }?: LongTextConversionOptions): UseLongTextConversionReturn;
1330
1710
 
1331
- export { ActionIcon, type ActionIconProps, ActionType, type StreamEvent as AgentStreamEvent, AgentToolCard, type AgentToolCardProps, AssistantMessage, type AssistantMessageProps, type FileAttachment as ChatFileAttachment, CodeBlock, type CodeBlockProps, CompactToolRow, type CompactToolRowProps, CompactToolStatusLine, type CompactToolStatusLineProps, type ConversionInfo, type CreateStreamFn, type DisplayModeContextType, DisplayModeProvider, type DisplayModeProviderProps, DisplayModeToggle, type DisplayModeToggleProps, EnvVarsPanel, type EnvVarsPanelProps, ErrorMessage, type ErrorMessageProps, FileBadge, type FileBadgeProps, JsonDisplay, type JsonDisplayProps, LazyMarkdown, type LazyMarkdownProps, LoadingIndicator, type LoadingIndicatorProps, LogEntry, LogsPanel, type LogsPanelProps, type LongTextConversionOptions, MessageEntry, type MessageEntryProps, MessageList, type MessageListProps, NormalizedEntry, NormalizedToolCall, OptionCards, type OptionCardsProps, ParsedOption, type QueuedMessage, RichContent, RichContentRenderer, type RichContentRendererProps, RichContentRenderers, StatusIndicator, type StatusIndicatorProps, StepAccordion, type StepAccordionProps, type StepStatus, type StreamGenerator, StreamingText, type StreamingTextProps, type TextAttachment, type Theme, type ThemeContextType, ThemeProvider, type ThemeProviderProps, ThinkingMessage, type ThinkingMessageProps, TodoItem, TodoPanel, type TodoPanelProps, ToolCallCard, type ToolCallCardProps, ToolCallMessage, type ToolCallMessageProps, ToolDisplayConfig, ToolDisplayMode, ToolExecutionGroup, type ToolExecutionGroupProps, ToolStatus, TypewriterText, type TypewriterTextProps, type UseAgentChatOptions, type UseAgentChatReturn, type UseFileUploadOptions, type UseFileUploadReturn, type UseLongTextConversionReturn, type UseMessageQueueOptions, type UseMessageQueueReturn, type UseStopExecutionOptions, type UseStopExecutionReturn, UserMessage, type UserMessageProps, WidgetAction, WidgetRenderFunction, useAgentChat, useDisplayConfig, useDisplayMode, useFileUpload, useLongTextConversion, useMessageQueue, useStopExecution, useTheme };
1711
+ export { ActionIcon, type ActionIconProps, ActionType, type StreamEvent as AgentStreamEvent, AgentToolCard, type AgentToolCardProps, AssistantMessage, type AssistantMessageProps, type BeforeSendContext, type BeforeSendResult, type FileAttachment as ChatFileAttachment, type ChatMiddleware, CodeBlock, type CodeBlockProps, CompactToolRow, type CompactToolRowProps, CompactToolStatusLine, type CompactToolStatusLineProps, type ConversionInfo, type CreateStreamFn, type CreateStreamOptions, type DisplayModeContextType, DisplayModeProvider, type DisplayModeProviderProps, DisplayModeToggle, type DisplayModeToggleProps, EnvVarsPanel, type EnvVarsPanelProps, ErrorMessage, type ErrorMessageProps, FileBadge, type FileBadgeProps, JsonDisplay, type JsonDisplayProps, LazyMarkdown, type LazyMarkdownProps, LoadingIndicator, type LoadingIndicatorProps, LogEntry, LogsPanel, type LogsPanelProps, type LongTextConversionOptions, MarkdownComponents, MessageEntry, type MessageEntryProps, MessageList, type MessageListProps, MessageMetadata, MessageVariant, type MiddlewareRequest, type MiddlewareRequestResult, NormalizedEntry, NormalizedToolCall, OptionCards, type OptionCardsProps, ParsedOption, type QueuedMessage, RenderMetadataFunction, RichContent, RichContentRenderer, type RichContentRendererProps, RichContentRenderers, StatusIndicator, type StatusIndicatorProps, StepAccordion, type StepAccordionProps, type StepStatus, type StreamGenerator, StreamingText, type StreamingTextProps, type TextAttachment, type Theme, type ThemeContextType, ThemeProvider, type ThemeProviderProps, ThinkingMessage, type ThinkingMessageProps, TodoItem, TodoPanel, type TodoPanelProps, ToolCallCard, type ToolCallCardProps, ToolCallMessage, type ToolCallMessageProps, ToolDisplayConfig, ToolDisplayMode, ToolExecutionGroup, type ToolExecutionGroupProps, ToolStatus, TypewriterText, type TypewriterTextProps, TypographyScale, type UseAgentChatOptions, type UseAgentChatReturn, type UseFileUploadOptions, type UseFileUploadReturn, type UseLongTextConversionReturn, type UseMessageQueueOptions, type UseMessageQueueReturn, type UseStopExecutionOptions, type UseStopExecutionReturn, UserMessage, type UserMessageProps, WidgetAction, WidgetRenderFunction, applyEventMiddleware, applyRequestMiddleware, callMiddlewareComplete, callMiddlewareError, useAgentChat, useDisplayConfig, useDisplayMode, useFileUpload, useLongTextConversion, useMessageQueue, useStopExecution, useTheme };