@devicai/ui 0.62.2 → 0.62.4

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.
Files changed (27) hide show
  1. package/README.md +14 -1
  2. package/dist/cjs/api/types.js.map +1 -1
  3. package/dist/cjs/components/AICommandBar/useAICommandBar.js +5 -5
  4. package/dist/cjs/components/AICommandBar/useAICommandBar.js.map +1 -1
  5. package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js +5 -5
  6. package/dist/cjs/components/AIElementWrapper/useAIElementWrapper.js.map +1 -1
  7. package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js +5 -5
  8. package/dist/cjs/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
  9. package/dist/cjs/hooks/useDevicChat.js +12 -8
  10. package/dist/cjs/hooks/useDevicChat.js.map +1 -1
  11. package/dist/cjs/hooks/useModelInterface.js +109 -33
  12. package/dist/cjs/hooks/useModelInterface.js.map +1 -1
  13. package/dist/esm/api/types.d.ts +16 -0
  14. package/dist/esm/api/types.js.map +1 -1
  15. package/dist/esm/components/AICommandBar/useAICommandBar.js +5 -5
  16. package/dist/esm/components/AICommandBar/useAICommandBar.js.map +1 -1
  17. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js +5 -5
  18. package/dist/esm/components/AIElementWrapper/useAIElementWrapper.js.map +1 -1
  19. package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js +5 -5
  20. package/dist/esm/components/AIGenerationButton/useAIGenerationButton.js.map +1 -1
  21. package/dist/esm/hooks/useDevicChat.js +12 -8
  22. package/dist/esm/hooks/useDevicChat.js.map +1 -1
  23. package/dist/esm/hooks/useModelInterface.d.ts +54 -1
  24. package/dist/esm/hooks/useModelInterface.js +108 -35
  25. package/dist/esm/hooks/useModelInterface.js.map +1 -1
  26. package/dist/esm/index.d.ts +1 -1
  27. package/package.json +1 -1
