@devicai/ui 0.47.0 → 0.47.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../../src/api/types.ts"],"sourcesContent":["import 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 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';\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\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\n/**\n * DTO for sending messages to the assistant\n */\nexport interface ProcessMessageDto {\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 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\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\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 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\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 */\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}\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 identifier: string;\n name: string;\n description: string;\n state: 'active' | 'inactive' | 'coming_soon';\n imgUrl?: string;\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 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\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 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"],"names":[],"mappings":"AAoCA;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;AA+iBA;;AAEG;IACS;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,EAbW,gBAAgB,KAAhB,gBAAgB,GAAA,EAAA,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"types.js","sources":["../../../src/api/types.ts"],"sourcesContent":["import 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 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';\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\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 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 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\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\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 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\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 */\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}\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 identifier: string;\n name: string;\n description: string;\n state: 'active' | 'inactive' | 'coming_soon';\n imgUrl?: string;\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 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\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 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"],"names":[],"mappings":"AAoCA;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;AAqjBA;;AAEG;IACS;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,EAbW,gBAAgB,KAAhB,gBAAgB,GAAA,EAAA,CAAA,CAAA;;;;"}
@@ -341,7 +341,7 @@ function useAICommandBar(options) {
341
341
  try {
342
342
  const { responses } = await executeToolCalls(pendingCalls);
343
343
  if (responses.length > 0) {
344
- await clientRef.current.sendToolResponses(assistantId, chatUid, responses);
344
+ await clientRef.current.sendToolResponses(assistantId, chatUid, responses, toolSchemas);
345
345
  setShouldPoll(true);
346
346
  }
347
347
  }
@@ -350,7 +350,7 @@ function useAICommandBar(options) {
350
350
  setError(error);
351
351
  onErrorRef.current?.(error);
352
352
  }
353
- }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls]);
353
+ }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]);
354
354
  // Polling