package/README.md CHANGED
@@ -1106,8 +1106,9 @@ Hook for implementing the Model Interface Protocol.
1106
1106
  const {
1107
1107
  toolSchemas, // Tool schemas to send to API
1108
1108
  isClientTool, // (name: string) => boolean
1109
- handleToolCalls, // (toolCalls: ToolCall[]) => Promise<ToolCallResponse[]>
1109
+ handleToolCalls, // (toolCalls: ToolCall[]) => Promise<{ responses, widgetCalls, toolSchemas }>
1110
1110
  extractPendingToolCalls, // (messages: ChatMessage[]) => ToolCall[]
1111
+ resolvePendingToolCalls, // (realtime: RealtimeChatHistory) => ToolCall[] — includes calls to tools no longer loaded
1111
1112
  } = useModelInterface({
1112
1113
  tools: [
1113
1114
  {
@@ -1426,6 +1427,18 @@ const locationTool: ModelInterfaceTool = {
1426
1427
  />
1427
1428
  ```
1428
1429
 
1430
+ ### Tools that are no longer loaded
1431
+
1432
+ Tools often depend on the screen the user is on, so the model can call one that is gone by the time the call arrives — the user navigated away while the assistant was still working. The API keeps the conversation in `waiting_for_tool_response` until every client-side call is answered, so an unanswered call would block the conversation.
1433
+
1434
+ When that happens the components wait up to 5 seconds (`unavailableToolGraceMs` on `useModelInterface`) for the tool to be registered — the screen the model just navigated to may still be mounting — and run it if it shows up. Otherwise the call is answered with an error the model can read, and the run continues:
1435
+
1436
+ ```json
1437
+ { "error": "Tool \"go_to_study_step\" is not available: ...", "errorType": "TOOL_UNAVAILABLE" }
1438
+ ```
1439
+
1440
+ Backend tools that answer asynchronously (`pendingAsyncToolCalls` in the realtime state) are never answered by the client.
1441
+
1429
1442
  ## TypeScript
1430
1443
 
1431
1444
  All types are exported:
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../../../src/api/types.ts"],"sourcesContent":["import type { AvatarStyle } from '../utils/avatar';\n\nimport type React from 'react';\n\n/**\n * File attachment for messages\n */\nexport interface ChatFile {\n name: string;\n downloadUrl?: string;\n fileType?: 'image' | 'document' | 'audio' | 'video' | 'other';\n}\n\n/**\n * Attachment as it appears on a message.\n *\n * Two shapes reach the UI for the same thing: the optimistic message built\n * locally on send uses `url`/`type`, while the history returned by the API\n * carries the stored `downloadUrl`/`fileType`. Both are accepted here; use\n * `normalizeMessageFile` before reading them.\n */\nexport interface MessageFile {\n name: string;\n url?: string;\n type?: string;\n downloadUrl?: string;\n fileType?: string;\n}\n\n/**\n * Message content structure\n */\nexport interface MessageContent {\n /**\n * The message text.\n *\n * Declared as a string because that is what it is for every role a reader\n * cares about, but do not trust it blindly on a `guard_rail` message:\n * conversations stopped by a guardrail before the backend fix carry the raw\n * provider result object here instead. Guard a `typeof x === 'string'` check\n * around anything that treats it as text.\n */\n message?: string;\n data?: any;\n files?: MessageFile[];\n}\n\n/** Collapse either attachment shape into a single one the UI can render. */\nexport function normalizeMessageFile(file: MessageFile): {\n name: string;\n url: string;\n type: string;\n} {\n return {\n name: file.name,\n url: file.url || file.downloadUrl || '',\n type: file.type || file.fileType || 'other',\n };\n}\n\n/**\n * Tool call from the model\n */\nexport interface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\n/**\n * Chat message structure\n */\nexport interface ChatMessage {\n uid: string;\n role: 'user' | 'assistant' | 'developer' | 'system' | 'tool' | 'guard_rail';\n content: MessageContent;\n timestamp: number;\n chatUid?: string;\n tool_calls?: ToolCall[];\n tool_call_id?: string;\n summary?: string;\n /**\n * Where `content.message` came from, when the model did not write it.\n * `'finish_tool'`: the assistant is configured to require a tool call to\n * finish (\"Require Tool Use to Finish\") and the backend lifted the reply from\n * the finish tool's `message` argument, so it can be read without parsing\n * tool calls. Absent on replies the model wrote itself — use it to label the\n * bubble as produced by the tool.\n */\n contentSource?: string;\n /**\n * Id of a speech-to-text transcript (from POST /api/v1/whisper) that seeded\n * this message. Present on user messages dictated by voice; the chat can use\n * it to fetch the source audio (GET /api/v1/whisper/:transcriptId) and offer\n * playback.\n */\n transcriptId?: string;\n /**\n * Original server uid, present when the UI adopted an optimistic uid for\n * this message to keep React keys stable. Server-side references (e.g.\n * memory recall anchors) match against it.\n */\n serverUid?: string;\n /**\n * Client-side only: the conversation was busy when this message was sent, so\n * it was accepted into the queue and is waiting its turn. Drawn as a message\n * that has not landed rather than as part of the conversation. Falls away on\n * its own once the message comes back inside the history.\n */\n queued?: boolean;\n /**\n * Client-side only: when this message was accepted into the queue. Used to\n * tell \"the server has not reported it yet\" from \"the server no longer has\n * it\", which the timestamp is the only honest way to decide.\n */\n queuedAt?: number;\n}\n\n/**\n * Previous conversation message for initialization\n */\nexport interface PreviousMessage {\n message: string;\n role: 'user' | 'assistant';\n}\n\n/**\n * Model interface tool schema following OpenAI function calling format\n */\nexport interface ModelInterfaceToolSchema {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: {\n type: 'object';\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\n/**\n * Props passed to a response widget component.\n * The widget is responsible for collecting the user's response and\n * calling `submit` with the payload to resolve the tool call.\n */\nexport interface ResponseWidgetProps {\n /** The tool call this widget is responding to */\n toolCall: ToolCall;\n /** Parsed arguments from the tool call */\n params: any;\n /** Submit the tool response payload (sent as the tool call result to the model) */\n submit: (response: any) => void;\n /** Cancel the tool call. Sends an error response so the model can continue. */\n cancel?: (reason?: string) => void;\n /** Whether the widget is currently submitting */\n isSubmitting?: boolean;\n}\n\n/**\n * Interactive response widget configuration for a client-side tool.\n *\n * When the model calls a tool configured with a `responseWidget`, the\n * widget is rendered in the chat UI instead of executing a callback.\n * The user interacts with the widget, which calls `submit(response)` to\n * define the tool response sent back to the model.\n *\n * - `render: 'inline'` renders the widget in the message thread at the\n * position of the tool call. The text input remains enabled.\n * - `render: 'input'` replaces the chat input area with the widget\n * while it is pending. The text input is disabled until submission.\n */\nexport interface ResponseWidgetConfig {\n /** Where to render the widget */\n render: 'inline' | 'input';\n /** The widget component */\n component: React.ComponentType<ResponseWidgetProps>;\n}\n\n/**\n * Model interface tool definition for client-side tools.\n *\n * A tool must provide either a `callback` (executed automatically when\n * the model invokes the tool) or a `responseWidget` (renders UI for\n * the user to produce the tool response). Providing both is an error.\n */\nexport interface ModelInterfaceTool {\n toolName: string;\n schema: ModelInterfaceToolSchema;\n /** Executed automatically when the model calls this tool */\n callback?: (params: any) => Promise<any> | any;\n /** Interactive widget that collects the user's tool response */\n responseWidget?: ResponseWidgetConfig;\n}\n\n/**\n * Tool call response to send back to the API\n */\nexport interface ToolCallResponse {\n tool_call_id: string;\n content: any;\n role: 'tool';\n /**\n * The client-side tools still on offer for the rest of the turn. The API\n * reads them off the first response of the batch: leaving them out drops\n * the tools from the continuation, so the model cannot call them again.\n */\n tools?: ModelInterfaceToolSchema[];\n}\n\n/**\n * DTO for sending messages to the assistant\n */\nexport interface ProcessMessageDto {\n disabledIntegrations?: string[];\n message: string;\n chatUid?: string;\n userName?: string;\n files?: ChatFile[];\n /** Tags to associate with this chat (top-level, distinct from `metadata`). */\n tags?: string[];\n metadata?: {\n promptTemplateParams?: Record<string, any>;\n tenantToken?: string;\n [key: string]: any;\n };\n tenantId?: string;\n subtenantId?: string;\n previousConversation?: PreviousMessage[];\n enabledTools?: string[];\n provider?: string;\n model?: string;\n // Model interface protocol fields\n tools?: ModelInterfaceToolSchema[];\n applicationState?: Record<string, any>;\n skipSummarization?: boolean;\n /**\n * Id of a speech-to-text transcript (from POST /api/v1/whisper) that seeded\n * this message. Sent so the conversation keeps a link to the original audio.\n */\n transcriptId?: string;\n}\n\n/**\n * Response from the /whisper speech-to-text endpoint.\n */\nexport interface WhisperTranscriptionResponse {\n /** Public id of the transcript; send it back as ProcessMessageDto.transcriptId. */\n transcriptId: string;\n /** Transcribed text. */\n text: string;\n /** Language hint used, if any. */\n language?: string;\n /** Download URL of the source audio. */\n audioUrl?: string;\n /** Transcription model used. */\n model?: string;\n}\n\n/**\n * Response from the assistant\n */\nexport interface AssistantResponse {\n messages: ChatMessage[];\n chatUid: string;\n inputTokens?: number;\n outputTokens?: number;\n}\n\n/**\n * Async mode response\n */\nexport interface AsyncResponse {\n chatUid: string;\n message?: string;\n error?: string;\n /**\n * The conversation could not take the message right now, so it was queued\n * instead of starting a run of its own. Still an acceptance: the answer comes\n * later, and may cover several messages at once.\n */\n queued?: boolean;\n /** How many messages are queued on this conversation, this one included. */\n queuePosition?: number;\n /** When the queued message reaches the model. */\n willProcess?: QueueDisposition;\n}\n\n/**\n * When a queued message will reach the model.\n *\n * `after_delay` is the one that is not about being busy: an idle conversation\n * on an assistant with an input delay collects what is written during the\n * window, so a message can come back queued with nothing in flight at all.\n */\nexport type QueueDisposition = 'after_delay' | 'next_turn' | 'on_resume';\n\n/** Response of the stop endpoint. */\nexport interface StopChatResponse {\n chatUid: string;\n message: string;\n /**\n * Queued messages the stop threw away — answering them would be the opposite\n * of what was asked. Handed back so their text can be put where the user\n * wrote it. Absent on an API older than this, and when nothing was queued.\n */\n discardedMessages?: ChatMessage[];\n}\n\n/**\n * Real-time chat history status.\n * `limit_exceeded` means the message was blocked before reaching the LLM\n * because a configured tenant/subtenant usage limit was reached.\n */\nexport type RealtimeStatus =\n | 'processing'\n | 'completed'\n | 'error'\n | 'waiting_for_tool_response'\n | 'handed_off'\n | 'limit_exceeded'\n /** Collecting messages during the assistant's input delay, before any run. */\n | 'buffering';\n\n/**\n * Details of a tenant/subtenant usage limit that blocked a message.\n * Returned on the realtime endpoint when status is `limit_exceeded`, and on\n * the HTTP 429 body (`details`) when a synchronous request is blocked.\n */\nexport interface TenantLimitExceeded {\n /** Human-readable message describing the block. */\n message?: string;\n /** The rule that triggered the block (scope, metric, window, limit…). */\n blockingRule?: {\n scope?: 'tenant' | 'subtenant';\n subtenantId?: string;\n metric?: 'tokens' | 'cost';\n windowUnit?: 'hour' | 'day' | 'week' | 'month';\n windowEvery?: number;\n limit?: number;\n };\n /** Current consumption in the blocking window. */\n current?: number;\n /** The limit that was reached. */\n limit?: number;\n /** Epoch ms when the blocking window resets and usage is allowed again. */\n resetsAt?: number;\n}\n\n/** One fact a long-term-memory recall surfaced. */\nexport interface RecalledMemoryFact {\n fact: string;\n relation: string;\n /** Source entity name of the graph edge, when the fact connects two. */\n source: string | null;\n /** Target entity name of the graph edge, when the fact connects two. */\n target: string | null;\n /** ISO date the fact became valid, if known. */\n validAt: string | null;\n}\n\n/** One graph entity a long-term-memory recall surfaced. */\nexport interface RecalledMemoryEntity {\n id: string;\n name: string;\n type: string;\n summary: string | null;\n}\n\n/** One previous-session turn a conversation-start recall carried over. */\nexport interface RecalledMemoryTurn {\n role: string;\n content: string;\n}\n\n/**\n * One structured long-term-memory recall event of a conversation: the facts,\n * entities and previous-session turns a recall surfaced, plus the uid of the\n * message that brought it in (`messageUid`: the initial user message, or the\n * assistant message carrying the memory tool call — resolvable through\n * `toolCallId` while the run is still in flight).\n */\nexport interface RecalledMemoryRecord {\n uid: string;\n messageUid?: string;\n toolCallId?: string;\n source:\n | 'conversation_start'\n | 'search_memory'\n | 'search_memory_nodes'\n | 'explore_memory_graph';\n query?: string;\n facts?: RecalledMemoryFact[];\n entities?: RecalledMemoryEntity[];\n turns?: RecalledMemoryTurn[];\n timestampMs: number;\n}\n\n/**\n * Snapshot of the core-memory block a conversation saw (audit trail): the\n * render revision plus the injected entries as structured items.\n */\nexport interface CoreMemorySnapshot {\n uid: string;\n revision: string;\n items: Array<{\n id: number;\n section: string;\n content: string;\n pinned: boolean;\n source: string;\n }>;\n entries: number;\n omitted: number;\n chars: number;\n timestampMs: number;\n}\n\n/**\n * Real-time chat history response\n */\nexport interface RealtimeChatHistory {\n /** Ephemeral provider output; never persisted or treated as a tool call. */\n streamingMessage?: ChatMessage;\n chatUID: string;\n clientUID: string;\n chatHistory: ChatMessage[];\n status: RealtimeStatus;\n lastUpdatedAt: number;\n pendingToolCalls?: ToolCall[];\n handedOffSubThreadId?: string;\n /** Present only when status is `limit_exceeded`. */\n limitExceeded?: TenantLimitExceeded;\n /**\n * Memory-recall events of the in-flight run — lets the UI show what the\n * assistant is recalling while the response is still processing.\n */\n recalledMemories?: RecalledMemoryRecord[];\n /**\n * Messages accepted into this conversation that the model has not seen yet.\n * Non-zero means more is coming: a `completed` status with messages still\n * queued is not the end of the exchange.\n */\n queuedMessages?: number;\n /**\n * The queued messages themselves. This is the conversation's queue, not the\n * caller's — it can include messages the same conversation received through\n * another channel. Absent on an API that does not return them, in which case\n * the widget falls back to its own optimistic copies.\n */\n pendingUserMessages?: ChatMessage[];\n /**\n * Compaction checkpoints of the in-flight run. A conversation that compacts\n * mid-run stops sending the messages above the cut immediately, so these\n * arrive here before they are persisted on the conversation.\n */\n compactions?: CompactionCheckpoint[];\n /** The compaction running right now, if any. */\n compaction?: CompactionActivity;\n}\n\n/**\n * A single usage rule with its current consumption (from GET\n * /api/v1/tenant-usage/:tenantId[/subtenants/:subtenantId]).\n */\nexport interface TenantUsageRule {\n scope: 'tenant' | 'subtenant';\n subtenantId?: string;\n metric: 'tokens' | 'cost';\n windowUnit: 'hour' | 'day' | 'week' | 'month';\n windowEvery: number;\n /** Configured limit for the window. */\n limit: number;\n /** Current consumption in the active window. */\n current: number;\n /** Utilization percentage (0..100, capped). */\n percent: number;\n /** Epoch ms when the active window resets. */\n resetsAt?: number;\n /** Where the rule comes from ('tier' | 'adhoc'). */\n origin?: string;\n /** Tier the rule belongs to, if any. */\n tierId?: string;\n}\n\n/**\n * Response of GET /api/v1/tenant-usage/:tenantId[/subtenants/:subtenantId]:\n * the effective usage rules with their current consumption + the active tier.\n */\nexport interface TenantUsage {\n tenantId: string;\n subtenantId?: string;\n tierId?: string;\n usage: TenantUsageRule[];\n}\n\n/**\n * A durable per-window usage history row (from GET\n * /api/v1/tenant-usage/:tenantId/history).\n */\nexport interface TenantUsageHistoryRow {\n clientUID: string;\n tenantId: string;\n subtenantId: string;\n scope: 'tenant' | 'subtenant';\n metric: 'tokens' | 'cost';\n windowUnit: 'hour' | 'day' | 'week' | 'month';\n windowEvery: number;\n windowKey: string;\n windowStart: number;\n windowEnd: number;\n /** Counted consumption (enforced). */\n consumption: number;\n /** Exempt consumption that did not count toward the limit, if any. */\n exemptConsumption?: number;\n limit: number;\n percent: number;\n tierId?: string;\n origin?: string;\n capturedAt: number;\n}\n\n/**\n * Options for querying tenant usage history.\n */\nexport interface TenantUsageHistoryQuery {\n subtenantId?: string;\n scope?: 'tenant' | 'subtenant';\n metric?: 'tokens' | 'cost';\n windowUnit?: 'hour' | 'day' | 'week' | 'month';\n /** Epoch ms lower bound (windowEnd >= from). */\n from?: number;\n /** Epoch ms upper bound (windowEnd <= to). */\n to?: number;\n limit?: number;\n skip?: number;\n}\n\n/**\n * Chat history structure\n */\n/** A concrete value carried verbatim through a compaction. */\nexport interface CompactionFact {\n kind: string;\n value: string;\n label?: string;\n}\n\n/** The structured body a compaction produced. */\nexport interface CompactionSummary {\n goal?: string;\n constraints?: string[];\n inProgress?: string;\n pending?: string[];\n decisions?: string[];\n data?: Array<{ label: string; value: string }>;\n done?: string[];\n openQuestions?: string[];\n /** Fallback when the model answered without structure. */\n raw?: string;\n}\n\n/**\n * One compaction of a conversation: the messages before its boundary folded\n * into a written summary plus the identifiers, paths and urls lifted out of\n * them verbatim. From then on the model receives the checkpoint instead of\n * those messages — which are still in the conversation, and still shown.\n *\n * Only the newest checkpoint is in force: each compaction merges the previous\n * summary into itself.\n */\nexport interface CompactionCheckpoint {\n uid: string;\n /** 1 for the first compaction of the conversation, 2 for the next… */\n index: number;\n timestampMs: number;\n trigger: 'auto' | 'manual';\n /** First message that still travels verbatim. */\n firstKeptMessageUid?: string;\n /** Last folded message: where the widget belongs in the conversation. */\n anchorMessageUid?: string;\n compactedMessageCount: number;\n summary: CompactionSummary;\n facts: CompactionFact[];\n tokensBefore: number;\n tokensAfter: number;\n provider?: string;\n model?: string;\n cost?: number;\n}\n\n/**\n * A compaction happening right now, from the realtime endpoint.\n *\n * A compaction is a model call of its own, taken between two assistant\n * messages, so a client that only knows `processing` shows a conversation\n * that appears to have stalled for a few seconds. Present while it runs and\n * on the single update that reports it finished.\n */\nexport interface CompactionActivity {\n state: 'running' | 'completed';\n startedAt: number;\n /**\n * What this pass is folding: the messages new since the last checkpoint.\n * Not the conversation's totals — a checkpoint's own\n * `compactedMessageCount` and `tokensBefore` are cumulative across every\n * compaction, so the two are on different scales and must not be paired.\n */\n messageCount: number;\n tokensBefore: number;\n /** Which checkpoint the pass produced, once it is done. */\n index?: number;\n finishedAt?: number;\n}\n\nexport interface ChatHistory {\n chatUID: string;\n clientUID: string;\n userUID: string;\n chatContent: ChatMessage[];\n name?: string;\n assistantSpecializationIdentifier: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n llm?: string;\n inputTokens?: number;\n outputTokens?: number;\n metadata?: Record<string, any>;\n tenantId?: string;\n handedOff?: boolean;\n handedOffSubThreadId?: string;\n handedOffToolCallId?: string;\n /** Structured long-term-memory recall events of the conversation. */\n recalledMemories?: RecalledMemoryRecord[];\n /** Audit trail of the core-memory blocks the conversation saw. */\n coreMemories?: CoreMemorySnapshot[];\n /** Compaction checkpoints of the conversation, oldest first. */\n compactions?: CompactionCheckpoint[];\n}\n\n/** One core memory entry (the always-injected tier), as returned by the memory API. */\nexport interface CoreMemoryEntry {\n id: number;\n section: string;\n content: string;\n source: string;\n pinned: boolean;\n supersedes: number | null;\n archivedAt: string | null;\n createdAt?: string;\n updatedAt?: string;\n}\n\n/** Deployment caps of the core memory tier. */\nexport interface CoreMemoryLimits {\n maxChars: number;\n maxEntries: number;\n maxEntryChars: number;\n}\n\n/**\n * Response of GET /api/v1/memory/assistants/:identifier/core — the entries\n * of the bucket the assistant resolves for a tenant/subtenant combination.\n */\nexport interface CoreMemoryList {\n /** False when the assistant does not have the core memory tier enabled. */\n enabled: boolean;\n /** The resolved bucket tuple (tenant/subtenant/owner dimensions). */\n bucket: { tenantId?: string; subtenantId?: string; entityId?: string };\n entries: CoreMemoryEntry[];\n limits?: CoreMemoryLimits;\n}\n\n/**\n * Assistant specialization info\n */\nexport interface AssistantSpecialization {\n liveVoice?: import('./liveVoice.types').LiveVoiceConfiguration;\n identifier: string;\n name: string;\n description: string;\n state: 'active' | 'inactive' | 'coming_soon';\n imgUrl?: string;\n /** Pinned style of the generated avatar shown when there is no imgUrl. */\n avatarStyle?: AvatarStyle;\n availableToolsGroups?: Array<{\n name: string;\n description?: string;\n uid?: string;\n iconUrl?: string;\n tools?: Array<{\n name: string;\n description: string;\n }>;\n }>;\n model?: string;\n isCustom?: boolean;\n creationTimestampMs?: number;\n /**\n * Whether this assistant offers MCP servers of the tenant's own.\n *\n * Same contract as `tenantIntegrations` below, absence included.\n */\n tenantMcpServers?: {\n enabled: boolean;\n /** Servers listed ready to connect. Says nothing about how many are connected. */\n count?: number;\n };\n /**\n * Whether this assistant offers connected apps to its tenants.\n *\n * **Absent means \"cannot tell\", not \"no\"** — an API older than this field\n * says nothing, and treating silence as a no would hide the connected-apps\n * button from anyone whose deployment has not caught up yet.\n */\n tenantIntegrations?: {\n enabled: boolean;\n /**\n * How many apps the catalogue offers. An upper bound — the listing drops\n * any the provider cannot resolve — and enough to size a placeholder.\n */\n count?: number;\n };\n /**\n * Whether this assistant accepts messages sent while the conversation is\n * busy, queueing them instead of refusing them.\n *\n * **Absent means no**, unlike `tenantIntegrations` above. Promising a queue\n * that does not exist is paid for with a 409 and with the user's text left in\n * the air, so silence is read as the safe answer rather than as the open one.\n */\n messageQueueEnabled?: boolean;\n /** How many messages may wait at once before further sends are refused. */\n maxQueuedMessages?: number;\n}\n\n/**\n * Summary of a conversation for listing\n */\nexport interface ConversationSummary {\n chatUID: string;\n name?: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n}\n\nexport interface ListConversationsResponse {\n histories: ConversationSummary[];\n total: number;\n offset: number;\n limit: number;\n}\n\n/**\n * API error response\n */\nexport interface ApiError {\n statusCode: number;\n message: string;\n error?: string;\n /** Optional structured details (e.g. usage-limit blocking info on a 429). */\n details?: any;\n}\n\n/**\n * Feedback submission request\n */\nexport interface FeedbackSubmission {\n messageId: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n}\n\n/**\n * Feedback entry response\n */\nexport interface FeedbackEntry {\n _id: string;\n requestId: string;\n chatUID?: string;\n threadId?: string;\n agentId?: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n creationTimestamp: string;\n lastEditTimestamp?: string;\n}\n\n/**\n * Agent thread states\n */\nexport enum AgentThreadState {\n QUEUED = 'queued',\n PROCESSING = 'processing',\n COMPLETED = 'completed',\n FAILED = 'failed',\n TERMINATED = 'terminated',\n PAUSED = 'paused',\n PAUSED_FOR_APPROVAL = 'paused_for_approval',\n APPROVAL_REJECTED = 'approval_rejected',\n WAITING_FOR_RESPONSE = 'waiting_for_response',\n PAUSED_FOR_RESUME = 'paused_for_resume',\n HANDED_OFF = 'handed_off',\n GUARDRAIL_TRIGGER = 'guardrail_trigger',\n}\n\n/**\n * Task within an agent thread\n */\nexport interface AgentTaskDto {\n _id?: string;\n title?: string;\n description?: string;\n completed: boolean;\n}\n\n/**\n * Agent thread DTO\n */\nexport interface AgentThreadDto {\n _id?: string;\n agentId: string;\n state: AgentThreadState;\n threadContent: ChatMessage[];\n tasks?: AgentTaskDto[];\n finishReason?: string;\n pausedReason?: string;\n name?: string;\n creationTimestampMs?: number;\n lastEditTimestampMs?: number;\n pauseUntil?: number;\n isSubthread?: boolean;\n parentThreadId?: string;\n subThreadToolCallId?: string;\n parentAgentId?: string;\n}\n\n/**\n * Agent details\n */\nexport interface AgentDto {\n _id?: string;\n name: string;\n description?: string;\n imgUrl?: string;\n /** Pinned style of the generated avatar shown when there is no imgUrl. */\n avatarStyle?: AvatarStyle;\n agentId?: string;\n}\n\n/**\n * Hand-off tool response content\n */\nexport interface HandOffToolResponse {\n response: string;\n subthreadId: string;\n}\n\n/**\n * Represents a single tool call within a tool group\n */\nexport interface ToolGroupCall {\n name: string;\n input: any;\n output: any;\n toolCallId: string;\n}\n\n/**\n * Configuration for grouping consecutive tool calls under a single renderer\n */\nexport interface ToolGroupConfig {\n tools: string[];\n renderer: (calls: ToolGroupCall[]) => React.ReactNode;\n}\n\n/**\n * One of the end user's connected accounts for an app.\n *\n * The provider's own identifiers do not travel here beyond `id`, which the\n * client needs in order to name the account it wants disconnected — and which\n * the server re-checks against the caller's tenant on the way back in.\n */\nexport interface IntegrationAccount {\n id: string;\n status: string;\n connectedAt?: string;\n updatedAt?: string;\n /** True when the account exists but can no longer run tools. */\n needsReconnect?: boolean;\n statusReason?: string;\n}\n\n/**\n * One value the end user is asked for before an account can be connected —\n * their API key, the subdomain of their instance.\n *\n * Comes from the provider's own catalogue, so the form is rendered from this\n * rather than from anything app-specific: most apps do not authenticate with\n * credentials Devic holds, and there are hundreds of them.\n */\nexport interface IntegrationAuthField {\n name: string;\n label: string;\n type: string;\n required: boolean;\n description?: string;\n /** Prefilled — usually a provider endpoint most accounts should keep. */\n default?: string;\n /** Mask it on screen. */\n secret: boolean;\n}\n\n/**\n * One way of connecting an app.\n *\n * `redirect` schemes send the user to the provider; the rest are connected\n * with the values they type, without ever leaving the page.\n *\n * There is deliberately no field for the *application's* credentials: the\n * OAuth application belongs to the developer who embedded this widget, is\n * registered once for every tenant, and is never the end user's to supply.\n */\nexport interface IntegrationAuthScheme {\n /** The provider's own name for it: `OAUTH2`, `API_KEY`, … */\n mode: string;\n /** Credentials for this scheme are held for you — nothing to fill in. */\n composioManaged: boolean;\n redirect: boolean;\n /** What this account supplies. Empty for a scheme that asks nothing. */\n accountFields: IntegrationAuthField[];\n /** The provider's own setup guide, when there is one. */\n guideUrl?: string;\n}\n\n/**\n * The answer when connecting needs values that were not sent.\n *\n * `stage` decides who can act on it: `account` is the end user, and the form\n * asks them. `app` is the developer's OAuth application, which the end user\n * cannot register — so that case is shown as \"not available yet\" instead of a\n * form asking a stranger for someone else's client secret.\n */\nexport interface IntegrationSetupRequired {\n code: \"INTEGRATION_SETUP_REQUIRED\";\n message: string;\n toolkit: string;\n authScheme: string;\n stage: \"app\" | \"account\";\n fields: IntegrationAuthField[];\n guideUrl?: string;\n}\n\n/**\n * An app the assistant offers to its tenants, with the accounts THIS tenant\n * has connected. Never another tenant's.\n */\nexport interface Integration {\n /** App slug, e.g. `gmail`. */\n app: string;\n name: string;\n description?: string;\n logo?: string;\n /** True when at least one account is active. */\n connected: boolean;\n accounts: IntegrationAccount[];\n /** Event types the developer allows this tenant to switch on. */\n availableTriggers?: string[];\n}\n\n// ── MCP servers the end user connects for themselves ──────────────────────\n\nexport type TenantMcpAuthMode = \"oauth\" | \"header\" | \"none\";\n\n/** One of the end user's own MCP connections. */\nexport interface TenantMcpConnection {\n id: string;\n /**\n * What to put in `disabledIntegrations` to have this server sit a message\n * out. Sent by the API so the prefix that separates it from an app slug lives\n * on the server, in one place.\n */\n toggleId?: string;\n name?: string;\n url: string;\n /** The developer's template this came from, when it came from one. */\n templateId?: string;\n authMode?: TenantMcpAuthMode;\n status: \"pending_auth\" | \"active\" | \"error\";\n toolCount?: number;\n tools?: string[];\n lastProbeStatus?: string;\n lastProbeError?: string;\n lastProbeTimestampMs?: number;\n /** Connected for the whole tenant, so every end user of it shares this. */\n shared: boolean;\n /** True when this end user may use it but not change or remove it. */\n readOnly: boolean;\n}\n\n/**\n * One row of the MCP panel: either a server the developer offers ready to\n * connect, or one this end user added.\n *\n * A single list rather than two, because that is what the panel draws — keeping\n * \"offered\" and \"connected\" apart would leave them out of step for a moment\n * after every connect.\n */\nexport interface TenantMcpServer {\n source: \"template\" | \"custom\";\n templateId?: string;\n name: string;\n url: string;\n description?: string;\n logoUrl?: string;\n authMode?: TenantMcpAuthMode;\n /** Header the credential travels in, for `header` servers. */\n headerName?: string;\n /** Whether the end user may supply their own OAuth application. */\n allowClientCredentials?: boolean;\n /** Null until this tenant connects it. */\n connection: TenantMcpConnection | null;\n}\n\nexport interface TenantMcpListing {\n offered: boolean;\n /** Whether adding a server of one's own is permitted. */\n allowCustom: boolean;\n limits: { maxServers: number; maxToolsPerServer: number; used: number };\n servers: TenantMcpServer[];\n}\n\n/** Credentials the end user supplies when connecting a server. */\nexport interface TenantMcpAuthInput {\n mode?: TenantMcpAuthMode;\n headerName?: string;\n headerValue?: string;\n upstreamOAuth?: { clientId?: string; clientSecret?: string; scopes?: string[] };\n}\n\n/**\n * What connecting answers with.\n *\n * `status: \"active\"` means it is done. `authorizationUrl` must be opened in a\n * popup. `requiresClientCredentials` means the server has no dynamic client\n * registration and the end user has to register an OAuth application with it\n * themselves, authorising `callbackUrl` as the redirect URI.\n */\nexport interface TenantMcpConnectResult {\n id: string;\n status: \"pending_auth\" | \"active\" | \"error\";\n toolCount?: number;\n authorizationUrl?: string;\n requiresClientCredentials?: boolean;\n callbackUrl?: string;\n error?: string;\n}\n"],"names":["AgentThreadState"],"mappings":";;AA+CA;AACM,SAAU,oBAAoB,CAAC,IAAiB,EAAA;IAKpD,OAAO;QACL,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,GAAG,EAAE,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,IAAI,EAAE;QACvC,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,IAAI,OAAO;KAC5C;AACH;AAguBA;;AAEG;AACSA;AAAZ,CAAA,UAAY,gBAAgB,EAAA;AAC1B,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,qBAAA,CAAA,GAAA,qBAA2C;AAC3C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACzC,CAAC,EAbWA,wBAAgB,KAAhBA,wBAAgB,GAAA,EAAA,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"types.js","sources":["../../../../src/api/types.ts"],"sourcesContent":["import type { AvatarStyle } from '../utils/avatar';\n\nimport type React from 'react';\n\n/**\n * File attachment for messages\n */\nexport interface ChatFile {\n name: string;\n downloadUrl?: string;\n fileType?: 'image' | 'document' | 'audio' | 'video' | 'other';\n}\n\n/**\n * Attachment as it appears on a message.\n *\n * Two shapes reach the UI for the same thing: the optimistic message built\n * locally on send uses `url`/`type`, while the history returned by the API\n * carries the stored `downloadUrl`/`fileType`. Both are accepted here; use\n * `normalizeMessageFile` before reading them.\n */\nexport interface MessageFile {\n name: string;\n url?: string;\n type?: string;\n downloadUrl?: string;\n fileType?: string;\n}\n\n/**\n * Message content structure\n */\nexport interface MessageContent {\n /**\n * The message text.\n *\n * Declared as a string because that is what it is for every role a reader\n * cares about, but do not trust it blindly on a `guard_rail` message:\n * conversations stopped by a guardrail before the backend fix carry the raw\n * provider result object here instead. Guard a `typeof x === 'string'` check\n * around anything that treats it as text.\n */\n message?: string;\n data?: any;\n files?: MessageFile[];\n}\n\n/** Collapse either attachment shape into a single one the UI can render. */\nexport function normalizeMessageFile(file: MessageFile): {\n name: string;\n url: string;\n type: string;\n} {\n return {\n name: file.name,\n url: file.url || file.downloadUrl || '',\n type: file.type || file.fileType || 'other',\n };\n}\n\n/**\n * Tool call from the model\n */\nexport interface ToolCall {\n id: string;\n type: 'function';\n function: {\n name: string;\n arguments: string;\n };\n}\n\n/**\n * Chat message structure\n */\nexport interface ChatMessage {\n uid: string;\n role: 'user' | 'assistant' | 'developer' | 'system' | 'tool' | 'guard_rail';\n content: MessageContent;\n timestamp: number;\n chatUid?: string;\n tool_calls?: ToolCall[];\n tool_call_id?: string;\n summary?: string;\n /**\n * Where `content.message` came from, when the model did not write it.\n * `'finish_tool'`: the assistant is configured to require a tool call to\n * finish (\"Require Tool Use to Finish\") and the backend lifted the reply from\n * the finish tool's `message` argument, so it can be read without parsing\n * tool calls. Absent on replies the model wrote itself — use it to label the\n * bubble as produced by the tool.\n */\n contentSource?: string;\n /**\n * Id of a speech-to-text transcript (from POST /api/v1/whisper) that seeded\n * this message. Present on user messages dictated by voice; the chat can use\n * it to fetch the source audio (GET /api/v1/whisper/:transcriptId) and offer\n * playback.\n */\n transcriptId?: string;\n /**\n * Original server uid, present when the UI adopted an optimistic uid for\n * this message to keep React keys stable. Server-side references (e.g.\n * memory recall anchors) match against it.\n */\n serverUid?: string;\n /**\n * Client-side only: the conversation was busy when this message was sent, so\n * it was accepted into the queue and is waiting its turn. Drawn as a message\n * that has not landed rather than as part of the conversation. Falls away on\n * its own once the message comes back inside the history.\n */\n queued?: boolean;\n /**\n * Client-side only: when this message was accepted into the queue. Used to\n * tell \"the server has not reported it yet\" from \"the server no longer has\n * it\", which the timestamp is the only honest way to decide.\n */\n queuedAt?: number;\n}\n\n/**\n * Previous conversation message for initialization\n */\nexport interface PreviousMessage {\n message: string;\n role: 'user' | 'assistant';\n}\n\n/**\n * Model interface tool schema following OpenAI function calling format\n */\nexport interface ModelInterfaceToolSchema {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: {\n type: 'object';\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\n/**\n * Props passed to a response widget component.\n * The widget is responsible for collecting the user's response and\n * calling `submit` with the payload to resolve the tool call.\n */\nexport interface ResponseWidgetProps {\n /** The tool call this widget is responding to */\n toolCall: ToolCall;\n /** Parsed arguments from the tool call */\n params: any;\n /** Submit the tool response payload (sent as the tool call result to the model) */\n submit: (response: any) => void;\n /** Cancel the tool call. Sends an error response so the model can continue. */\n cancel?: (reason?: string) => void;\n /** Whether the widget is currently submitting */\n isSubmitting?: boolean;\n}\n\n/**\n * Interactive response widget configuration for a client-side tool.\n *\n * When the model calls a tool configured with a `responseWidget`, the\n * widget is rendered in the chat UI instead of executing a callback.\n * The user interacts with the widget, which calls `submit(response)` to\n * define the tool response sent back to the model.\n *\n * - `render: 'inline'` renders the widget in the message thread at the\n * position of the tool call. The text input remains enabled.\n * - `render: 'input'` replaces the chat input area with the widget\n * while it is pending. The text input is disabled until submission.\n */\nexport interface ResponseWidgetConfig {\n /** Where to render the widget */\n render: 'inline' | 'input';\n /** The widget component */\n component: React.ComponentType<ResponseWidgetProps>;\n}\n\n/**\n * Model interface tool definition for client-side tools.\n *\n * A tool must provide either a `callback` (executed automatically when\n * the model invokes the tool) or a `responseWidget` (renders UI for\n * the user to produce the tool response). Providing both is an error.\n */\nexport interface ModelInterfaceTool {\n toolName: string;\n schema: ModelInterfaceToolSchema;\n /** Executed automatically when the model calls this tool */\n callback?: (params: any) => Promise<any> | any;\n /** Interactive widget that collects the user's tool response */\n responseWidget?: ResponseWidgetConfig;\n}\n\n/**\n * Tool call response to send back to the API\n */\nexport interface ToolCallResponse {\n tool_call_id: string;\n content: any;\n role: 'tool';\n /**\n * The client-side tools still on offer for the rest of the turn. The API\n * reads them off the first response of the batch: leaving them out drops\n * the tools from the continuation, so the model cannot call them again.\n */\n tools?: ModelInterfaceToolSchema[];\n}\n\n/**\n * DTO for sending messages to the assistant\n */\nexport interface ProcessMessageDto {\n disabledIntegrations?: string[];\n message: string;\n chatUid?: string;\n userName?: string;\n files?: ChatFile[];\n /** Tags to associate with this chat (top-level, distinct from `metadata`). */\n tags?: string[];\n metadata?: {\n promptTemplateParams?: Record<string, any>;\n tenantToken?: string;\n [key: string]: any;\n };\n tenantId?: string;\n subtenantId?: string;\n previousConversation?: PreviousMessage[];\n enabledTools?: string[];\n provider?: string;\n model?: string;\n // Model interface protocol fields\n tools?: ModelInterfaceToolSchema[];\n applicationState?: Record<string, any>;\n skipSummarization?: boolean;\n /**\n * Id of a speech-to-text transcript (from POST /api/v1/whisper) that seeded\n * this message. Sent so the conversation keeps a link to the original audio.\n */\n transcriptId?: string;\n}\n\n/**\n * Response from the /whisper speech-to-text endpoint.\n */\nexport interface WhisperTranscriptionResponse {\n /** Public id of the transcript; send it back as ProcessMessageDto.transcriptId. */\n transcriptId: string;\n /** Transcribed text. */\n text: string;\n /** Language hint used, if any. */\n language?: string;\n /** Download URL of the source audio. */\n audioUrl?: string;\n /** Transcription model used. */\n model?: string;\n}\n\n/**\n * Response from the assistant\n */\nexport interface AssistantResponse {\n messages: ChatMessage[];\n chatUid: string;\n inputTokens?: number;\n outputTokens?: number;\n}\n\n/**\n * Async mode response\n */\nexport interface AsyncResponse {\n chatUid: string;\n message?: string;\n error?: string;\n /**\n * The conversation could not take the message right now, so it was queued\n * instead of starting a run of its own. Still an acceptance: the answer comes\n * later, and may cover several messages at once.\n */\n queued?: boolean;\n /** How many messages are queued on this conversation, this one included. */\n queuePosition?: number;\n /** When the queued message reaches the model. */\n willProcess?: QueueDisposition;\n}\n\n/**\n * When a queued message will reach the model.\n *\n * `after_delay` is the one that is not about being busy: an idle conversation\n * on an assistant with an input delay collects what is written during the\n * window, so a message can come back queued with nothing in flight at all.\n */\nexport type QueueDisposition = 'after_delay' | 'next_turn' | 'on_resume';\n\n/** Response of the stop endpoint. */\nexport interface StopChatResponse {\n chatUid: string;\n message: string;\n /**\n * Queued messages the stop threw away — answering them would be the opposite\n * of what was asked. Handed back so their text can be put where the user\n * wrote it. Absent on an API older than this, and when nothing was queued.\n */\n discardedMessages?: ChatMessage[];\n}\n\n/**\n * Real-time chat history status.\n * `limit_exceeded` means the message was blocked before reaching the LLM\n * because a configured tenant/subtenant usage limit was reached.\n */\nexport type RealtimeStatus =\n | 'processing'\n | 'completed'\n | 'error'\n | 'waiting_for_tool_response'\n | 'handed_off'\n | 'limit_exceeded'\n /** Collecting messages during the assistant's input delay, before any run. */\n | 'buffering';\n\n/**\n * Details of a tenant/subtenant usage limit that blocked a message.\n * Returned on the realtime endpoint when status is `limit_exceeded`, and on\n * the HTTP 429 body (`details`) when a synchronous request is blocked.\n */\nexport interface TenantLimitExceeded {\n /** Human-readable message describing the block. */\n message?: string;\n /** The rule that triggered the block (scope, metric, window, limit…). */\n blockingRule?: {\n scope?: 'tenant' | 'subtenant';\n subtenantId?: string;\n metric?: 'tokens' | 'cost';\n windowUnit?: 'hour' | 'day' | 'week' | 'month';\n windowEvery?: number;\n limit?: number;\n };\n /** Current consumption in the blocking window. */\n current?: number;\n /** The limit that was reached. */\n limit?: number;\n /** Epoch ms when the blocking window resets and usage is allowed again. */\n resetsAt?: number;\n}\n\n/** One fact a long-term-memory recall surfaced. */\nexport interface RecalledMemoryFact {\n fact: string;\n relation: string;\n /** Source entity name of the graph edge, when the fact connects two. */\n source: string | null;\n /** Target entity name of the graph edge, when the fact connects two. */\n target: string | null;\n /** ISO date the fact became valid, if known. */\n validAt: string | null;\n}\n\n/** One graph entity a long-term-memory recall surfaced. */\nexport interface RecalledMemoryEntity {\n id: string;\n name: string;\n type: string;\n summary: string | null;\n}\n\n/** One previous-session turn a conversation-start recall carried over. */\nexport interface RecalledMemoryTurn {\n role: string;\n content: string;\n}\n\n/**\n * One structured long-term-memory recall event of a conversation: the facts,\n * entities and previous-session turns a recall surfaced, plus the uid of the\n * message that brought it in (`messageUid`: the initial user message, or the\n * assistant message carrying the memory tool call — resolvable through\n * `toolCallId` while the run is still in flight).\n */\nexport interface RecalledMemoryRecord {\n uid: string;\n messageUid?: string;\n toolCallId?: string;\n source:\n | 'conversation_start'\n | 'search_memory'\n | 'search_memory_nodes'\n | 'explore_memory_graph';\n query?: string;\n facts?: RecalledMemoryFact[];\n entities?: RecalledMemoryEntity[];\n turns?: RecalledMemoryTurn[];\n timestampMs: number;\n}\n\n/**\n * Snapshot of the core-memory block a conversation saw (audit trail): the\n * render revision plus the injected entries as structured items.\n */\nexport interface CoreMemorySnapshot {\n uid: string;\n revision: string;\n items: Array<{\n id: number;\n section: string;\n content: string;\n pinned: boolean;\n source: string;\n }>;\n entries: number;\n omitted: number;\n chars: number;\n timestampMs: number;\n}\n\n/** A backend tool call waiting on an external system for its result. */\nexport interface PendingAsyncToolCall {\n toolCallId: string;\n toolName: string;\n sentAt: number;\n resolved: boolean;\n resolvedAt?: number;\n /** Where the external system posts the result. */\n callbackUrl?: string;\n}\n\n/**\n * Real-time chat history response\n */\nexport interface RealtimeChatHistory {\n /** Ephemeral provider output; never persisted or treated as a tool call. */\n streamingMessage?: ChatMessage;\n chatUID: string;\n clientUID: string;\n chatHistory: ChatMessage[];\n status: RealtimeStatus;\n lastUpdatedAt: number;\n pendingToolCalls?: ToolCall[];\n /**\n * Backend tools whose result an external system posts later. They hold the\n * conversation in `waiting_for_tool_response` too, but they are not the\n * client's to answer.\n */\n pendingAsyncToolCalls?: PendingAsyncToolCall[];\n handedOffSubThreadId?: string;\n /** Present only when status is `limit_exceeded`. */\n limitExceeded?: TenantLimitExceeded;\n /**\n * Memory-recall events of the in-flight run — lets the UI show what the\n * assistant is recalling while the response is still processing.\n */\n recalledMemories?: RecalledMemoryRecord[];\n /**\n * Messages accepted into this conversation that the model has not seen yet.\n * Non-zero means more is coming: a `completed` status with messages still\n * queued is not the end of the exchange.\n */\n queuedMessages?: number;\n /**\n * The queued messages themselves. This is the conversation's queue, not the\n * caller's — it can include messages the same conversation received through\n * another channel. Absent on an API that does not return them, in which case\n * the widget falls back to its own optimistic copies.\n */\n pendingUserMessages?: ChatMessage[];\n /**\n * Compaction checkpoints of the in-flight run. A conversation that compacts\n * mid-run stops sending the messages above the cut immediately, so these\n * arrive here before they are persisted on the conversation.\n */\n compactions?: CompactionCheckpoint[];\n /** The compaction running right now, if any. */\n compaction?: CompactionActivity;\n}\n\n/**\n * A single usage rule with its current consumption (from GET\n * /api/v1/tenant-usage/:tenantId[/subtenants/:subtenantId]).\n */\nexport interface TenantUsageRule {\n scope: 'tenant' | 'subtenant';\n subtenantId?: string;\n metric: 'tokens' | 'cost';\n windowUnit: 'hour' | 'day' | 'week' | 'month';\n windowEvery: number;\n /** Configured limit for the window. */\n limit: number;\n /** Current consumption in the active window. */\n current: number;\n /** Utilization percentage (0..100, capped). */\n percent: number;\n /** Epoch ms when the active window resets. */\n resetsAt?: number;\n /** Where the rule comes from ('tier' | 'adhoc'). */\n origin?: string;\n /** Tier the rule belongs to, if any. */\n tierId?: string;\n}\n\n/**\n * Response of GET /api/v1/tenant-usage/:tenantId[/subtenants/:subtenantId]:\n * the effective usage rules with their current consumption + the active tier.\n */\nexport interface TenantUsage {\n tenantId: string;\n subtenantId?: string;\n tierId?: string;\n usage: TenantUsageRule[];\n}\n\n/**\n * A durable per-window usage history row (from GET\n * /api/v1/tenant-usage/:tenantId/history).\n */\nexport interface TenantUsageHistoryRow {\n clientUID: string;\n tenantId: string;\n subtenantId: string;\n scope: 'tenant' | 'subtenant';\n metric: 'tokens' | 'cost';\n windowUnit: 'hour' | 'day' | 'week' | 'month';\n windowEvery: number;\n windowKey: string;\n windowStart: number;\n windowEnd: number;\n /** Counted consumption (enforced). */\n consumption: number;\n /** Exempt consumption that did not count toward the limit, if any. */\n exemptConsumption?: number;\n limit: number;\n percent: number;\n tierId?: string;\n origin?: string;\n capturedAt: number;\n}\n\n/**\n * Options for querying tenant usage history.\n */\nexport interface TenantUsageHistoryQuery {\n subtenantId?: string;\n scope?: 'tenant' | 'subtenant';\n metric?: 'tokens' | 'cost';\n windowUnit?: 'hour' | 'day' | 'week' | 'month';\n /** Epoch ms lower bound (windowEnd >= from). */\n from?: number;\n /** Epoch ms upper bound (windowEnd <= to). */\n to?: number;\n limit?: number;\n skip?: number;\n}\n\n/**\n * Chat history structure\n */\n/** A concrete value carried verbatim through a compaction. */\nexport interface CompactionFact {\n kind: string;\n value: string;\n label?: string;\n}\n\n/** The structured body a compaction produced. */\nexport interface CompactionSummary {\n goal?: string;\n constraints?: string[];\n inProgress?: string;\n pending?: string[];\n decisions?: string[];\n data?: Array<{ label: string; value: string }>;\n done?: string[];\n openQuestions?: string[];\n /** Fallback when the model answered without structure. */\n raw?: string;\n}\n\n/**\n * One compaction of a conversation: the messages before its boundary folded\n * into a written summary plus the identifiers, paths and urls lifted out of\n * them verbatim. From then on the model receives the checkpoint instead of\n * those messages — which are still in the conversation, and still shown.\n *\n * Only the newest checkpoint is in force: each compaction merges the previous\n * summary into itself.\n */\nexport interface CompactionCheckpoint {\n uid: string;\n /** 1 for the first compaction of the conversation, 2 for the next… */\n index: number;\n timestampMs: number;\n trigger: 'auto' | 'manual';\n /** First message that still travels verbatim. */\n firstKeptMessageUid?: string;\n /** Last folded message: where the widget belongs in the conversation. */\n anchorMessageUid?: string;\n compactedMessageCount: number;\n summary: CompactionSummary;\n facts: CompactionFact[];\n tokensBefore: number;\n tokensAfter: number;\n provider?: string;\n model?: string;\n cost?: number;\n}\n\n/**\n * A compaction happening right now, from the realtime endpoint.\n *\n * A compaction is a model call of its own, taken between two assistant\n * messages, so a client that only knows `processing` shows a conversation\n * that appears to have stalled for a few seconds. Present while it runs and\n * on the single update that reports it finished.\n */\nexport interface CompactionActivity {\n state: 'running' | 'completed';\n startedAt: number;\n /**\n * What this pass is folding: the messages new since the last checkpoint.\n * Not the conversation's totals — a checkpoint's own\n * `compactedMessageCount` and `tokensBefore` are cumulative across every\n * compaction, so the two are on different scales and must not be paired.\n */\n messageCount: number;\n tokensBefore: number;\n /** Which checkpoint the pass produced, once it is done. */\n index?: number;\n finishedAt?: number;\n}\n\nexport interface ChatHistory {\n chatUID: string;\n clientUID: string;\n userUID: string;\n chatContent: ChatMessage[];\n name?: string;\n assistantSpecializationIdentifier: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n llm?: string;\n inputTokens?: number;\n outputTokens?: number;\n metadata?: Record<string, any>;\n tenantId?: string;\n handedOff?: boolean;\n handedOffSubThreadId?: string;\n handedOffToolCallId?: string;\n /** Structured long-term-memory recall events of the conversation. */\n recalledMemories?: RecalledMemoryRecord[];\n /** Audit trail of the core-memory blocks the conversation saw. */\n coreMemories?: CoreMemorySnapshot[];\n /** Compaction checkpoints of the conversation, oldest first. */\n compactions?: CompactionCheckpoint[];\n}\n\n/** One core memory entry (the always-injected tier), as returned by the memory API. */\nexport interface CoreMemoryEntry {\n id: number;\n section: string;\n content: string;\n source: string;\n pinned: boolean;\n supersedes: number | null;\n archivedAt: string | null;\n createdAt?: string;\n updatedAt?: string;\n}\n\n/** Deployment caps of the core memory tier. */\nexport interface CoreMemoryLimits {\n maxChars: number;\n maxEntries: number;\n maxEntryChars: number;\n}\n\n/**\n * Response of GET /api/v1/memory/assistants/:identifier/core — the entries\n * of the bucket the assistant resolves for a tenant/subtenant combination.\n */\nexport interface CoreMemoryList {\n /** False when the assistant does not have the core memory tier enabled. */\n enabled: boolean;\n /** The resolved bucket tuple (tenant/subtenant/owner dimensions). */\n bucket: { tenantId?: string; subtenantId?: string; entityId?: string };\n entries: CoreMemoryEntry[];\n limits?: CoreMemoryLimits;\n}\n\n/**\n * Assistant specialization info\n */\nexport interface AssistantSpecialization {\n liveVoice?: import('./liveVoice.types').LiveVoiceConfiguration;\n identifier: string;\n name: string;\n description: string;\n state: 'active' | 'inactive' | 'coming_soon';\n imgUrl?: string;\n /** Pinned style of the generated avatar shown when there is no imgUrl. */\n avatarStyle?: AvatarStyle;\n availableToolsGroups?: Array<{\n name: string;\n description?: string;\n uid?: string;\n iconUrl?: string;\n tools?: Array<{\n name: string;\n description: string;\n }>;\n }>;\n model?: string;\n isCustom?: boolean;\n creationTimestampMs?: number;\n /**\n * Whether this assistant offers MCP servers of the tenant's own.\n *\n * Same contract as `tenantIntegrations` below, absence included.\n */\n tenantMcpServers?: {\n enabled: boolean;\n /** Servers listed ready to connect. Says nothing about how many are connected. */\n count?: number;\n };\n /**\n * Whether this assistant offers connected apps to its tenants.\n *\n * **Absent means \"cannot tell\", not \"no\"** — an API older than this field\n * says nothing, and treating silence as a no would hide the connected-apps\n * button from anyone whose deployment has not caught up yet.\n */\n tenantIntegrations?: {\n enabled: boolean;\n /**\n * How many apps the catalogue offers. An upper bound — the listing drops\n * any the provider cannot resolve — and enough to size a placeholder.\n */\n count?: number;\n };\n /**\n * Whether this assistant accepts messages sent while the conversation is\n * busy, queueing them instead of refusing them.\n *\n * **Absent means no**, unlike `tenantIntegrations` above. Promising a queue\n * that does not exist is paid for with a 409 and with the user's text left in\n * the air, so silence is read as the safe answer rather than as the open one.\n */\n messageQueueEnabled?: boolean;\n /** How many messages may wait at once before further sends are refused. */\n maxQueuedMessages?: number;\n}\n\n/**\n * Summary of a conversation for listing\n */\nexport interface ConversationSummary {\n chatUID: string;\n name?: string;\n creationTimestampMs: number;\n lastEditTimestampMs?: number;\n}\n\nexport interface ListConversationsResponse {\n histories: ConversationSummary[];\n total: number;\n offset: number;\n limit: number;\n}\n\n/**\n * API error response\n */\nexport interface ApiError {\n statusCode: number;\n message: string;\n error?: string;\n /** Optional structured details (e.g. usage-limit blocking info on a 429). */\n details?: any;\n}\n\n/**\n * Feedback submission request\n */\nexport interface FeedbackSubmission {\n messageId: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n}\n\n/**\n * Feedback entry response\n */\nexport interface FeedbackEntry {\n _id: string;\n requestId: string;\n chatUID?: string;\n threadId?: string;\n agentId?: string;\n feedback?: boolean;\n feedbackComment?: string;\n feedbackData?: Record<string, any>;\n creationTimestamp: string;\n lastEditTimestamp?: string;\n}\n\n/**\n * Agent thread states\n */\nexport enum AgentThreadState {\n QUEUED = 'queued',\n PROCESSING = 'processing',\n COMPLETED = 'completed',\n FAILED = 'failed',\n TERMINATED = 'terminated',\n PAUSED = 'paused',\n PAUSED_FOR_APPROVAL = 'paused_for_approval',\n APPROVAL_REJECTED = 'approval_rejected',\n WAITING_FOR_RESPONSE = 'waiting_for_response',\n PAUSED_FOR_RESUME = 'paused_for_resume',\n HANDED_OFF = 'handed_off',\n GUARDRAIL_TRIGGER = 'guardrail_trigger',\n}\n\n/**\n * Task within an agent thread\n */\nexport interface AgentTaskDto {\n _id?: string;\n title?: string;\n description?: string;\n completed: boolean;\n}\n\n/**\n * Agent thread DTO\n */\nexport interface AgentThreadDto {\n _id?: string;\n agentId: string;\n state: AgentThreadState;\n threadContent: ChatMessage[];\n tasks?: AgentTaskDto[];\n finishReason?: string;\n pausedReason?: string;\n name?: string;\n creationTimestampMs?: number;\n lastEditTimestampMs?: number;\n pauseUntil?: number;\n isSubthread?: boolean;\n parentThreadId?: string;\n subThreadToolCallId?: string;\n parentAgentId?: string;\n}\n\n/**\n * Agent details\n */\nexport interface AgentDto {\n _id?: string;\n name: string;\n description?: string;\n imgUrl?: string;\n /** Pinned style of the generated avatar shown when there is no imgUrl. */\n avatarStyle?: AvatarStyle;\n agentId?: string;\n}\n\n/**\n * Hand-off tool response content\n */\nexport interface HandOffToolResponse {\n response: string;\n subthreadId: string;\n}\n\n/**\n * Represents a single tool call within a tool group\n */\nexport interface ToolGroupCall {\n name: string;\n input: any;\n output: any;\n toolCallId: string;\n}\n\n/**\n * Configuration for grouping consecutive tool calls under a single renderer\n */\nexport interface ToolGroupConfig {\n tools: string[];\n renderer: (calls: ToolGroupCall[]) => React.ReactNode;\n}\n\n/**\n * One of the end user's connected accounts for an app.\n *\n * The provider's own identifiers do not travel here beyond `id`, which the\n * client needs in order to name the account it wants disconnected — and which\n * the server re-checks against the caller's tenant on the way back in.\n */\nexport interface IntegrationAccount {\n id: string;\n status: string;\n connectedAt?: string;\n updatedAt?: string;\n /** True when the account exists but can no longer run tools. */\n needsReconnect?: boolean;\n statusReason?: string;\n}\n\n/**\n * One value the end user is asked for before an account can be connected —\n * their API key, the subdomain of their instance.\n *\n * Comes from the provider's own catalogue, so the form is rendered from this\n * rather than from anything app-specific: most apps do not authenticate with\n * credentials Devic holds, and there are hundreds of them.\n */\nexport interface IntegrationAuthField {\n name: string;\n label: string;\n type: string;\n required: boolean;\n description?: string;\n /** Prefilled — usually a provider endpoint most accounts should keep. */\n default?: string;\n /** Mask it on screen. */\n secret: boolean;\n}\n\n/**\n * One way of connecting an app.\n *\n * `redirect` schemes send the user to the provider; the rest are connected\n * with the values they type, without ever leaving the page.\n *\n * There is deliberately no field for the *application's* credentials: the\n * OAuth application belongs to the developer who embedded this widget, is\n * registered once for every tenant, and is never the end user's to supply.\n */\nexport interface IntegrationAuthScheme {\n /** The provider's own name for it: `OAUTH2`, `API_KEY`, … */\n mode: string;\n /** Credentials for this scheme are held for you — nothing to fill in. */\n composioManaged: boolean;\n redirect: boolean;\n /** What this account supplies. Empty for a scheme that asks nothing. */\n accountFields: IntegrationAuthField[];\n /** The provider's own setup guide, when there is one. */\n guideUrl?: string;\n}\n\n/**\n * The answer when connecting needs values that were not sent.\n *\n * `stage` decides who can act on it: `account` is the end user, and the form\n * asks them. `app` is the developer's OAuth application, which the end user\n * cannot register — so that case is shown as \"not available yet\" instead of a\n * form asking a stranger for someone else's client secret.\n */\nexport interface IntegrationSetupRequired {\n code: \"INTEGRATION_SETUP_REQUIRED\";\n message: string;\n toolkit: string;\n authScheme: string;\n stage: \"app\" | \"account\";\n fields: IntegrationAuthField[];\n guideUrl?: string;\n}\n\n/**\n * An app the assistant offers to its tenants, with the accounts THIS tenant\n * has connected. Never another tenant's.\n */\nexport interface Integration {\n /** App slug, e.g. `gmail`. */\n app: string;\n name: string;\n description?: string;\n logo?: string;\n /** True when at least one account is active. */\n connected: boolean;\n accounts: IntegrationAccount[];\n /** Event types the developer allows this tenant to switch on. */\n availableTriggers?: string[];\n}\n\n// ── MCP servers the end user connects for themselves ──────────────────────\n\nexport type TenantMcpAuthMode = \"oauth\" | \"header\" | \"none\";\n\n/** One of the end user's own MCP connections. */\nexport interface TenantMcpConnection {\n id: string;\n /**\n * What to put in `disabledIntegrations` to have this server sit a message\n * out. Sent by the API so the prefix that separates it from an app slug lives\n * on the server, in one place.\n */\n toggleId?: string;\n name?: string;\n url: string;\n /** The developer's template this came from, when it came from one. */\n templateId?: string;\n authMode?: TenantMcpAuthMode;\n status: \"pending_auth\" | \"active\" | \"error\";\n toolCount?: number;\n tools?: string[];\n lastProbeStatus?: string;\n lastProbeError?: string;\n lastProbeTimestampMs?: number;\n /** Connected for the whole tenant, so every end user of it shares this. */\n shared: boolean;\n /** True when this end user may use it but not change or remove it. */\n readOnly: boolean;\n}\n\n/**\n * One row of the MCP panel: either a server the developer offers ready to\n * connect, or one this end user added.\n *\n * A single list rather than two, because that is what the panel draws — keeping\n * \"offered\" and \"connected\" apart would leave them out of step for a moment\n * after every connect.\n */\nexport interface TenantMcpServer {\n source: \"template\" | \"custom\";\n templateId?: string;\n name: string;\n url: string;\n description?: string;\n logoUrl?: string;\n authMode?: TenantMcpAuthMode;\n /** Header the credential travels in, for `header` servers. */\n headerName?: string;\n /** Whether the end user may supply their own OAuth application. */\n allowClientCredentials?: boolean;\n /** Null until this tenant connects it. */\n connection: TenantMcpConnection | null;\n}\n\nexport interface TenantMcpListing {\n offered: boolean;\n /** Whether adding a server of one's own is permitted. */\n allowCustom: boolean;\n limits: { maxServers: number; maxToolsPerServer: number; used: number };\n servers: TenantMcpServer[];\n}\n\n/** Credentials the end user supplies when connecting a server. */\nexport interface TenantMcpAuthInput {\n mode?: TenantMcpAuthMode;\n headerName?: string;\n headerValue?: string;\n upstreamOAuth?: { clientId?: string; clientSecret?: string; scopes?: string[] };\n}\n\n/**\n * What connecting answers with.\n *\n * `status: \"active\"` means it is done. `authorizationUrl` must be opened in a\n * popup. `requiresClientCredentials` means the server has no dynamic client\n * registration and the end user has to register an OAuth application with it\n * themselves, authorising `callbackUrl` as the redirect URI.\n */\nexport interface TenantMcpConnectResult {\n id: string;\n status: \"pending_auth\" | \"active\" | \"error\";\n toolCount?: number;\n authorizationUrl?: string;\n requiresClientCredentials?: boolean;\n callbackUrl?: string;\n error?: string;\n}\n"],"names":["AgentThreadState"],"mappings":";;AA+CA;AACM,SAAU,oBAAoB,CAAC,IAAiB,EAAA;IAKpD,OAAO;QACL,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,GAAG,EAAE,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,WAAW,IAAI,EAAE;QACvC,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,IAAI,OAAO;KAC5C;AACH;AAivBA;;AAEG;AACSA;AAAZ,CAAA,UAAY,gBAAgB,EAAA;AAC1B,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,qBAAA,CAAA,GAAA,qBAA2C;AAC3C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACvC,IAAA,gBAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,gBAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;AACzC,CAAC,EAbWA,wBAAgB,KAAhBA,wBAAgB,GAAA,EAAA,CAAA,CAAA;;;;"}
@@ -166,7 +166,7 @@ function useAICommandBar(options) {
166
166
  }
167
167
  }, [apiKey, baseUrl]);
168
168
  // Model interface
169
- const { toolSchemas, handleToolCalls: executeToolCalls, extractPendingToolCalls, } = useModelInterface.useModelInterface({
169
+ const { toolSchemas, handleToolCalls: executeToolCalls, resolvePendingToolCalls, } = useModelInterface.useModelInterface({
170
170
  tools: modelInterfaceTools,
171
171
  onToolExecute: onToolCall,
172
172
  });
@@ -340,13 +340,13 @@ function useAICommandBar(options) {
340
340
  const handlePendingToolCalls = React.useCallback(async (data) => {
341
341
  if (!clientRef.current || !chatUid)
342
342
  return;
343
- const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);
343
+ const pendingCalls = resolvePendingToolCalls(data);
344
344
  if (pendingCalls.length === 0)
345
345
  return;
346
346
  try {
347
- const { responses } = await executeToolCalls(pendingCalls);
347
+ const { responses, toolSchemas: schemas } = await executeToolCalls(pendingCalls);
348
348
  if (responses.length > 0) {
349
- await clientRef.current.sendToolResponses(assistantId, chatUid, responses, toolSchemas);
349
+ await clientRef.current.sendToolResponses(assistantId, chatUid, responses, schemas);
350
350
  setShouldPoll(true);
351
351
  }
352
352
  }
@@ -355,7 +355,7 @@ function useAICommandBar(options) {
355
355
  setError(error);
356
356
  onErrorRef.current?.(error);
357
357
  }
358
- }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]);
358
+ }, [chatUid, assistantId, executeToolCalls, resolvePendingToolCalls]);
359
359
  // Polling
360
360
  usePolling.usePolling(shouldPoll ? chatUid : null, async () => {
361
361
  if (!clientRef.current || !chatUid) {
@@ -1 +1 @@
1
- {"version":3,"file":"useAICommandBar.js","sources":["../../../../../src/components/AICommandBar/useAICommandBar.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef, useMemo } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling, resolvePollingInterval, resolveStreaming } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport { useTranslations } from '../../i18n';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\nimport type {\n AICommandBarOptions,\n AICommandBarCommand,\n CommandBarResult,\n ToolCallSummary,\n ChatDrawerHandle,\n} from './AICommandBar.types';\n\nexport interface UseAICommandBarOptions {\n assistantId: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n /** Tags applied to the conversation (merged/deduped with the provider's). */\n tags?: string[];\n /** Poll cadence (ms) for the command in progress (overrides the provider's). */\n pollingInterval?: number;\n /** Follow it over a server-sent event stream instead of polling (overrides the provider's). */\n streaming?: boolean;\n options?: AICommandBarOptions;\n isVisible?: boolean;\n onVisibilityChange?: (visible: boolean) => void;\n onExecute?: 'openDrawer' | 'callback';\n chatDrawerRef?: React.RefObject<ChatDrawerHandle>;\n onResponse?: (response: CommandBarResult) => void;\n modelInterfaceTools?: ModelInterfaceTool[];\n onSubmit?: (message: string) => void;\n onToolCall?: (toolName: string, params: Record<string, any>) => void;\n onError?: (error: Error) => void;\n onOpen?: () => void;\n onClose?: () => void;\n}\n\nexport interface UseAICommandBarResult {\n // Visibility\n isVisible: boolean;\n open: () => void;\n close: () => void;\n toggle: () => void;\n\n // Input\n inputValue: string;\n setInputValue: (value: string) => void;\n inputRef: React.RefObject<HTMLInputElement>;\n focus: () => void;\n\n // Processing state\n isProcessing: boolean;\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Result\n result: CommandBarResult | null;\n chatUid: string | null;\n error: Error | null;\n\n // History\n history: string[];\n historyIndex: number;\n showingHistory: boolean;\n setShowingHistory: (show: boolean) => void;\n\n // Commands\n showingCommands: boolean;\n filteredCommands: AICommandBarCommand[];\n selectedCommandIndex: number;\n selectCommand: (command: AICommandBarCommand) => void;\n\n // Actions\n submit: (message?: string) => Promise<void>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n clearHistory: () => void;\n}\n\n/**\n * Parse a shortcut string like \"cmd+j\" into its components\n */\nfunction parseShortcut(shortcut: string): { key: string; modifiers: string[] } {\n const parts = shortcut.toLowerCase().split('+');\n const key = parts.pop() || '';\n const modifiers = parts;\n return { key, modifiers };\n}\n\n/**\n * Check if a keyboard event matches a shortcut string\n */\nfunction matchShortcut(event: KeyboardEvent, shortcut: string): boolean {\n const { key, modifiers } = parseShortcut(shortcut);\n\n const keyMatch = event.key.toLowerCase() === key;\n const cmdMatch = modifiers.includes('cmd') === (event.metaKey || event.ctrlKey);\n const shiftMatch = modifiers.includes('shift') === event.shiftKey;\n const altMatch = modifiers.includes('alt') === event.altKey;\n\n return keyMatch && cmdMatch && shiftMatch && altMatch;\n}\n\n/**\n * Format a shortcut string for display\n */\nexport function formatShortcut(shortcut: string): string {\n const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform);\n return shortcut\n .replace(/cmd/gi, isMac ? '\\u2318' : 'Ctrl')\n .replace(/shift/gi, '\\u21E7')\n .replace(/alt/gi, isMac ? '\\u2325' : 'Alt')\n .replace(/\\+/g, ' ')\n .replace(/([a-z])/gi, (match) => match.toUpperCase());\n}\n\n/**\n * Format tool name to human-readable (fallback when no summary)\n */\nfunction formatToolName(toolName: string): string {\n // Convert snake_case or camelCase to human-readable\n return toolName\n .replace(/_/g, ' ')\n .replace(/([A-Z])/g, ' $1')\n .trim()\n .toLowerCase()\n .replace(/^./, (c) => c.toUpperCase());\n}\n\n/**\n * Hook for managing AICommandBar state and behavior\n */\nexport function useAICommandBar(options: UseAICommandBarOptions): UseAICommandBarResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n tags,\n pollingInterval: propsPollingInterval,\n streaming: propsStreaming,\n options: barOptions = {},\n isVisible: controlledVisible,\n onVisibilityChange,\n onExecute = 'callback',\n chatDrawerRef,\n onResponse,\n modelInterfaceTools = [],\n onSubmit,\n onToolCall,\n onError,\n onOpen,\n onClose,\n } = options;\n\n const { shortcut } = barOptions;\n\n const t = useTranslations(barOptions.translations);\n\n // Get context\n const context = useOptionalDevicContext();\n const apiKey = propsApiKey || context?.apiKey;\n const getTenantSession = context?.getTenantSession;\n const onSessionExpired = context?.onSessionExpired;\n const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';\n const resolvedTenantId = tenantId || context?.tenantId;\n const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };\n const resolvedTags = Array.from(\n new Set([...(context?.tags ?? []), ...(tags ?? [])])\n );\n const pollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval\n );\n const streaming = resolveStreaming(propsStreaming, context?.streaming);\n\n // Visibility state\n const [internalVisible, setInternalVisible] = useState(false);\n const isVisible = controlledVisible ?? internalVisible;\n\n // Input state\n const [inputValue, setInputValue] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n\n // Processing state\n const [isProcessing, setIsProcessing] = useState(false);\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Result state\n const [result, setResult] = useState<CommandBarResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Polling state\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // History state\n const enableHistory = barOptions.enableHistory !== false; // default true\n const maxHistoryItems = barOptions.maxHistoryItems ?? 50;\n const historyStorageKey = barOptions.historyStorageKey ?? 'devic-command-bar-history';\n const showHistoryCommand = barOptions.showHistoryCommand !== false; // default true\n\n const [history, setHistory] = useState<string[]>(() => {\n if (!enableHistory || typeof window === 'undefined') return [];\n try {\n const stored = localStorage.getItem(historyStorageKey);\n return stored ? JSON.parse(stored) : [];\n } catch {\n return [];\n }\n });\n const [historyIndex, setHistoryIndex] = useState(-1);\n const [showingHistory, setShowingHistory] = useState(false);\n const [tempInput, setTempInput] = useState(''); // Store current input when navigating history\n\n // Commands state\n const commands = barOptions.commands ?? [];\n const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);\n\n // Built-in history command\n const historyCommand: AICommandBarCommand = useMemo(() => ({\n keyword: 'history',\n description: t('Show command history'),\n message: '', // Special handling\n }), [t]);\n\n // All available commands (user commands + built-in)\n const allCommands = useMemo(() => {\n const userCommands = commands;\n // Add history command if enabled and not overwritten\n if (showHistoryCommand && !userCommands.some(c => c.keyword === 'history')) {\n return [...userCommands, historyCommand];\n }\n return userCommands;\n }, [commands, showHistoryCommand, historyCommand]);\n\n // Detect if showing command suggestions\n const isCommandMode = inputValue.startsWith('/');\n const commandQuery = isCommandMode ? inputValue.slice(1).toLowerCase() : '';\n const showingCommands = isCommandMode && !isProcessing && !result;\n\n // Filter commands based on query\n const filteredCommands = useMemo(() => {\n if (!showingCommands) return [];\n if (commandQuery === '') return allCommands;\n return allCommands.filter(cmd =>\n cmd.keyword.toLowerCase().includes(commandQuery) ||\n cmd.description.toLowerCase().includes(commandQuery)\n );\n }, [showingCommands, commandQuery, allCommands]);\n\n // Reset command selection when filtered list changes\n useEffect(() => {\n setSelectedCommandIndex(0);\n }, [filteredCommands.length]);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onToolCallRef = useRef(onToolCall);\n const onSubmitRef = useRef(onSubmit);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onToolCallRef.current = onToolCall;\n onSubmitRef.current = onSubmit;\n onOpenRef.current = onOpen;\n onCloseRef.current = onClose;\n });\n\n // API client\n const clientRef = useRef<DevicApiClient | null>(null);\n if (!clientRef.current && (apiKey || getTenantSession)) {\n clientRef.current = new DevicApiClient({ apiKey, baseUrl, getTenantSession, onSessionExpired });\n }\n\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n // Model interface\n const {\n toolSchemas,\n handleToolCalls: executeToolCalls,\n extractPendingToolCalls,\n } = useModelInterface({\n tools: modelInterfaceTools,\n onToolExecute: onToolCall,\n });\n\n // Visibility controls\n const open = useCallback(() => {\n setInternalVisible(true);\n onVisibilityChange?.(true);\n onOpenRef.current?.();\n // Focus input after visibility change\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [onVisibilityChange]);\n\n const close = useCallback(() => {\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n }, [onVisibilityChange]);\n\n const toggle = useCallback(() => {\n if (isVisible) {\n close();\n } else {\n open();\n }\n }, [isVisible, open, close]);\n\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Save history to localStorage\n const saveHistory = useCallback((newHistory: string[]) => {\n if (!enableHistory || typeof window === 'undefined') return;\n try {\n localStorage.setItem(historyStorageKey, JSON.stringify(newHistory));\n } catch {\n // Ignore localStorage errors\n }\n }, [enableHistory, historyStorageKey]);\n\n // Add item to history\n const addToHistory = useCallback((message: string) => {\n if (!enableHistory || !message.trim() || message.startsWith('/')) return;\n\n setHistory(prev => {\n // Don't add duplicates at the top\n const filtered = prev.filter(item => item !== message);\n const newHistory = [message, ...filtered].slice(0, maxHistoryItems);\n saveHistory(newHistory);\n return newHistory;\n });\n setHistoryIndex(-1);\n }, [enableHistory, maxHistoryItems, saveHistory]);\n\n // Clear history\n const clearHistory = useCallback(() => {\n setHistory([]);\n setHistoryIndex(-1);\n if (enableHistory && typeof window !== 'undefined') {\n try {\n localStorage.removeItem(historyStorageKey);\n } catch {\n // Ignore\n }\n }\n }, [enableHistory, historyStorageKey]);\n\n // Navigate history\n const navigateHistory = useCallback((direction: 'up' | 'down') => {\n if (!enableHistory || history.length === 0) return;\n\n if (direction === 'up') {\n if (historyIndex === -1) {\n // Save current input before navigating\n setTempInput(inputValue);\n setHistoryIndex(0);\n setInputValue(history[0]);\n } else if (historyIndex < history.length - 1) {\n const newIndex = historyIndex + 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n }\n } else {\n if (historyIndex > 0) {\n const newIndex = historyIndex - 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n } else if (historyIndex === 0) {\n setHistoryIndex(-1);\n setInputValue(tempInput);\n }\n }\n }, [enableHistory, history, historyIndex, inputValue, tempInput]);\n\n // Ref to hold submit function (to avoid circular dependency)\n const submitRef = useRef<(message?: string) => Promise<void>>();\n\n // Select a command\n const selectCommand = useCallback((command: AICommandBarCommand) => {\n if (command.keyword === 'history') {\n // Special handling for history command\n setShowingHistory(true);\n setInputValue('');\n } else {\n // Send the command's message\n setInputValue('');\n submitRef.current?.(command.message);\n }\n }, []);\n\n // Navigate commands\n const navigateCommands = useCallback((direction: 'up' | 'down') => {\n if (filteredCommands.length === 0) return;\n\n if (direction === 'down') {\n setSelectedCommandIndex(prev =>\n prev < filteredCommands.length - 1 ? prev + 1 : 0\n );\n } else {\n setSelectedCommandIndex(prev =>\n prev > 0 ? prev - 1 : filteredCommands.length - 1\n );\n }\n }, [filteredCommands.length]);\n\n // Register keyboard shortcut\n useEffect(() => {\n if (!shortcut) return;\n\n const handler = (e: KeyboardEvent) => {\n if (matchShortcut(e, shortcut)) {\n e.preventDefault();\n toggle();\n }\n };\n\n window.addEventListener('keydown', handler);\n return () => window.removeEventListener('keydown', handler);\n }, [shortcut, toggle]);\n\n // Process tool calls from realtime data\n const processToolCalls = useCallback((messages: ChatMessage[]): ToolCallSummary[] => {\n const summaries: ToolCallSummary[] = [];\n const toolResponseMap = new Map<string, any>();\n\n // Collect tool responses\n for (const msg of messages) {\n if (msg.role === 'tool' && msg.tool_call_id) {\n toolResponseMap.set(msg.tool_call_id, msg.content);\n }\n }\n\n // Collect tool calls from assistant messages\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.tool_calls?.length) {\n for (const tc of msg.tool_calls) {\n const hasResponse = toolResponseMap.has(tc.id);\n let input: any;\n try {\n input = JSON.parse(tc.function.arguments || '{}');\n } catch {\n input = {};\n }\n\n // Use message summary if available, otherwise format tool name\n const summaryText = msg.summary || formatToolName(tc.function.name);\n\n summaries.push({\n id: tc.id,\n name: tc.function.name,\n status: hasResponse ? 'completed' : 'executing',\n summary: summaryText,\n input,\n output: toolResponseMap.get(tc.id),\n });\n }\n }\n }\n\n return summaries;\n }, []);\n\n // Handle pending client-side tool calls\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid) return;\n\n const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);\n if (pendingCalls.length === 0) return;\n\n try {\n const { responses } = await executeToolCalls(pendingCalls);\n if (responses.length > 0) {\n await clientRef.current.sendToolResponses(\n assistantId,\n chatUid,\n responses,\n toolSchemas\n );\n setShouldPoll(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]\n );\n\n // Polling\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid) {\n throw new Error(t('Cannot poll without client or chatUid'));\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\n streamFn: streaming\n ? (onSnapshot, signal, onActivity) => clientRef.current!.streamRealtimeHistory(assistantId!, chatUid!, onSnapshot, signal, onActivity)\n : undefined,\n enabled: shouldPoll,\n stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],\n onUpdate: async (data: RealtimeChatHistory) => {\n // Update tool calls display\n const summaries = processToolCalls(data.chatHistory);\n setToolCalls(summaries);\n\n // Update current tool summary\n // Prefer showing an executing tool, but fall back to the last tool (completed or not)\n if (summaries.length > 0) {\n const lastExecuting = summaries.filter(s => s.status === 'executing').pop();\n const lastTool = summaries[summaries.length - 1];\n setCurrentToolSummary(lastExecuting?.summary || lastTool?.summary || null);\n }\n\n // Handle client-side tool calls\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n setShouldPoll(false);\n\n if (data?.status === 'error') {\n setIsProcessing(false);\n const err = new Error(t('Processing failed'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n if (data?.status === 'completed') {\n setIsProcessing(false);\n\n // Extract final assistant message\n const assistantMessages = data.chatHistory.filter(m => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const commandResult: CommandBarResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: processToolCalls(data.chatHistory),\n };\n\n setResult(commandResult);\n\n // Handle execution mode\n if (onExecute === 'openDrawer' && chatDrawerRef?.current) {\n chatDrawerRef.current.setChatUid(chatUid);\n chatDrawerRef.current.open();\n // Close and reset the command bar when handing off to drawer\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n } else {\n onResponseRef.current?.(commandResult);\n }\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n }\n );\n\n // Submit message\n const submit = useCallback(\n async (message?: string) => {\n const msg = message ?? inputValue;\n if (!msg.trim()) return;\n\n if (!clientRef.current) {\n const err = new Error(\n t('API client not configured. Please provide an API key.')\n );\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n // Add to history before processing\n addToHistory(msg);\n\n // Clear input and start processing\n setInputValue('');\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setShowingHistory(false);\n setHistoryIndex(-1);\n\n onSubmitRef.current?.(msg);\n\n try {\n const dto = {\n message: msg,\n chatUid: chatUid || undefined,\n metadata: resolvedTenantMetadata,\n tenantId: resolvedTenantId,\n ...(resolvedTags.length > 0 && { tags: resolvedTags }),\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n };\n\n const response = await clientRef.current.sendMessageAsync(assistantId, dto);\n\n if (response.chatUid && response.chatUid !== chatUid) {\n setChatUid(response.chatUid);\n }\n\n setShouldPoll(true);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n setIsProcessing(false);\n onErrorRef.current?.(error);\n }\n },\n [inputValue, chatUid, assistantId, resolvedTenantId, resolvedTenantMetadata, resolvedTags, toolSchemas, addToHistory]\n );\n\n // Update submit ref for use in selectCommand\n submitRef.current = submit;\n\n // Reset state\n const reset = useCallback(() => {\n setInputValue('');\n setIsProcessing(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setResult(null);\n setChatUid(null);\n setError(null);\n setShouldPoll(false);\n }, []);\n\n // Handle keyboard events\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n // Handle Escape\n if (e.key === 'Escape') {\n e.preventDefault();\n if (showingHistory) {\n setShowingHistory(false);\n return;\n }\n if (showingCommands) {\n setInputValue('');\n return;\n }\n // Reset if there's a result or if processing\n if (result || isProcessing) {\n reset();\n }\n close();\n return;\n }\n\n // Handle arrow keys for commands\n if (showingCommands && filteredCommands.length > 0) {\n if (e.key === 'ArrowDown') {\n e.preventDefault();\n navigateCommands('down');\n return;\n }\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateCommands('up');\n return;\n }\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n selectCommand(selectedCommand);\n }\n return;\n }\n if (e.key === 'Tab') {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n setInputValue('/' + selectedCommand.keyword + ' ');\n }\n return;\n }\n }\n\n // Handle arrow keys for history (only when not in command mode)\n if (!showingCommands && !isProcessing) {\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateHistory('up');\n return;\n }\n if (e.key === 'ArrowDown' && historyIndex >= 0) {\n e.preventDefault();\n navigateHistory('down');\n return;\n }\n }\n\n // Handle Enter to submit\n if (e.key === 'Enter' && !e.shiftKey && !isProcessing) {\n e.preventDefault();\n submit();\n }\n },\n [\n isProcessing,\n result,\n showingCommands,\n showingHistory,\n filteredCommands,\n selectedCommandIndex,\n historyIndex,\n submit,\n reset,\n close,\n navigateCommands,\n navigateHistory,\n selectCommand,\n ]\n );\n\n return {\n isVisible,\n open,\n close,\n toggle,\n inputValue,\n setInputValue,\n inputRef,\n focus,\n isProcessing,\n toolCalls,\n currentToolSummary,\n result,\n chatUid,\n error,\n history,\n historyIndex,\n showingHistory,\n setShowingHistory,\n showingCommands,\n filteredCommands,\n selectedCommandIndex,\n selectCommand,\n submit,\n reset,\n handleKeyDown,\n clearHistory,\n };\n}\n"],"names":["useTranslations","useOptionalDevicContext","resolvePollingInterval","resolveStreaming","useState","useRef","useMemo","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;;AAuFA;;AAEG;AACH,SAAS,aAAa,CAAC,QAAgB,EAAA;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC;IAC/C,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE;IAC7B,MAAM,SAAS,GAAG,KAAK;AACvB,IAAA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE;AAC3B;AAEA;;AAEG;AACH,SAAS,aAAa,CAAC,KAAoB,EAAE,QAAgB,EAAA;IAC3D,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,aAAa,CAAC,QAAQ,CAAC;IAElD,MAAM,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,GAAG;AAChD,IAAA,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC;AAC/E,IAAA,MAAM,UAAU,GAAG,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,KAAK,CAAC,QAAQ;AACjE,IAAA,MAAM,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC,MAAM;AAE3D,IAAA,OAAO,QAAQ,IAAI,QAAQ,IAAI,UAAU,IAAI,QAAQ;AACvD;AAEA;;AAEG;AACG,SAAU,cAAc,CAAC,QAAgB,EAAA;AAC7C,IAAA,MAAM,KAAK,GAAG,OAAO,SAAS,KAAK,WAAW,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;AAChF,IAAA,OAAO;AACJ,SAAA,OAAO,CAAC,OAAO,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM;AAC1C,S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;IAED,OAAO;QACL,SAAS;QACT,IAAI;QACJ,KAAK;QACL,MAAM;QACN,UAAU;QACV,aAAa;QACb,QAAQ;QACR,KAAK;QACL,YAAY;QACZ,SAAS;QACT,kBAAkB;QAClB,MAAM;QACN,OAAO;QACP,KAAK;QACL,OAAO;QACP,YAAY;QACZ,cAAc;QACd,iBAAiB;QACjB,eAAe;QACf,gBAAgB;QAChB,oBAAoB;QACpB,aAAa;QACb,MAAM;QACN,KAAK;QACL,aAAa;QACb,YAAY;KACb;AACH;;;;;"}
1
+ {"version":3,"file":"useAICommandBar.js","sources":["../../../../../src/components/AICommandBar/useAICommandBar.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef, useMemo } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling, resolvePollingInterval, resolveStreaming } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport { useTranslations } from '../../i18n';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\nimport type {\n AICommandBarOptions,\n AICommandBarCommand,\n CommandBarResult,\n ToolCallSummary,\n ChatDrawerHandle,\n} from './AICommandBar.types';\n\nexport interface UseAICommandBarOptions {\n assistantId: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n /** Tags applied to the conversation (merged/deduped with the provider's). */\n tags?: string[];\n /** Poll cadence (ms) for the command in progress (overrides the provider's). */\n pollingInterval?: number;\n /** Follow it over a server-sent event stream instead of polling (overrides the provider's). */\n streaming?: boolean;\n options?: AICommandBarOptions;\n isVisible?: boolean;\n onVisibilityChange?: (visible: boolean) => void;\n onExecute?: 'openDrawer' | 'callback';\n chatDrawerRef?: React.RefObject<ChatDrawerHandle>;\n onResponse?: (response: CommandBarResult) => void;\n modelInterfaceTools?: ModelInterfaceTool[];\n onSubmit?: (message: string) => void;\n onToolCall?: (toolName: string, params: Record<string, any>) => void;\n onError?: (error: Error) => void;\n onOpen?: () => void;\n onClose?: () => void;\n}\n\nexport interface UseAICommandBarResult {\n // Visibility\n isVisible: boolean;\n open: () => void;\n close: () => void;\n toggle: () => void;\n\n // Input\n inputValue: string;\n setInputValue: (value: string) => void;\n inputRef: React.RefObject<HTMLInputElement>;\n focus: () => void;\n\n // Processing state\n isProcessing: boolean;\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Result\n result: CommandBarResult | null;\n chatUid: string | null;\n error: Error | null;\n\n // History\n history: string[];\n historyIndex: number;\n showingHistory: boolean;\n setShowingHistory: (show: boolean) => void;\n\n // Commands\n showingCommands: boolean;\n filteredCommands: AICommandBarCommand[];\n selectedCommandIndex: number;\n selectCommand: (command: AICommandBarCommand) => void;\n\n // Actions\n submit: (message?: string) => Promise<void>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n clearHistory: () => void;\n}\n\n/**\n * Parse a shortcut string like \"cmd+j\" into its components\n */\nfunction parseShortcut(shortcut: string): { key: string; modifiers: string[] } {\n const parts = shortcut.toLowerCase().split('+');\n const key = parts.pop() || '';\n const modifiers = parts;\n return { key, modifiers };\n}\n\n/**\n * Check if a keyboard event matches a shortcut string\n */\nfunction matchShortcut(event: KeyboardEvent, shortcut: string): boolean {\n const { key, modifiers } = parseShortcut(shortcut);\n\n const keyMatch = event.key.toLowerCase() === key;\n const cmdMatch = modifiers.includes('cmd') === (event.metaKey || event.ctrlKey);\n const shiftMatch = modifiers.includes('shift') === event.shiftKey;\n const altMatch = modifiers.includes('alt') === event.altKey;\n\n return keyMatch && cmdMatch && shiftMatch && altMatch;\n}\n\n/**\n * Format a shortcut string for display\n */\nexport function formatShortcut(shortcut: string): string {\n const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform);\n return shortcut\n .replace(/cmd/gi, isMac ? '\\u2318' : 'Ctrl')\n .replace(/shift/gi, '\\u21E7')\n .replace(/alt/gi, isMac ? '\\u2325' : 'Alt')\n .replace(/\\+/g, ' ')\n .replace(/([a-z])/gi, (match) => match.toUpperCase());\n}\n\n/**\n * Format tool name to human-readable (fallback when no summary)\n */\nfunction formatToolName(toolName: string): string {\n // Convert snake_case or camelCase to human-readable\n return toolName\n .replace(/_/g, ' ')\n .replace(/([A-Z])/g, ' $1')\n .trim()\n .toLowerCase()\n .replace(/^./, (c) => c.toUpperCase());\n}\n\n/**\n * Hook for managing AICommandBar state and behavior\n */\nexport function useAICommandBar(options: UseAICommandBarOptions): UseAICommandBarResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n tags,\n pollingInterval: propsPollingInterval,\n streaming: propsStreaming,\n options: barOptions = {},\n isVisible: controlledVisible,\n onVisibilityChange,\n onExecute = 'callback',\n chatDrawerRef,\n onResponse,\n modelInterfaceTools = [],\n onSubmit,\n onToolCall,\n onError,\n onOpen,\n onClose,\n } = options;\n\n const { shortcut } = barOptions;\n\n const t = useTranslations(barOptions.translations);\n\n // Get context\n const context = useOptionalDevicContext();\n const apiKey = propsApiKey || context?.apiKey;\n const getTenantSession = context?.getTenantSession;\n const onSessionExpired = context?.onSessionExpired;\n const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';\n const resolvedTenantId = tenantId || context?.tenantId;\n const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };\n const resolvedTags = Array.from(\n new Set([...(context?.tags ?? []), ...(tags ?? [])])\n );\n const pollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval\n );\n const streaming = resolveStreaming(propsStreaming, context?.streaming);\n\n // Visibility state\n const [internalVisible, setInternalVisible] = useState(false);\n const isVisible = controlledVisible ?? internalVisible;\n\n // Input state\n const [inputValue, setInputValue] = useState('');\n const inputRef = useRef<HTMLInputElement>(null);\n\n // Processing state\n const [isProcessing, setIsProcessing] = useState(false);\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Result state\n const [result, setResult] = useState<CommandBarResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n // Polling state\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // History state\n const enableHistory = barOptions.enableHistory !== false; // default true\n const maxHistoryItems = barOptions.maxHistoryItems ?? 50;\n const historyStorageKey = barOptions.historyStorageKey ?? 'devic-command-bar-history';\n const showHistoryCommand = barOptions.showHistoryCommand !== false; // default true\n\n const [history, setHistory] = useState<string[]>(() => {\n if (!enableHistory || typeof window === 'undefined') return [];\n try {\n const stored = localStorage.getItem(historyStorageKey);\n return stored ? JSON.parse(stored) : [];\n } catch {\n return [];\n }\n });\n const [historyIndex, setHistoryIndex] = useState(-1);\n const [showingHistory, setShowingHistory] = useState(false);\n const [tempInput, setTempInput] = useState(''); // Store current input when navigating history\n\n // Commands state\n const commands = barOptions.commands ?? [];\n const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);\n\n // Built-in history command\n const historyCommand: AICommandBarCommand = useMemo(() => ({\n keyword: 'history',\n description: t('Show command history'),\n message: '', // Special handling\n }), [t]);\n\n // All available commands (user commands + built-in)\n const allCommands = useMemo(() => {\n const userCommands = commands;\n // Add history command if enabled and not overwritten\n if (showHistoryCommand && !userCommands.some(c => c.keyword === 'history')) {\n return [...userCommands, historyCommand];\n }\n return userCommands;\n }, [commands, showHistoryCommand, historyCommand]);\n\n // Detect if showing command suggestions\n const isCommandMode = inputValue.startsWith('/');\n const commandQuery = isCommandMode ? inputValue.slice(1).toLowerCase() : '';\n const showingCommands = isCommandMode && !isProcessing && !result;\n\n // Filter commands based on query\n const filteredCommands = useMemo(() => {\n if (!showingCommands) return [];\n if (commandQuery === '') return allCommands;\n return allCommands.filter(cmd =>\n cmd.keyword.toLowerCase().includes(commandQuery) ||\n cmd.description.toLowerCase().includes(commandQuery)\n );\n }, [showingCommands, commandQuery, allCommands]);\n\n // Reset command selection when filtered list changes\n useEffect(() => {\n setSelectedCommandIndex(0);\n }, [filteredCommands.length]);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onToolCallRef = useRef(onToolCall);\n const onSubmitRef = useRef(onSubmit);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onToolCallRef.current = onToolCall;\n onSubmitRef.current = onSubmit;\n onOpenRef.current = onOpen;\n onCloseRef.current = onClose;\n });\n\n // API client\n const clientRef = useRef<DevicApiClient | null>(null);\n if (!clientRef.current && (apiKey || getTenantSession)) {\n clientRef.current = new DevicApiClient({ apiKey, baseUrl, getTenantSession, onSessionExpired });\n }\n\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n // Model interface\n const {\n toolSchemas,\n handleToolCalls: executeToolCalls,\n resolvePendingToolCalls,\n } = useModelInterface({\n tools: modelInterfaceTools,\n onToolExecute: onToolCall,\n });\n\n // Visibility controls\n const open = useCallback(() => {\n setInternalVisible(true);\n onVisibilityChange?.(true);\n onOpenRef.current?.();\n // Focus input after visibility change\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [onVisibilityChange]);\n\n const close = useCallback(() => {\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n }, [onVisibilityChange]);\n\n const toggle = useCallback(() => {\n if (isVisible) {\n close();\n } else {\n open();\n }\n }, [isVisible, open, close]);\n\n const focus = useCallback(() => {\n inputRef.current?.focus();\n }, []);\n\n // Save history to localStorage\n const saveHistory = useCallback((newHistory: string[]) => {\n if (!enableHistory || typeof window === 'undefined') return;\n try {\n localStorage.setItem(historyStorageKey, JSON.stringify(newHistory));\n } catch {\n // Ignore localStorage errors\n }\n }, [enableHistory, historyStorageKey]);\n\n // Add item to history\n const addToHistory = useCallback((message: string) => {\n if (!enableHistory || !message.trim() || message.startsWith('/')) return;\n\n setHistory(prev => {\n // Don't add duplicates at the top\n const filtered = prev.filter(item => item !== message);\n const newHistory = [message, ...filtered].slice(0, maxHistoryItems);\n saveHistory(newHistory);\n return newHistory;\n });\n setHistoryIndex(-1);\n }, [enableHistory, maxHistoryItems, saveHistory]);\n\n // Clear history\n const clearHistory = useCallback(() => {\n setHistory([]);\n setHistoryIndex(-1);\n if (enableHistory && typeof window !== 'undefined') {\n try {\n localStorage.removeItem(historyStorageKey);\n } catch {\n // Ignore\n }\n }\n }, [enableHistory, historyStorageKey]);\n\n // Navigate history\n const navigateHistory = useCallback((direction: 'up' | 'down') => {\n if (!enableHistory || history.length === 0) return;\n\n if (direction === 'up') {\n if (historyIndex === -1) {\n // Save current input before navigating\n setTempInput(inputValue);\n setHistoryIndex(0);\n setInputValue(history[0]);\n } else if (historyIndex < history.length - 1) {\n const newIndex = historyIndex + 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n }\n } else {\n if (historyIndex > 0) {\n const newIndex = historyIndex - 1;\n setHistoryIndex(newIndex);\n setInputValue(history[newIndex]);\n } else if (historyIndex === 0) {\n setHistoryIndex(-1);\n setInputValue(tempInput);\n }\n }\n }, [enableHistory, history, historyIndex, inputValue, tempInput]);\n\n // Ref to hold submit function (to avoid circular dependency)\n const submitRef = useRef<(message?: string) => Promise<void>>();\n\n // Select a command\n const selectCommand = useCallback((command: AICommandBarCommand) => {\n if (command.keyword === 'history') {\n // Special handling for history command\n setShowingHistory(true);\n setInputValue('');\n } else {\n // Send the command's message\n setInputValue('');\n submitRef.current?.(command.message);\n }\n }, []);\n\n // Navigate commands\n const navigateCommands = useCallback((direction: 'up' | 'down') => {\n if (filteredCommands.length === 0) return;\n\n if (direction === 'down') {\n setSelectedCommandIndex(prev =>\n prev < filteredCommands.length - 1 ? prev + 1 : 0\n );\n } else {\n setSelectedCommandIndex(prev =>\n prev > 0 ? prev - 1 : filteredCommands.length - 1\n );\n }\n }, [filteredCommands.length]);\n\n // Register keyboard shortcut\n useEffect(() => {\n if (!shortcut) return;\n\n const handler = (e: KeyboardEvent) => {\n if (matchShortcut(e, shortcut)) {\n e.preventDefault();\n toggle();\n }\n };\n\n window.addEventListener('keydown', handler);\n return () => window.removeEventListener('keydown', handler);\n }, [shortcut, toggle]);\n\n // Process tool calls from realtime data\n const processToolCalls = useCallback((messages: ChatMessage[]): ToolCallSummary[] => {\n const summaries: ToolCallSummary[] = [];\n const toolResponseMap = new Map<string, any>();\n\n // Collect tool responses\n for (const msg of messages) {\n if (msg.role === 'tool' && msg.tool_call_id) {\n toolResponseMap.set(msg.tool_call_id, msg.content);\n }\n }\n\n // Collect tool calls from assistant messages\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.tool_calls?.length) {\n for (const tc of msg.tool_calls) {\n const hasResponse = toolResponseMap.has(tc.id);\n let input: any;\n try {\n input = JSON.parse(tc.function.arguments || '{}');\n } catch {\n input = {};\n }\n\n // Use message summary if available, otherwise format tool name\n const summaryText = msg.summary || formatToolName(tc.function.name);\n\n summaries.push({\n id: tc.id,\n name: tc.function.name,\n status: hasResponse ? 'completed' : 'executing',\n summary: summaryText,\n input,\n output: toolResponseMap.get(tc.id),\n });\n }\n }\n }\n\n return summaries;\n }, []);\n\n // Handle pending client-side tool calls\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid) return;\n\n const pendingCalls = resolvePendingToolCalls(data);\n if (pendingCalls.length === 0) return;\n\n try {\n const { responses, toolSchemas: schemas } =\n await executeToolCalls(pendingCalls);\n if (responses.length > 0) {\n await clientRef.current.sendToolResponses(\n assistantId,\n chatUid,\n responses,\n schemas\n );\n setShouldPoll(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [chatUid, assistantId, executeToolCalls, resolvePendingToolCalls]\n );\n\n // Polling\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid) {\n throw new Error(t('Cannot poll without client or chatUid'));\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\n streamFn: streaming\n ? (onSnapshot, signal, onActivity) => clientRef.current!.streamRealtimeHistory(assistantId!, chatUid!, onSnapshot, signal, onActivity)\n : undefined,\n enabled: shouldPoll,\n stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],\n onUpdate: async (data: RealtimeChatHistory) => {\n // Update tool calls display\n const summaries = processToolCalls(data.chatHistory);\n setToolCalls(summaries);\n\n // Update current tool summary\n // Prefer showing an executing tool, but fall back to the last tool (completed or not)\n if (summaries.length > 0) {\n const lastExecuting = summaries.filter(s => s.status === 'executing').pop();\n const lastTool = summaries[summaries.length - 1];\n setCurrentToolSummary(lastExecuting?.summary || lastTool?.summary || null);\n }\n\n // Handle client-side tool calls\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n setShouldPoll(false);\n\n if (data?.status === 'error') {\n setIsProcessing(false);\n const err = new Error(t('Processing failed'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n if (data?.status === 'completed') {\n setIsProcessing(false);\n\n // Extract final assistant message\n const assistantMessages = data.chatHistory.filter(m => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const commandResult: CommandBarResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: processToolCalls(data.chatHistory),\n };\n\n setResult(commandResult);\n\n // Handle execution mode\n if (onExecute === 'openDrawer' && chatDrawerRef?.current) {\n chatDrawerRef.current.setChatUid(chatUid);\n chatDrawerRef.current.open();\n // Close and reset the command bar when handing off to drawer\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setInternalVisible(false);\n onVisibilityChange?.(false);\n onCloseRef.current?.();\n } else {\n onResponseRef.current?.(commandResult);\n }\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n }\n );\n\n // Submit message\n const submit = useCallback(\n async (message?: string) => {\n const msg = message ?? inputValue;\n if (!msg.trim()) return;\n\n if (!clientRef.current) {\n const err = new Error(\n t('API client not configured. Please provide an API key.')\n );\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n // Add to history before processing\n addToHistory(msg);\n\n // Clear input and start processing\n setInputValue('');\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setShowingHistory(false);\n setHistoryIndex(-1);\n\n onSubmitRef.current?.(msg);\n\n try {\n const dto = {\n message: msg,\n chatUid: chatUid || undefined,\n metadata: resolvedTenantMetadata,\n tenantId: resolvedTenantId,\n ...(resolvedTags.length > 0 && { tags: resolvedTags }),\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n };\n\n const response = await clientRef.current.sendMessageAsync(assistantId, dto);\n\n if (response.chatUid && response.chatUid !== chatUid) {\n setChatUid(response.chatUid);\n }\n\n setShouldPoll(true);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n setIsProcessing(false);\n onErrorRef.current?.(error);\n }\n },\n [inputValue, chatUid, assistantId, resolvedTenantId, resolvedTenantMetadata, resolvedTags, toolSchemas, addToHistory]\n );\n\n // Update submit ref for use in selectCommand\n submitRef.current = submit;\n\n // Reset state\n const reset = useCallback(() => {\n setInputValue('');\n setIsProcessing(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\n setResult(null);\n setChatUid(null);\n setError(null);\n setShouldPoll(false);\n }, []);\n\n // Handle keyboard events\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n // Handle Escape\n if (e.key === 'Escape') {\n e.preventDefault();\n if (showingHistory) {\n setShowingHistory(false);\n return;\n }\n if (showingCommands) {\n setInputValue('');\n return;\n }\n // Reset if there's a result or if processing\n if (result || isProcessing) {\n reset();\n }\n close();\n return;\n }\n\n // Handle arrow keys for commands\n if (showingCommands && filteredCommands.length > 0) {\n if (e.key === 'ArrowDown') {\n e.preventDefault();\n navigateCommands('down');\n return;\n }\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateCommands('up');\n return;\n }\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n selectCommand(selectedCommand);\n }\n return;\n }\n if (e.key === 'Tab') {\n e.preventDefault();\n const selectedCommand = filteredCommands[selectedCommandIndex];\n if (selectedCommand) {\n setInputValue('/' + selectedCommand.keyword + ' ');\n }\n return;\n }\n }\n\n // Handle arrow keys for history (only when not in command mode)\n if (!showingCommands && !isProcessing) {\n if (e.key === 'ArrowUp') {\n e.preventDefault();\n navigateHistory('up');\n return;\n }\n if (e.key === 'ArrowDown' && historyIndex >= 0) {\n e.preventDefault();\n navigateHistory('down');\n return;\n }\n }\n\n // Handle Enter to submit\n if (e.key === 'Enter' && !e.shiftKey && !isProcessing) {\n e.preventDefault();\n submit();\n }\n },\n [\n isProcessing,\n result,\n showingCommands,\n showingHistory,\n filteredCommands,\n selectedCommandIndex,\n historyIndex,\n submit,\n reset,\n close,\n navigateCommands,\n navigateHistory,\n selectCommand,\n ]\n );\n\n return {\n isVisible,\n open,\n close,\n toggle,\n inputValue,\n setInputValue,\n inputRef,\n focus,\n isProcessing,\n toolCalls,\n currentToolSummary,\n result,\n chatUid,\n error,\n history,\n historyIndex,\n showingHistory,\n setShowingHistory,\n showingCommands,\n filteredCommands,\n selectedCommandIndex,\n selectCommand,\n submit,\n reset,\n handleKeyDown,\n clearHistory,\n };\n}\n"],"names":["useTranslations","useOptionalDevicContext","resolvePollingInterval","resolveStreaming","useState","useRef","useMemo","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;;AAuFA;;AAEG;AACH,SAAS,aAAa,CAAC,QAAgB,EAAA;IACrC,MAAM,KAAK,GAAG,QAA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QACjB,eAAe;QACf,gBAAgB;QAChB,oBAAoB;QACpB,aAAa;QACb,MAAM;QACN,KAAK;QACL,aAAa;QACb,YAAY;KACb;AACH;;;;;"}
@@ -45,17 +45,17 @@ function useAIElementWrapper(options) {
45
45
  clientRef.current.setConfig({ apiKey, baseUrl });
46
46
  }
47
47
  }, [apiKey, baseUrl]);
48
- const { toolSchemas, handleToolCalls: executeToolCalls, extractPendingToolCalls, } = useModelInterface.useModelInterface({ tools: modelInterfaceTools });
48
+ const { toolSchemas, handleToolCalls: executeToolCalls, resolvePendingToolCalls, } = useModelInterface.useModelInterface({ tools: modelInterfaceTools });
49
49
  const handlePendingToolCalls = React.useCallback(async (data) => {
50
50
  if (!clientRef.current || !chatUid || !assistantId)
51
51
  return;
52
- const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);
52
+ const pendingCalls = resolvePendingToolCalls(data);
53
53
  if (pendingCalls.length === 0)
54
54
  return;
55
55
  try {
56
- const { responses } = await executeToolCalls(pendingCalls);
56
+ const { responses, toolSchemas: schemas } = await executeToolCalls(pendingCalls);
57
57
  if (responses.length > 0) {
58
- await clientRef.current.sendToolResponses(assistantId, chatUid, responses, toolSchemas);
58
+ await clientRef.current.sendToolResponses(assistantId, chatUid, responses, schemas);
59
59
  setShouldPoll(true);
60
60
  }
61
61
  }
@@ -64,7 +64,7 @@ function useAIElementWrapper(options) {
64
64
  setError(error);
65
65
  onErrorRef.current?.(error);
66
66
  }
67
- }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]);
67
+ }, [chatUid, assistantId, executeToolCalls, resolvePendingToolCalls]);
68
68
  usePolling.usePolling(shouldPoll ? chatUid : null, async () => {
69
69
  if (!clientRef.current || !chatUid || !assistantId) {
70
70
  throw new Error(t('Cannot poll without client, chatUid or assistantId'));
@@ -1 +1 @@
1
- {"version":3,"file":"useAIElementWrapper.js","sources":["../../../../../src/components/AIElementWrapper/useAIElementWrapper.ts"],"sourcesContent":["import { useState, useCallback, useRef, useEffect } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling, resolvePollingInterval, resolveStreaming } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport { useTranslations } from '../../i18n';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\n\nexport interface UseAIElementWrapperOptions {\n assistantId?: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n /** Poll cadence (ms) for the generation in progress (overrides the provider's). */\n pollingInterval?: number;\n /** Follow it over a server-sent event stream instead of polling (overrides the provider's). */\n streaming?: boolean;\n modelInterfaceTools?: ModelInterfaceTool[];\n onResponse?: (message: ChatMessage) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface UseAIElementWrapperResult {\n isProcessing: boolean;\n response: ChatMessage | null;\n error: Error | null;\n /** Send a prompt to the inline assistant. */\n sendInlinePrompt: (prompt: string) => Promise<void>;\n /** Reset response/error state. */\n reset: () => void;\n}\n\n/**\n * Hook that manages the inline AI generation flow for AIElementWrapper.\n * Reuses sendMessageAsync + polling, similar to useAIGenerationButton but\n * without the modal/tooltip UI orchestration.\n */\nexport function useAIElementWrapper(\n options: UseAIElementWrapperOptions\n): UseAIElementWrapperResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n pollingInterval: propsPollingInterval,\n streaming: propsStreaming,\n modelInterfaceTools = [],\n onResponse,\n onError,\n } = options;\n\n const t = useTranslations();\n const context = useOptionalDevicContext();\n const apiKey = propsApiKey || context?.apiKey;\n const getTenantSession = context?.getTenantSession;\n const onSessionExpired = context?.onSessionExpired;\n const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';\n const resolvedTenantId = tenantId || context?.tenantId;\n const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };\n const pollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval\n );\n const streaming = resolveStreaming(propsStreaming, context?.streaming);\n\n const [isProcessing, setIsProcessing] = useState(false);\n const [response, setResponse] = useState<ChatMessage | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [shouldPoll, setShouldPoll] = useState(false);\n\n const onResponseRef = useRef(onResponse);\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onResponseRef.current = onResponse;\n onErrorRef.current = onError;\n });\n\n const clientRef = useRef<DevicApiClient | null>(null);\n if (!clientRef.current && (apiKey || getTenantSession)) {\n clientRef.current = new DevicApiClient({ apiKey, baseUrl, getTenantSession, onSessionExpired });\n }\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n const {\n toolSchemas,\n handleToolCalls: executeToolCalls,\n extractPendingToolCalls,\n } = useModelInterface({ tools: modelInterfaceTools });\n\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid || !assistantId) return;\n const pendingCalls =\n data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);\n if (pendingCalls.length === 0) return;\n try {\n const { responses } = await executeToolCalls(pendingCalls);\n if (responses.length > 0) {\n await clientRef.current.sendToolResponses(\n assistantId,\n chatUid,\n responses,\n toolSchemas\n );\n setShouldPoll(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]\n );\n\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid || !assistantId) {\n throw new Error(t('Cannot poll without client, chatUid or assistantId'));\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\n streamFn: streaming\n ? (onSnapshot, signal, onActivity) => clientRef.current!.streamRealtimeHistory(assistantId!, chatUid!, onSnapshot, signal, onActivity)\n : undefined,\n enabled: shouldPoll,\n stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],\n onUpdate: async (data: RealtimeChatHistory) => {\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n setShouldPoll(false);\n if (data?.status === 'error') {\n setIsProcessing(false);\n const err = new Error(t('Processing failed'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n if (data?.status === 'completed') {\n setIsProcessing(false);\n const assistantMessages = data.chatHistory.filter(\n (m: ChatMessage) => m.role === 'assistant'\n );\n const last = assistantMessages[assistantMessages.length - 1];\n if (last) {\n setResponse(last);\n onResponseRef.current?.(last);\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n }\n );\n\n const sendInlinePrompt = useCallback(\n async (prompt: string) => {\n if (!assistantId) {\n const err = new Error(t('assistantId is required for inline behavior'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n if (!clientRef.current) {\n const err = new Error(\n t('API client not configured. Please provide an API key.')\n );\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n const trimmed = prompt.trim();\n if (!trimmed) {\n const err = new Error(t('Prompt is empty'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n setIsProcessing(true);\n setError(null);\n setResponse(null);\n\n try {\n const dto = {\n message: trimmed,\n metadata: resolvedTenantMetadata,\n tenantId: resolvedTenantId,\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n };\n const resp = await clientRef.current.sendMessageAsync(assistantId, dto);\n if (resp.chatUid) setChatUid(resp.chatUid);\n setShouldPoll(true);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n setIsProcessing(false);\n onErrorRef.current?.(error);\n }\n },\n [assistantId, resolvedTenantId, resolvedTenantMetadata, toolSchemas]\n );\n\n const reset = useCallback(() => {\n setIsProcessing(false);\n setResponse(null);\n setError(null);\n setChatUid(null);\n setShouldPoll(false);\n }, []);\n\n return {\n isProcessing,\n response,\n error,\n sendInlinePrompt,\n reset,\n };\n}\n"],"names":["useTranslations","useOptionalDevicContext","resolvePollingInterval","resolveStreaming","useState","useRef","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;;AAqCA;;;;AAIG;AACG,SAAU,mBAAmB,CACjC,OAAmC,EAAA;AAEnC,IAAA,MAAM,EACJ,WAAW,EACX,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,eAAe,EAAE,oBAAoB,EACrC,SAAS,EAAE,cAAc,EACzB,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,OAAO,GACR,GAAG,OAAO;AAEX,IAAA,MAAM,CAAC,GAAGA,+BAAe,EAAE;AAC3B,IAAA,MAAM,OAAO,GAAGC,oCAAuB,EAAE;AACzC,IAAA,MAAM,MAAM,GAAG,WAAW,IAAI,OAAO,EAAE,MAAM;AAC7C,IAAA,MAAM,gBAAgB,GAAG,OAAO,EAAE,gBAAgB;AAClD,IAAA,MAAM,gBAAgB,GAAG,OAAO,EAAE,gBAAgB;IAClD,MAAM,OAAO,GAAG,YAAY,IAAI,OAAO,EAAE,OAAO,IAAI,sBAAsB;AAC1E,IAAA,MAAM,gBAAgB,GAAG,QAAQ,IAAI,OAAO,EAAE,QAAQ;IACtD,MAAM,sBAAsB,GAAG,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,GAAG,cAAc,EAAE;IAChF,MAAM,eAAe,GAAGC,iCAAsB,CAC5C,oBAAoB,EACpB,OAAO,EAAE,eAAe,CACzB;IACD,MAAM,SAAS,GAAGC,2BAAgB,CAAC,cAAc,EAAE,OAAO,EAAE,SAAS,CAAC;IAEtE,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAGC,cAAQ,CAAC,KAAK,CAAC;IACvD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,CAAC,gBAAgB,CAAC,WAAW,EAAE,GAAG,CAAC;YACvE,IAAI,IAAI,CAAC,OAAO;AAAE,gBAAA,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC;YAC1C,aAAa,CAAC,IAAI,CAAC;QACrB;QAAE,OAAO,GAAG,EAAE;YACZ,MAAM,KAAK,GAAG,GAAG,YAAY,KAAK,GAAG,GAAG,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACjE,QAAQ,CAAC,KAAK,CAAC;YACf,eAAe,CAAC,KAAK,CAAC;AACtB,YAAA,UAAU,CAAC,OAAO,GAAG,KAAK,CAAC;QAC7B;IACF,CAAC,EACD,CAAC,WAAW,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,WAAW,CAAC,CACrE;AAED,IAAA,MAAM,KAAK,GAAGA,iBAAW,CAAC,MAAK;QAC7B,eAAe,CAAC,KAAK,CAAC;QACtB,WAAW,CAAC,IAAI,CAAC;QACjB,QAAQ,CAAC,IAAI,CAAC;QACd,UAAU,CAAC,IAAI,CAAC;QAChB,aAAa,CAAC,KAAK,CAAC;IACtB,CAAC,EAAE,EAAE,CAAC;IAEN,OAAO;QACL,YAAY;QACZ,QAAQ;QACR,KAAK;QACL,gBAAgB;QAChB,KAAK;KACN;AACH;;;;"}
1
+ {"version":3,"file":"useAIElementWrapper.js","sources":["../../../../../src/components/AIElementWrapper/useAIElementWrapper.ts"],"sourcesContent":["import { useState, useCallback, useRef, useEffect } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling, resolvePollingInterval, resolveStreaming } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport { useTranslations } from '../../i18n';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\n\nexport interface UseAIElementWrapperOptions {\n assistantId?: string;\n apiKey?: string;\n baseUrl?: string;\n tenantId?: string;\n tenantMetadata?: Record<string, any>;\n /** Poll cadence (ms) for the generation in progress (overrides the provider's). */\n pollingInterval?: number;\n /** Follow it over a server-sent event stream instead of polling (overrides the provider's). */\n streaming?: boolean;\n modelInterfaceTools?: ModelInterfaceTool[];\n onResponse?: (message: ChatMessage) => void;\n onError?: (error: Error) => void;\n}\n\nexport interface UseAIElementWrapperResult {\n isProcessing: boolean;\n response: ChatMessage | null;\n error: Error | null;\n /** Send a prompt to the inline assistant. */\n sendInlinePrompt: (prompt: string) => Promise<void>;\n /** Reset response/error state. */\n reset: () => void;\n}\n\n/**\n * Hook that manages the inline AI generation flow for AIElementWrapper.\n * Reuses sendMessageAsync + polling, similar to useAIGenerationButton but\n * without the modal/tooltip UI orchestration.\n */\nexport function useAIElementWrapper(\n options: UseAIElementWrapperOptions\n): UseAIElementWrapperResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n pollingInterval: propsPollingInterval,\n streaming: propsStreaming,\n modelInterfaceTools = [],\n onResponse,\n onError,\n } = options;\n\n const t = useTranslations();\n const context = useOptionalDevicContext();\n const apiKey = propsApiKey || context?.apiKey;\n const getTenantSession = context?.getTenantSession;\n const onSessionExpired = context?.onSessionExpired;\n const baseUrl = propsBaseUrl || context?.baseUrl || 'https://api.devic.ai';\n const resolvedTenantId = tenantId || context?.tenantId;\n const resolvedTenantMetadata = { ...context?.tenantMetadata, ...tenantMetadata };\n const pollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval\n );\n const streaming = resolveStreaming(propsStreaming, context?.streaming);\n\n const [isProcessing, setIsProcessing] = useState(false);\n const [response, setResponse] = useState<ChatMessage | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [shouldPoll, setShouldPoll] = useState(false);\n\n const onResponseRef = useRef(onResponse);\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onResponseRef.current = onResponse;\n onErrorRef.current = onError;\n });\n\n const clientRef = useRef<DevicApiClient | null>(null);\n if (!clientRef.current && (apiKey || getTenantSession)) {\n clientRef.current = new DevicApiClient({ apiKey, baseUrl, getTenantSession, onSessionExpired });\n }\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n const {\n toolSchemas,\n handleToolCalls: executeToolCalls,\n resolvePendingToolCalls,\n } = useModelInterface({ tools: modelInterfaceTools });\n\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid || !assistantId) return;\n const pendingCalls =\n resolvePendingToolCalls(data);\n if (pendingCalls.length === 0) return;\n try {\n const { responses, toolSchemas: schemas } =\n await executeToolCalls(pendingCalls);\n if (responses.length > 0) {\n await clientRef.current.sendToolResponses(\n assistantId,\n chatUid,\n responses,\n schemas\n );\n setShouldPoll(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [chatUid, assistantId, executeToolCalls, resolvePendingToolCalls]\n );\n\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid || !assistantId) {\n throw new Error(t('Cannot poll without client, chatUid or assistantId'));\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\n streamFn: streaming\n ? (onSnapshot, signal, onActivity) => clientRef.current!.streamRealtimeHistory(assistantId!, chatUid!, onSnapshot, signal, onActivity)\n : undefined,\n enabled: shouldPoll,\n stopStatuses: ['completed', 'error', 'waiting_for_tool_response'],\n onUpdate: async (data: RealtimeChatHistory) => {\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n setShouldPoll(false);\n if (data?.status === 'error') {\n setIsProcessing(false);\n const err = new Error(t('Processing failed'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n if (data?.status === 'completed') {\n setIsProcessing(false);\n const assistantMessages = data.chatHistory.filter(\n (m: ChatMessage) => m.role === 'assistant'\n );\n const last = assistantMessages[assistantMessages.length - 1];\n if (last) {\n setResponse(last);\n onResponseRef.current?.(last);\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n }\n );\n\n const sendInlinePrompt = useCallback(\n async (prompt: string) => {\n if (!assistantId) {\n const err = new Error(t('assistantId is required for inline behavior'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n if (!clientRef.current) {\n const err = new Error(\n t('API client not configured. Please provide an API key.')\n );\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n const trimmed = prompt.trim();\n if (!trimmed) {\n const err = new Error(t('Prompt is empty'));\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n setIsProcessing(true);\n setError(null);\n setResponse(null);\n\n try {\n const dto = {\n message: trimmed,\n metadata: resolvedTenantMetadata,\n tenantId: resolvedTenantId,\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n };\n const resp = await clientRef.current.sendMessageAsync(assistantId, dto);\n if (resp.chatUid) setChatUid(resp.chatUid);\n setShouldPoll(true);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n setIsProcessing(false);\n onErrorRef.current?.(error);\n }\n },\n [assistantId, resolvedTenantId, resolvedTenantMetadata, toolSchemas]\n );\n\n const reset = useCallback(() => {\n setIsProcessing(false);\n setResponse(null);\n setError(null);\n setChatUid(null);\n setShouldPoll(false);\n }, []);\n\n return {\n isProcessing,\n response,\n error,\n sendInlinePrompt,\n reset,\n };\n}\n"],"names":["useTranslations","useOptionalDevicContext","resolvePollingInterval","resolveStreaming","useState","useRef","useEffect","DevicApiClient","useModelInterface","useCallback","usePolling"],"mappings":";;;;;;;;;;AAqCA;;;;AAIG;AACG,SAAU,mBAAmB,CACjC,OAAmC,EAAA;AAEnC,IAAA,MAAM,EACJ,WAAW,EACX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AU,CAAC,OAAO,GAAG,KAAK,CAAC;QAC7B;IACF,CAAC,EACD,CAAC,WAAW,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,WAAW,CAAC,CACrE;AAED,IAAA,MAAM,KAAK,GAAGA,iBAAW,CAAC,MAAK;QAC7B,eAAe,CAAC,KAAK,CAAC;QACtB,WAAW,CAAC,IAAI,CAAC;QACjB,QAAQ,CAAC,IAAI,CAAC;QACd,UAAU,CAAC,IAAI,CAAC;QAChB,aAAa,CAAC,KAAK,CAAC;IACtB,CAAC,EAAE,EAAE,CAAC;IAEN,OAAO;QACL,YAAY;QACZ,QAAQ;QACR,KAAK;QACL,gBAAgB;QAChB,KAAK;KACN;AACH;;;;"}
@@ -66,7 +66,7 @@ function useAIGenerationButton(options) {
66
66
  }
67
67
  }, [apiKey, baseUrl]);
68
68
  // Model interface
69
- const { toolSchemas, handleToolCalls: executeToolCalls, extractPendingToolCalls, } = useModelInterface.useModelInterface({
69
+ const { toolSchemas, handleToolCalls: executeToolCalls, resolvePendingToolCalls, } = useModelInterface.useModelInterface({
70
70
  tools: modelInterfaceTools,
71
71
  });
72
72
  /**
@@ -123,13 +123,13 @@ function useAIGenerationButton(options) {
123
123
  const handlePendingToolCalls = React.useCallback(async (data) => {
124
124
  if (!clientRef.current || !chatUid)
125
125
  return;
126
- const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);
126
+ const pendingCalls = resolvePendingToolCalls(data);
127
127
  if (pendingCalls.length === 0)
128
128
  return;
129
129
  try {
130
- const { responses } = await executeToolCalls(pendingCalls);
130
+ const { responses, toolSchemas: schemas } = await executeToolCalls(pendingCalls);
131
131
  if (responses.length > 0) {
132
- await clientRef.current.sendToolResponses(assistantId, chatUid, responses, toolSchemas);
132
+ await clientRef.current.sendToolResponses(assistantId, chatUid, responses, schemas);
133
133
  setShouldPoll(true);
134
134
  }
135
135
  }
@@ -138,7 +138,7 @@ function useAIGenerationButton(options) {
138
138
  setError(error);
139
139
  onErrorRef.current?.(error);
140
140
  }
141
- }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]);
141
+ }, [chatUid, assistantId, executeToolCalls, resolvePendingToolCalls]);
142
142
  // Polling
143
143
  usePolling.usePolling(shouldPoll ? chatUid : null, async () => {
144
144
  if (!clientRef.current || !chatUid) {