355
355
  usePolling(shouldPoll ? chatUid : null, async () => {
356
356
  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 } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\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 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 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 // 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\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: 'Show command history',\n message: '', // Special handling\n }), []);\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(assistantId, chatUid, responses);\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]\n );\n\n // Polling\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid) {\n throw new Error('Cannot poll without client or chatUid');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\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('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('API client not configured. Please provide an API key.');\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":[],"mappings":";;;;;;;AAoFA;;AAEG;AACH,SAAS,aAAa,CAA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c,EAAE;gBAClB,eAAe,CAAC,IAAI,CAAC;gBACrB;YACF;YACA,IAAI,CAAC,CAAC,GAAG,KAAK,WAAW,IAAI,YAAY,IAAI,CAAC,EAAE;gBAC9C,CAAC,CAAC,cAAc,EAAE;gBAClB,eAAe,CAAC,MAAM,CAAC;gBACvB;YACF;QACF;;AAGA,QAAA,IAAI,CAAC,CAAC,GAAG,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,YAAY,EAAE;YACrD,CAAC,CAAC,cAAc,EAAE;AAClB,YAAA,MAAM,EAAE;QACV;AACF,IAAA,CAAC,EACD;QACE,YAAY;QACZ,MAAM;QACN,eAAe;QACf,cAAc;QACd,gBAAgB;QAChB,oBAAoB;QACpB,YAAY;QACZ,MAAM;QACN,KAAK;QACL,KAAK;QACL,gBAAgB;QAChB,eAAe;QACf,aAAa;AACd,KAAA,CACF;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 } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\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 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 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 // 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\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: 'Show command history',\n message: '', // Special handling\n }), []);\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('Cannot poll without client or chatUid');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\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('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('API client not configured. Please provide an API key.');\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 setShowingHist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GAAG,GAAG,CAAC;gBACpD;gBACA;YACF;QACF;;AAGA,QAAA,IAAI,CAAC,eAAe,IAAI,CAAC,YAAY,EAAE;AACrC,YAAA,IAAI,CAAC,CAAC,GAAG,KAAK,SAAS,EAAE;gBACvB,CAAC,CAAC,cAAc,EAAE;gBAClB,eAAe,CAAC,IAAI,CAAC;gBACrB;YACF;YACA,IAAI,CAAC,CAAC,GAAG,KAAK,WAAW,IAAI,YAAY,IAAI,CAAC,EAAE;gBAC9C,CAAC,CAAC,cAAc,EAAE;gBAClB,eAAe,CAAC,MAAM,CAAC;gBACvB;YACF;QACF;;AAGA,QAAA,IAAI,CAAC,CAAC,GAAG,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,YAAY,EAAE;YACrD,CAAC,CAAC,cAAc,EAAE;AAClB,YAAA,MAAM,EAAE;QACV;AACF,IAAA,CAAC,EACD;QACE,YAAY;QACZ,MAAM;QACN,eAAe;QACf,cAAc;QACd,gBAAgB;QAChB,oBAAoB;QACpB,YAAY;QACZ,MAAM;QACN,KAAK;QACL,KAAK;QACL,gBAAgB;QAChB,eAAe;QACf,aAAa;AACd,KAAA,CACF;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;;;;"}
@@ -50,7 +50,7 @@ function useAIElementWrapper(options) {
50
50
  try {
51
51
  const { responses } = await executeToolCalls(pendingCalls);
52
52
  if (responses.length > 0) {
53
- await clientRef.current.sendToolResponses(assistantId, chatUid, responses);
53
+ await clientRef.current.sendToolResponses(assistantId, chatUid, responses, toolSchemas);
54
54
  setShouldPoll(true);
55
55
  }
56
56
  }
@@ -59,7 +59,7 @@ function useAIElementWrapper(options) {
59
59
  setError(error);
60
60
  onErrorRef.current?.(error);
61
61
  }
62
- }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls]);
62
+ }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]);
63
63
  usePolling(shouldPoll ? chatUid : null, async () => {
64
64
  if (!clientRef.current || !chatUid || !assistantId) {
65
65
  throw new Error('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 } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\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 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 modelInterfaceTools = [],\n onResponse,\n onError,\n } = options;\n\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\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(assistantId, chatUid, responses);\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]\n );\n\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid || !assistantId) {\n throw new Error('Cannot poll without client, chatUid or assistantId');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\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('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('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('API client not configured. Please provide an API key.');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n const trimmed = prompt.trim();\n if (!trimmed) {\n const err = new Error('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":[],"mappings":";;;;;;;AAkCA;;;;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,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,OAAO,GACR,GAAG,OAAO;AAEX,IAAA,MAAM,OAAO,GAAG,uBAAuB,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,GAAG,sBAAsB,CAC5C,oBAAoB,EACpB,OAAO,EAAE,eAAe,CACzB;IAED,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC;IACvD,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,GAAG,QAAQ,CAAqB,IAAI,CAAC;IAClE,MAAM,CAAC,KAA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GAAG,KAAK,CAAC;QAC7B;IACF,CAAC,EACD,CAAC,WAAW,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,WAAW,CAAC,CACrE;AAED,IAAA,MAAM,KAAK,GAAG,WAAW,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 } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\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 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 modelInterfaceTools = [],\n onResponse,\n onError,\n } = options;\n\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\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('Cannot poll without client, chatUid or assistantId');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\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('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('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('API client not configured. Please provide an API key.');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n const trimmed = prompt.trim();\n if (!trimmed) {\n const err = new Error('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":[],"mappings":";;;;;;;AAkCA;;;;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,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,OAAO,GACR,GAAG,OAAO;AAEX,IAAA,MAAM,OAAO,GAAG,uBAAuB,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,GAAG,sBAAsB,CAC5C,oBAAoB,EACpB,OAAO,EAAE,eAAe,CACzB;IAED,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC;I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,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,GAAG,WAAW,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;;;;"}
@@ -124,7 +124,7 @@ function useAIGenerationButton(options) {
124
124
  try {
125
125
  const { responses } = await executeToolCalls(pendingCalls);
126
126
  if (responses.length > 0) {
127
- await clientRef.current.sendToolResponses(assistantId, chatUid, responses);
127
+ await clientRef.current.sendToolResponses(assistantId, chatUid, responses, toolSchemas);
128
128
  setShouldPoll(true);
129
129
  }
130
130
  }
@@ -133,7 +133,7 @@ function useAIGenerationButton(options) {
133
133
  setError(error);
134
134
  onErrorRef.current?.(error);
135
135
  }
136
- }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls]);
136
+ }, [chatUid, assistantId, executeToolCalls, extractPendingToolCalls, toolSchemas]);
137
137
  // Polling
138
138
  usePolling(shouldPoll ? chatUid : null, async () => {
139
139
  if (!clientRef.current || !chatUid) {
@@ -1 +1 @@
1
- {"version":3,"file":"useAIGenerationButton.js","sources":["../../../../src/components/AIGenerationButton/useAIGenerationButton.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling, resolvePollingInterval } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\nimport type {\n AIGenerationButtonOptions,\n GenerationResult,\n} from './AIGenerationButton.types';\nimport type { ToolCallSummary } from '../AICommandBar/AICommandBar.types';\n\nexport interface UseAIGenerationButtonOptions {\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 generation in progress (overrides the provider's). */\n pollingInterval?: number;\n options?: AIGenerationButtonOptions;\n modelInterfaceTools?: ModelInterfaceTool[];\n onResponse?: (result: GenerationResult) => void;\n onBeforeSend?: (prompt: string) => string | undefined | Promise<string | undefined>;\n onError?: (error: Error) => void;\n onStart?: () => void;\n onOpen?: () => void;\n onClose?: () => void;\n disabled?: boolean;\n}\n\nexport interface UseAIGenerationButtonResult {\n // State\n isOpen: boolean;\n isProcessing: boolean;\n inputValue: string;\n setInputValue: (value: string) => void;\n error: Error | null;\n result: GenerationResult | null;\n\n // Tool calls state\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Input ref\n inputRef: React.RefObject<HTMLTextAreaElement>;\n\n // Actions\n open: () => void;\n close: () => void;\n toggle: () => void;\n generate: (prompt?: string) => Promise<GenerationResult | null>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n}\n\n/**\n * Hook for managing AIGenerationButton state and behavior\n */\nexport function useAIGenerationButton(\n options: UseAIGenerationButtonOptions\n): UseAIGenerationButtonResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n tags,\n pollingInterval: propsPollingInterval,\n options: buttonOptions = {},\n modelInterfaceTools = [],\n onResponse,\n onBeforeSend,\n onError,\n onStart,\n onOpen,\n onClose,\n disabled,\n } = options;\n\n const { mode = 'modal' } = buttonOptions;\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\n // State\n const [isOpen, setIsOpen] = useState(false);\n const [isProcessing, setIsProcessing] = useState(false);\n const [inputValue, setInputValue] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<GenerationResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // Tool calls state\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Refs\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const resolveRef = useRef<((value: GenerationResult | null) => void) | null>(null);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onBeforeSendRef = useRef(onBeforeSend);\n const onStartRef = useRef(onStart);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onBeforeSendRef.current = onBeforeSend;\n onStartRef.current = onStart;\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 });\n\n /**\n * Format tool name to human-readable (fallback when no summary)\n */\n const formatToolName = (toolName: string): string => {\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 * Process tool calls from realtime data\n */\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(assistantId, chatUid, responses);\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]\n );\n\n // Polling\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n if (!clientRef.current || !chatUid) {\n throw new Error('Cannot poll without client or chatUid');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\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 - show executing tool or last tool\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('Processing failed');\n setError(err);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\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: ChatMessage) => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const finalToolCalls = processToolCalls(data.chatHistory);\n const generationResult: GenerationResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: finalToolCalls,\n rawResponse: data,\n };\n\n setResult(generationResult);\n onResponseRef.current?.(generationResult);\n resolveRef.current?.(generationResult);\n resolveRef.current = null;\n\n // Close modal/tooltip after successful generation\n setIsOpen(false);\n onCloseRef.current?.();\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\n },\n }\n );\n\n // Open modal/tooltip\n const open = useCallback(() => {\n if (disabled) return;\n setIsOpen(true);\n setError(null);\n onOpenRef.current?.();\n // Focus input after opening\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [disabled]);\n\n // Close modal/tooltip\n const close = useCallback(() => {\n setIsOpen(false);\n setInputValue('');\n onCloseRef.current?.();\n }, []);\n\n // Toggle\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n // Generate\n const generate = useCallback(\n async (prompt?: string): Promise<GenerationResult | null> => {\n // Determine the prompt to use\n let finalPrompt = prompt ?? inputValue;\n\n // For direct mode, use predefined prompt if no prompt provided\n if (mode === 'direct' && !finalPrompt) {\n finalPrompt = buttonOptions.prompt || '';\n }\n\n if (!finalPrompt.trim()) {\n const err = new Error('Prompt is required');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n if (disabled) {\n return null;\n }\n\n if (!clientRef.current) {\n const err = new Error('API client not configured. Please provide an API key.');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n // Call onBeforeSend hook\n if (onBeforeSendRef.current) {\n const modifiedPrompt = await onBeforeSendRef.current(finalPrompt);\n if (modifiedPrompt !== undefined) {\n finalPrompt = modifiedPrompt;\n }\n }\n\n // Start processing\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n onStartRef.current?.();\n\n // Create a promise that will resolve when generation completes\n const resultPromise = new Promise<GenerationResult | null>((resolve) => {\n resolveRef.current = resolve;\n });\n\n try {\n const dto = {\n message: finalPrompt,\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) {\n setChatUid(response.chatUid);\n }\n\n setShouldPoll(true);\n\n return resultPromise;\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 return null;\n }\n },\n [\n inputValue,\n mode,\n buttonOptions.prompt,\n disabled,\n assistantId,\n resolvedTenantId,\n resolvedTenantMetadata,\n resolvedTags,\n toolSchemas,\n ]\n );\n\n // Reset\n const reset = useCallback(() => {\n setIsOpen(false);\n setIsProcessing(false);\n setInputValue('');\n setError(null);\n setResult(null);\n setChatUid(null);\n setShouldPoll(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\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 close();\n return;\n }\n\n // Handle Enter to submit (Cmd/Ctrl + Enter or Enter without Shift)\n if (e.key === 'Enter' && !isProcessing) {\n if (e.metaKey || e.ctrlKey || !e.shiftKey) {\n e.preventDefault();\n generate();\n }\n }\n },\n [isProcessing, generate, close]\n );\n\n return {\n isOpen,\n isProcessing,\n inputValue,\n setInputValue,\n error,\n result,\n toolCalls,\n currentToolSummary,\n inputRef,\n open,\n close,\n toggle,\n generate,\n reset,\n handleKeyDown,\n };\n}\n"],"names":[],"mappings":";;;;;;;AA8DA;;AAEG;AACG,SAAU,qBAAqB,CACnC,OAAqC,EAAA;IAErC,MAAM,EACJ,WAAW,EACX,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,IAAI,EACJ,eAAe,EAAE,oBAAoB,EACrC,OAAO,EAAE,aAAa,GAAG,EAAE,EAC3B,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,YAAY,EACZ,OAAO,EACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,QAAQ,GACT,GAAG,OAAO;AAEX,IAAA,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE,GAAG,aAAa;;AAGxC,IAAA,MAAM,OAAO,GAAG,uBAAuB,EAAE;AACzC,IAAA,MAAM,MAAM,GAAG,W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AC/B,CAAC,CAAsB,KAAI;;AAEzB,QAAA,IAAI,CAAC,CAAC,GAAG,KAAK,QAAQ,EAAE;YACtB,CAAC,CAAC,cAAc,EAAE;AAClB,YAAA,KAAK,EAAE;YACP;QACF;;QAGA,IAAI,CAAC,CAAC,GAAG,KAAK,OAAO,IAAI,CAAC,YAAY,EAAE;AACtC,YAAA,IAAI,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC,QAAQ,EAAE;gBACzC,CAAC,CAAC,cAAc,EAAE;AAClB,gBAAA,QAAQ,EAAE;YACZ;QACF;IACF,CAAC,EACD,CAAC,YAAY,EAAE,QAAQ,EAAE,KAAK,CAAC,CAChC;IAED,OAAO;QACL,MAAM;QACN,YAAY;QACZ,UAAU;QACV,aAAa;QACb,KAAK;QACL,MAAM;QACN,SAAS;QACT,kBAAkB;QAClB,QAAQ;QACR,IAAI;QACJ,KAAK;QACL,MAAM;QACN,QAAQ;QACR,KAAK;QACL,aAAa;KACd;AACH;;;;"}
1
+ {"version":3,"file":"useAIGenerationButton.js","sources":["../../../../src/components/AIGenerationButton/useAIGenerationButton.ts"],"sourcesContent":["import { useState, useEffect, useCallback, useRef } from 'react';\nimport { useOptionalDevicContext } from '../../provider';\nimport { DevicApiClient } from '../../api/client';\nimport { usePolling, resolvePollingInterval } from '../../hooks/usePolling';\nimport { useModelInterface } from '../../hooks/useModelInterface';\nimport type {\n ChatMessage,\n ModelInterfaceTool,\n RealtimeChatHistory,\n} from '../../api/types';\nimport type {\n AIGenerationButtonOptions,\n GenerationResult,\n} from './AIGenerationButton.types';\nimport type { ToolCallSummary } from '../AICommandBar/AICommandBar.types';\n\nexport interface UseAIGenerationButtonOptions {\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 generation in progress (overrides the provider's). */\n pollingInterval?: number;\n options?: AIGenerationButtonOptions;\n modelInterfaceTools?: ModelInterfaceTool[];\n onResponse?: (result: GenerationResult) => void;\n onBeforeSend?: (prompt: string) => string | undefined | Promise<string | undefined>;\n onError?: (error: Error) => void;\n onStart?: () => void;\n onOpen?: () => void;\n onClose?: () => void;\n disabled?: boolean;\n}\n\nexport interface UseAIGenerationButtonResult {\n // State\n isOpen: boolean;\n isProcessing: boolean;\n inputValue: string;\n setInputValue: (value: string) => void;\n error: Error | null;\n result: GenerationResult | null;\n\n // Tool calls state\n toolCalls: ToolCallSummary[];\n currentToolSummary: string | null;\n\n // Input ref\n inputRef: React.RefObject<HTMLTextAreaElement>;\n\n // Actions\n open: () => void;\n close: () => void;\n toggle: () => void;\n generate: (prompt?: string) => Promise<GenerationResult | null>;\n reset: () => void;\n handleKeyDown: (e: React.KeyboardEvent) => void;\n}\n\n/**\n * Hook for managing AIGenerationButton state and behavior\n */\nexport function useAIGenerationButton(\n options: UseAIGenerationButtonOptions\n): UseAIGenerationButtonResult {\n const {\n assistantId,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n tags,\n pollingInterval: propsPollingInterval,\n options: buttonOptions = {},\n modelInterfaceTools = [],\n onResponse,\n onBeforeSend,\n onError,\n onStart,\n onOpen,\n onClose,\n disabled,\n } = options;\n\n const { mode = 'modal' } = buttonOptions;\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\n // State\n const [isOpen, setIsOpen] = useState(false);\n const [isProcessing, setIsProcessing] = useState(false);\n const [inputValue, setInputValue] = useState('');\n const [error, setError] = useState<Error | null>(null);\n const [result, setResult] = useState<GenerationResult | null>(null);\n const [chatUid, setChatUid] = useState<string | null>(null);\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // Tool calls state\n const [toolCalls, setToolCalls] = useState<ToolCallSummary[]>([]);\n const [currentToolSummary, setCurrentToolSummary] = useState<string | null>(null);\n\n // Refs\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const resolveRef = useRef<((value: GenerationResult | null) => void) | null>(null);\n\n // Callback refs\n const onErrorRef = useRef(onError);\n const onResponseRef = useRef(onResponse);\n const onBeforeSendRef = useRef(onBeforeSend);\n const onStartRef = useRef(onStart);\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n\n useEffect(() => {\n onErrorRef.current = onError;\n onResponseRef.current = onResponse;\n onBeforeSendRef.current = onBeforeSend;\n onStartRef.current = onStart;\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 });\n\n /**\n * Format tool name to human-readable (fallback when no summary)\n */\n const formatToolName = (toolName: string): string => {\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 * Process tool calls from realtime data\n */\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('Cannot poll without client or chatUid');\n }\n return clientRef.current.getRealtimeHistory(assistantId, chatUid);\n },\n {\n interval: pollingInterval,\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 - show executing tool or last tool\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('Processing failed');\n setError(err);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\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: ChatMessage) => m.role === 'assistant');\n const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];\n\n if (lastAssistantMessage && chatUid) {\n const finalToolCalls = processToolCalls(data.chatHistory);\n const generationResult: GenerationResult = {\n chatUid,\n message: lastAssistantMessage,\n toolCalls: finalToolCalls,\n rawResponse: data,\n };\n\n setResult(generationResult);\n onResponseRef.current?.(generationResult);\n resolveRef.current?.(generationResult);\n resolveRef.current = null;\n\n // Close modal/tooltip after successful generation\n setIsOpen(false);\n onCloseRef.current?.();\n }\n }\n },\n onError: (err) => {\n setError(err);\n setIsProcessing(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n resolveRef.current?.(null);\n resolveRef.current = null;\n },\n }\n );\n\n // Open modal/tooltip\n const open = useCallback(() => {\n if (disabled) return;\n setIsOpen(true);\n setError(null);\n onOpenRef.current?.();\n // Focus input after opening\n setTimeout(() => inputRef.current?.focus(), 50);\n }, [disabled]);\n\n // Close modal/tooltip\n const close = useCallback(() => {\n setIsOpen(false);\n setInputValue('');\n onCloseRef.current?.();\n }, []);\n\n // Toggle\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n // Generate\n const generate = useCallback(\n async (prompt?: string): Promise<GenerationResult | null> => {\n // Determine the prompt to use\n let finalPrompt = prompt ?? inputValue;\n\n // For direct mode, use predefined prompt if no prompt provided\n if (mode === 'direct' && !finalPrompt) {\n finalPrompt = buttonOptions.prompt || '';\n }\n\n if (!finalPrompt.trim()) {\n const err = new Error('Prompt is required');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n if (disabled) {\n return null;\n }\n\n if (!clientRef.current) {\n const err = new Error('API client not configured. Please provide an API key.');\n setError(err);\n onErrorRef.current?.(err);\n return null;\n }\n\n // Call onBeforeSend hook\n if (onBeforeSendRef.current) {\n const modifiedPrompt = await onBeforeSendRef.current(finalPrompt);\n if (modifiedPrompt !== undefined) {\n finalPrompt = modifiedPrompt;\n }\n }\n\n // Start processing\n setIsProcessing(true);\n setError(null);\n setResult(null);\n setToolCalls([]);\n setCurrentToolSummary(null);\n onStartRef.current?.();\n\n // Create a promise that will resolve when generation completes\n const resultPromise = new Promise<GenerationResult | null>((resolve) => {\n resolveRef.current = resolve;\n });\n\n try {\n const dto = {\n message: finalPrompt,\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) {\n setChatUid(response.chatUid);\n }\n\n setShouldPoll(true);\n\n return resultPromise;\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 return null;\n }\n },\n [\n inputValue,\n mode,\n buttonOptions.prompt,\n disabled,\n assistantId,\n resolvedTenantId,\n resolvedTenantMetadata,\n resolvedTags,\n toolSchemas,\n ]\n );\n\n // Reset\n const reset = useCallback(() => {\n setIsOpen(false);\n setIsProcessing(false);\n setInputValue('');\n setError(null);\n setResult(null);\n setChatUid(null);\n setShouldPoll(false);\n setToolCalls([]);\n setCurrentToolSummary(null);\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 close();\n return;\n }\n\n // Handle Enter to submit (Cmd/Ctrl + Enter or Enter without Shift)\n if (e.key === 'Enter' && !isProcessing) {\n if (e.metaKey || e.ctrlKey || !e.shiftKey) {\n e.preventDefault();\n generate();\n }\n }\n },\n [isProcessing, generate, close]\n );\n\n return {\n isOpen,\n isProcessing,\n inputValue,\n setInputValue,\n error,\n result,\n toolCalls,\n currentToolSummary,\n inputRef,\n open,\n close,\n toggle,\n generate,\n reset,\n handleKeyDown,\n };\n}\n"],"names":[],"mappings":";;;;;;;AA8DA;;AAEG;AACG,SAAU,qBAAqB,CACnC,OAAqC,EAAA;IAErC,MAAM,EACJ,WAAW,EACX,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,IAAI,EACJ,eAAe,EAAE,oBAAoB,EACrC,OAAO,EAAE,aAAa,GAAG,EAAE,EAC3B,mBAAmB,GAAG,EAAE,EACxB,UAAU,EACV,YAAY,EACZ,OAAO,EACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,QAAQ,GACT,GAAG,OAAO;AAEX,IAAA,MAAM,EAAE,IAAI,GAAG,OAAO,EAAE,GAAG,aAAa;;AAGxC,IAAA,MAAM,OAAO,GAAG,uBAAuB,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;AAChF,IAAA,MAAM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