@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":"useDevicChat.js","sources":["../../../../src/hooks/useDevicChat.ts"],"sourcesContent":["import { useState, useCallback, useEffect, useRef, useMemo } from 'react';\nimport { useOptionalDevicContext } from '../provider';\nimport type { TenantMetadata, SubtenantMetadata } from '../provider';\nimport { DevicApiClient, DevicApiError } from '../api/client';\nimport { usePolling, resolvePollingInterval } from './usePolling';\nimport { useModelInterface, type PendingWidgetCall } from './useModelInterface';\nimport { createLogger } from '../utils/logger';\nimport type {\n ChatMessage,\n ChatFile,\n ModelInterfaceTool,\n RealtimeChatHistory,\n RealtimeStatus,\n RecalledMemoryRecord,\n TenantLimitExceeded,\n} from '../api/types';\n\n/**\n * Cadence for the handoff watch, which only waits for the parent thread to\n * leave `handed_off` and so does not need the main conversation's rhythm.\n * A configured `pollingInterval` still wins over it.\n */\nconst DEFAULT_HANDOFF_POLL_INTERVAL_MS = 5000;\n\nexport interface UseDevicChatOptions {\n /**\n * Assistant identifier\n */\n assistantId: string;\n\n /**\n * Existing chat UID to continue a conversation\n */\n chatUid?: string;\n\n /**\n * API key (overrides provider context)\n */\n apiKey?: string;\n\n /**\n * Base URL (overrides provider context)\n */\n baseUrl?: string;\n\n /**\n * Tenant ID for multi-tenant environments\n */\n tenantId?: string;\n\n /**\n * Tenant metadata (e.g. { name, email, imageUrl })\n */\n tenantMetadata?: TenantMetadata;\n\n /**\n * Subtenant ID identifying a user/entity inside the tenant\n */\n subtenantId?: string;\n\n /**\n * Subtenant metadata (e.g. { id, name, email, imageUrl })\n */\n subtenantMetadata?: SubtenantMetadata;\n\n /**\n * Tags applied to the conversation. Sent as the top-level `tags` of each\n * message (distinct from metadata). Falls back to the DevicProvider's `tags`\n * and is merged (deduped) with any per-message tags passed to `sendMessage`.\n */\n tags?: string[];\n\n /**\n * Tools enabled from the assistant's configured tool groups\n */\n enabledTools?: string[];\n\n /**\n * Apps the end user connected that should sit out the messages sent from\n * here, by slug (`[\"gmail\"]`).\n *\n * A deny list over their own connected apps, not over the assistant's tools:\n * what is not named stays available. Sent with every message while it is set,\n * so it lasts as long as the caller keeps it set — the server keeps nothing\n * and the account is never disconnected.\n */\n disabledIntegrations?: string[];\n\n /**\n * Client-side tools for model interface protocol\n */\n modelInterfaceTools?: ModelInterfaceTool[];\n\n /**\n * How often (ms) the conversation in progress is polled for new content.\n * Overrides the DevicProvider's `pollingInterval`. Values below 250 ms are\n * clamped.\n * @default 1000\n */\n pollingInterval?: number;\n\n /**\n * Callback when a message is sent\n */\n onMessageSent?: (message: ChatMessage) => void;\n\n /**\n * Callback when a message is received\n */\n onMessageReceived?: (message: ChatMessage) => void;\n\n /**\n * Callback when a tool is called\n */\n onToolCall?: (toolName: string, params: any) => void;\n\n /**\n * Callback when an error occurs\n */\n onError?: (error: Error) => void;\n\n /**\n * Callback when a new chat is created\n */\n onChatCreated?: (chatUid: string) => void;\n\n /**\n * Custom file upload handler. When provided, replaces the default\n * upload to Devic API. Receives the raw File objects and must return\n * an array of ChatFile with downloadUrl set.\n */\n onFileUpload?: (files: File[]) => Promise<ChatFile[]>;\n\n /**\n * Enable debug logging to the browser console.\n * Overrides the provider-level debug setting when provided.\n * @default false\n */\n debug?: boolean;\n}\n\nexport interface UseDevicChatResult {\n /**\n * Current chat messages\n */\n messages: ChatMessage[];\n\n /**\n * Current chat UID\n */\n chatUid: string | null;\n\n /**\n * Whether a message is being processed\n */\n isLoading: boolean;\n\n /**\n * Current status\n */\n status: RealtimeStatus | 'idle';\n\n /**\n * Last error\n */\n error: Error | null;\n\n /**\n * Set when the last message was blocked by a tenant/subtenant usage limit\n * (HTTP 429 / realtime status `limit_exceeded`). Carries the blocking rule,\n * current vs. limit and when the window resets. `null` while not limited.\n * Cleared when a new message is sent or the chat is cleared.\n */\n limitExceeded: TenantLimitExceeded | null;\n\n /**\n * Structured long-term-memory recall events of the conversation, streamed\n * in while the assistant is still processing (via the realtime poll) and\n * hydrated from the persisted history on load. Empty for assistants\n * without memory.\n */\n recalledMemories: RecalledMemoryRecord[];\n\n /**\n * Whether the assistant has handed off to a subagent\n */\n handedOff: boolean;\n\n /**\n * The subthread ID when a handoff is active\n */\n handedOffSubThreadId: string | null;\n\n /**\n * Send a message\n */\n sendMessage: (\n message: string,\n options?: {\n files?: File[];\n metadata?: Record<string, any>;\n /** Id of a speech-to-text transcript that seeded this message. */\n transcriptId?: string;\n /** Per-message tags, merged (deduped) with the resolved conversation tags. */\n tags?: string[];\n /**\n * Connected apps to leave out of this one message, by slug. Replaces the\n * hook's own `disabledIntegrations` rather than adding to it, so a caller\n * can send one message with everything on by passing `[]`.\n */\n disabledIntegrations?: string[];\n }\n ) => Promise<void>;\n\n /**\n * Clear the chat and start a new conversation\n */\n clearChat: () => void;\n\n /**\n * Load an existing chat\n */\n loadChat: (chatUid: string) => Promise<void>;\n\n /**\n * Called when the handoff subagent completes.\n * Triggers reload of full chat content.\n */\n onHandoffCompleted: () => void;\n\n /**\n * Stop the current conversation processing (client-side only).\n * Stops polling and resets loading state.\n */\n stopChat: () => void;\n\n /**\n * Pending tool calls that require user interaction via a response widget\n */\n pendingWidgetCalls: PendingWidgetCall[];\n\n /**\n * Submit a response for a pending widget tool call.\n * Sends the response to the API and resumes the conversation.\n */\n submitWidgetResponse: (toolCallId: string, response: any) => Promise<void>;\n\n /**\n * Cancel a pending widget tool call.\n * Sends an error response so the model can continue.\n */\n cancelWidgetCall: (toolCallId: string, reason?: string) => Promise<void>;\n}\n\n/**\n * Main hook for managing chat with a Devic assistant\n *\n * @example\n * ```tsx\n * const {\n * messages,\n * isLoading,\n * sendMessage,\n * } = useDevicChat({\n * assistantId: 'my-assistant',\n * modelInterfaceTools: [\n * {\n * toolName: 'get_user_location',\n * schema: { ... },\n * callback: async () => ({ lat: 40.7, lng: -74.0 })\n * }\n * ],\n * onMessageReceived: (msg) => console.log('Received:', msg),\n * });\n * ```\n */\nexport function useDevicChat(options: UseDevicChatOptions): UseDevicChatResult {\n const {\n assistantId,\n chatUid: initialChatUid,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n subtenantId,\n subtenantMetadata,\n tags,\n enabledTools,\n disabledIntegrations,\n modelInterfaceTools = [],\n pollingInterval: propsPollingInterval,\n onMessageSent,\n onMessageReceived,\n onToolCall,\n onError,\n onChatCreated,\n onFileUpload,\n debug: propsDebug,\n } = options;\n\n // Get context (may be null if not wrapped in provider)\n const context = useOptionalDevicContext();\n\n // Resolve configuration\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 resolvedSubtenantId = subtenantId || context?.subtenantId;\n const resolvedSubtenantMetadata = {\n ...context?.subtenantMetadata,\n ...subtenantMetadata,\n };\n // Provider tags + hook tags, deduped. Per-message tags are merged at send time.\n const resolvedTags = useMemo(\n () => Array.from(new Set([...(context?.tags ?? []), ...(tags ?? [])])),\n [context?.tags, tags]\n );\n const pollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval\n );\n const handoffPollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval,\n DEFAULT_HANDOFF_POLL_INTERVAL_MS\n );\n const debug = propsDebug ?? context?.debug ?? false;\n const log = useMemo(() => createLogger(debug), [debug]);\n const logRef = useRef(log);\n logRef.current = log;\n\n // State\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [chatUid, setChatUid] = useState<string | null>(initialChatUid || null);\n const [isLoading, setIsLoading] = useState(false);\n const [status, setStatus] = useState<RealtimeStatus | 'idle'>('idle');\n const [error, setError] = useState<Error | null>(null);\n const [limitExceeded, setLimitExceeded] = useState<TenantLimitExceeded | null>(\n null\n );\n\n // Long-term-memory recall events of the conversation. The realtime blob\n // only carries the in-flight run's records, so incoming batches merge (by\n // uid) instead of replacing — earlier runs' recalls stay visible.\n const [recalledMemories, setRecalledMemories] = useState<RecalledMemoryRecord[]>([]);\n const mergeRecalledMemories = useCallback(\n (incoming?: RecalledMemoryRecord[]) => {\n if (!incoming?.length) return;\n setRecalledMemories((prev) => {\n const known = new Set(prev.map((r) => r.uid));\n const fresh = incoming.filter((r) => !known.has(r.uid));\n return fresh.length ? [...prev, ...fresh] : prev;\n });\n },\n []\n );\n\n // Handoff state\n const [handedOff, setHandedOff] = useState(false);\n const [handedOffSubThreadId, setHandedOffSubThreadId] = useState<string | null>(null);\n const handoffPollRef = useRef<ReturnType<typeof setInterval> | null>(null);\n\n // Polling state\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // Keep a ref to chatUid so async callbacks always read the latest value\n const chatUidRef = useRef(chatUid);\n chatUidRef.current = chatUid;\n\n // Refs for callbacks\n const onMessageReceivedRef = useRef(onMessageReceived);\n const onErrorRef = useRef(onError);\n const onChatCreatedRef = useRef(onChatCreated);\n\n useEffect(() => {\n onMessageReceivedRef.current = onMessageReceived;\n onErrorRef.current = onError;\n onChatCreatedRef.current = onChatCreated;\n });\n\n // Create 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 // Update client config if it changes\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n // Resume chat state based on realtime status.\n // Called after loading chat history to detect in-progress conversations.\n const resumeFromRealtimeStatus = useCallback(\n async (targetChatUid: string) => {\n if (!clientRef.current) return;\n try {\n const realtime = await clientRef.current.getRealtimeHistory(assistantId, targetChatUid);\n logRef.current.log('[useDevicChat] resumeFromRealtimeStatus:', realtime.status);\n\n // Update messages with realtime data (may be fresher than static history)\n if (realtime.chatHistory?.length) {\n setMessages(realtime.chatHistory);\n }\n mergeRecalledMemories(realtime.recalledMemories);\n setStatus(realtime.status);\n\n if (realtime.status === 'processing') {\n // Chat is still processing — resume polling\n setIsLoading(true);\n setShouldPoll(true);\n } else if (realtime.status === 'waiting_for_tool_response') {\n // Chat is waiting for tool response — resume polling to trigger tool handling\n setIsLoading(true);\n setShouldPoll(true);\n } else if (realtime.status === 'handed_off') {\n // Chat has an active handoff\n setIsLoading(true);\n setHandedOff(true);\n const subThreadId = realtime.handedOffSubThreadId || null;\n logRef.current.log('[useDevicChat] Resuming handoff state:', { subThreadId });\n if (subThreadId) {\n setHandedOffSubThreadId(subThreadId);\n }\n } else {\n // completed or error — just stop\n setIsLoading(false);\n }\n } catch (err) {\n // If realtime fetch fails (e.g. chat has no realtime entry), just stay idle\n logRef.current.warn('[useDevicChat] resumeFromRealtimeStatus failed:', err);\n setIsLoading(false);\n }\n },\n [assistantId, mergeRecalledMemories]\n );\n\n // Load initial chat history if chatUid prop is provided\n // This runs once on mount (or when initialChatUid changes) to fetch existing conversation\n const initialChatLoadedRef = useRef(false);\n useEffect(() => {\n if (initialChatUid && clientRef.current && !initialChatLoadedRef.current) {\n initialChatLoadedRef.current = true;\n\n const loadInitialChat = async () => {\n setIsLoading(true);\n setError(null);\n try {\n const history = await clientRef.current!.getChatHistory(\n assistantId,\n initialChatUid,\n { tenantId: resolvedTenantId }\n );\n setMessages(history.chatContent);\n mergeRecalledMemories(history.recalledMemories);\n setChatUid(initialChatUid);\n\n // Check realtime status to resume in-progress conversations\n await resumeFromRealtimeStatus(initialChatUid);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n setIsLoading(false);\n }\n };\n\n loadInitialChat();\n }\n }, [initialChatUid, assistantId, resolvedTenantId, resumeFromRealtimeStatus]);\n\n // Model interface hook\n const {\n toolSchemas,\n handleToolCalls,\n extractPendingToolCalls,\n } = useModelInterface({\n tools: modelInterfaceTools,\n onToolExecute: onToolCall,\n });\n\n // Pending widget calls awaiting user interaction\n const [pendingWidgetCalls, setPendingWidgetCalls] = useState<PendingWidgetCall[]>([]);\n const pendingWidgetCallsRef = useRef<PendingWidgetCall[]>([]);\n useEffect(() => {\n pendingWidgetCallsRef.current = pendingWidgetCalls;\n }, [pendingWidgetCalls]);\n\n // Polling hook - uses callbacks for side effects, return value not needed\n logRef.current.log('[useDevicChat] Render - shouldPoll:', shouldPoll, 'chatUid:', chatUid);\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n logRef.current.log('[useDevicChat] fetchFn called, chatUid:', chatUid);\n if (!clientRef.current || !chatUid) {\n throw new Error('Cannot poll without client or chatUid');\n }\n const result = await clientRef.current.getRealtimeHistory(assistantId, chatUid);\n logRef.current.log('[useDevicChat] getRealtimeHistory result:', result);\n return result;\n },\n {\n interval: pollingInterval,\n enabled: shouldPoll,\n stopStatuses: [\n 'completed',\n 'error',\n 'waiting_for_tool_response',\n 'handed_off',\n 'limit_exceeded',\n ],\n onUpdate: async (data: RealtimeChatHistory) => {\n logRef.current.log('[useDevicChat] onUpdate called, status:', data.status);\n\n // Merge realtime data with optimistic messages.\n // When a server user message matches an optimistic one by text, adopt the\n // optimistic uid so React's key stays stable (avoids unmount/remount flicker).\n setMessages((prev) => {\n const normalize = (t?: string) => (t ?? '').trim();\n const optimisticUserByText = new Map(\n prev\n .filter((m) => m.role === 'user' && m.uid.startsWith('temp-'))\n .map((m) => [normalize(m.content?.message), m.uid])\n );\n\n const adoptedTempUids = new Set<string>();\n const merged = data.chatHistory.map((m) => {\n if (m.role === 'user') {\n const tempUid = optimisticUserByText.get(normalize(m.content?.message));\n if (tempUid) {\n adoptedTempUids.add(tempUid);\n // Keep the server uid around: recall anchors reference it.\n return { ...m, uid: tempUid, serverUid: m.uid };\n }\n }\n return m;\n });\n\n const mergedUIDs = new Set(merged.map((m) => m.uid));\n const optimistic = prev.filter(\n (m) => !mergedUIDs.has(m.uid) && !adoptedTempUids.has(m.uid)\n );\n\n return [...merged, ...optimistic];\n });\n // Surface recall events while the run is still processing, so the\n // \"recalled memories\" strip shows before the first response lands.\n mergeRecalledMemories(data.recalledMemories);\n setStatus(data.status);\n\n // Notify about new messages\n const lastMessage = data.chatHistory[data.chatHistory.length - 1];\n if (lastMessage && lastMessage.role === 'assistant') {\n onMessageReceivedRef.current?.(lastMessage);\n }\n\n // Handle model interface - check for pending tool calls\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n logRef.current.log('[useDevicChat] onStop called, status:', data?.status);\n setShouldPoll(false);\n\n if (data?.status === 'limit_exceeded') {\n // The message was blocked by a tenant/subtenant usage limit before\n // reaching the LLM. Surface the details so the UI can show a banner.\n setIsLoading(false);\n const details: TenantLimitExceeded = data.limitExceeded || {\n message: 'Usage limit reached.',\n };\n setLimitExceeded(details);\n const err = new Error(\n details.message || 'Usage limit reached.'\n ) as Error & { errorType?: string; details?: TenantLimitExceeded };\n err.errorType = 'TENANT_LIMIT_EXCEEDED';\n err.details = details;\n setError(err);\n onErrorRef.current?.(err);\n } else if (data?.status === 'error') {\n setIsLoading(false);\n const err = new Error('Chat processing failed');\n setError(err);\n onErrorRef.current?.(err);\n } else if (data?.status === 'completed') {\n setIsLoading(false);\n } else if (data?.status === 'handed_off') {\n // Subagent is working — keep isLoading true so the UI stays in loading state.\n // Set handoff state directly from the realtime status.\n setHandedOff(true);\n\n const subThreadId = data.handedOffSubThreadId || null;\n logRef.current.log('[useDevicChat] Handoff state set:', { handedOff: true, subThreadId });\n if (subThreadId) {\n setHandedOffSubThreadId(subThreadId);\n }\n }\n // Note: waiting_for_tool_response is handled in onUpdate to avoid double execution\n },\n onError: (err) => {\n logRef.current.error('[useDevicChat] onError called:', err);\n setError(err);\n setIsLoading(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n debug,\n }\n );\n\n // Handle pending tool calls from model interface\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid) return;\n\n // Get pending tool calls\n const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);\n\n if (pendingCalls.length === 0) return;\n\n try {\n // Execute client-side tools (partitioned into immediate responses and widget-driven)\n const { responses, widgetCalls } = await handleToolCalls(pendingCalls);\n\n // Queue widget-driven tool calls for user interaction\n if (widgetCalls.length > 0) {\n const existingIds = new Set(pendingWidgetCallsRef.current.map((c) => c.toolCall.id));\n const deduped = widgetCalls.filter((c) => !existingIds.has(c.toolCall.id));\n const next = [...pendingWidgetCallsRef.current, ...deduped];\n pendingWidgetCallsRef.current = next;\n setPendingWidgetCalls(next);\n // Stop polling while we wait for the user to submit the widget response.\n // The widget submission will re-trigger polling via submitWidgetResponse.\n setShouldPoll(false);\n setIsLoading(false);\n }\n\n if (responses.length > 0) {\n // Send tool responses back to the API\n await clientRef.current.sendToolResponses(assistantId, chatUid, responses);\n\n // Only resume polling if no widgets are blocking\n if (widgetCalls.length === 0) {\n setShouldPoll(true);\n setIsLoading(true);\n }\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, handleToolCalls, extractPendingToolCalls]\n );\n\n // Send a message\n const sendMessage = useCallback(\n async (\n message: string,\n sendOptions?: {\n files?: File[];\n metadata?: Record<string, any>;\n transcriptId?: string;\n tags?: string[];\n disabledIntegrations?: string[];\n }\n ) => {\n if (!clientRef.current) {\n const err = new Error(\n 'API client not configured. Please provide an API key.'\n );\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n setIsLoading(true);\n setError(null);\n setLimitExceeded(null);\n setStatus('processing');\n\n // Add user message optimistically (show file names before upload)\n const userMessage: ChatMessage = {\n uid: `temp-${Date.now()}`,\n role: 'user',\n content: {\n message,\n files: sendOptions?.files?.map((f) => ({\n name: f.name,\n url: '',\n type: f.type.split('/')[0] || 'other',\n })),\n },\n timestamp: Date.now(),\n ...(sendOptions?.transcriptId && {\n transcriptId: sendOptions.transcriptId,\n }),\n };\n\n setMessages((prev) => [...prev, userMessage]);\n onMessageSent?.(userMessage);\n\n try {\n // Upload files if provided\n let uploadedFiles: ChatFile[] | undefined;\n if (sendOptions?.files && sendOptions.files.length > 0) {\n logRef.current.log('[useDevicChat] Uploading files...');\n if (onFileUpload) {\n // Use custom upload handler\n uploadedFiles = await onFileUpload(sendOptions.files);\n } else {\n // Default: upload via Devic API\n const uploadResults = await Promise.all(\n sendOptions.files.map((file) => clientRef.current!.uploadFile(file))\n );\n uploadedFiles = uploadResults.map((r) => ({\n name: r.name,\n downloadUrl: r.downloadUrl,\n fileType: r.fileType as ChatFile['fileType'],\n }));\n }\n logRef.current.log('[useDevicChat] Files uploaded:', uploadedFiles);\n\n // Update optimistic message with download URLs\n setMessages((prev) =>\n prev.map((m) =>\n m.uid === userMessage.uid\n ? {\n ...m,\n content: {\n ...m.content,\n files: uploadedFiles!.map((f) => ({\n name: f.name,\n url: f.downloadUrl || '',\n type: f.fileType || 'other',\n })),\n },\n }\n : m\n )\n );\n }\n\n // Build request DTO\n const hasSubtenantMetadata =\n resolvedSubtenantMetadata &&\n Object.keys(resolvedSubtenantMetadata).length > 0;\n const dto = {\n message,\n chatUid: chatUid || undefined,\n files: uploadedFiles,\n metadata: {\n ...resolvedTenantMetadata,\n ...(hasSubtenantMetadata && {\n subtenantMetadata: resolvedSubtenantMetadata,\n }),\n ...sendOptions?.metadata,\n },\n tenantId: resolvedTenantId,\n ...(resolvedSubtenantId && { subtenantId: resolvedSubtenantId }),\n // Conversation tags: provider + hook + per-message, deduped\n ...(() => {\n const merged = Array.from(\n new Set([...resolvedTags, ...(sendOptions?.tags ?? [])])\n );\n return merged.length > 0 ? { tags: merged } : {};\n })(),\n enabledTools,\n // The end user's own apps that sit this message out. Sent only when\n // some are switched off: an older API ignores the field, and there is\n // no reason to put an empty array in every request.\n ...(() => {\n const off = sendOptions?.disabledIntegrations ?? disabledIntegrations;\n return off?.length ? { disabledIntegrations: off } : {};\n })(),\n // Include model interface tools if any\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n // Link to the speech-to-text transcript that seeded this message, if any\n ...(sendOptions?.transcriptId && { transcriptId: sendOptions.transcriptId }),\n };\n\n // Send message in async mode\n logRef.current.log('[useDevicChat] Sending message async...');\n const response = await clientRef.current.sendMessageAsync(assistantId, dto);\n logRef.current.log('[useDevicChat] sendMessageAsync response:', response);\n\n // Update chat UID if this is a new chat\n if (response.chatUid && response.chatUid !== chatUid) {\n logRef.current.log('[useDevicChat] Setting chatUid:', response.chatUid);\n setChatUid(response.chatUid);\n onChatCreatedRef.current?.(response.chatUid);\n }\n\n // Start polling for results\n logRef.current.log('[useDevicChat] Setting shouldPoll to true');\n setShouldPoll(true);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n\n // A synchronous usage-limit block surfaces as HTTP 429 /\n // TENANT_LIMIT_EXCEEDED (sync send path). Async sends surface it via the\n // realtime `limit_exceeded` status instead — both are handled.\n if (\n err instanceof DevicApiError &&\n (err.statusCode === 429 || err.errorType === 'TENANT_LIMIT_EXCEEDED')\n ) {\n const details: TenantLimitExceeded =\n (err.details as TenantLimitExceeded) || { message: err.message };\n if (!details.message) details.message = err.message;\n setLimitExceeded(details);\n }\n\n setError(error);\n setIsLoading(false);\n setStatus('error');\n onErrorRef.current?.(error);\n\n // Remove optimistic user message on error\n setMessages((prev) => prev.filter((m) => m.uid !== userMessage.uid));\n }\n },\n [\n chatUid,\n assistantId,\n enabledTools,\n // Without this, the callback keeps the list from the render that created\n // it: switching an app off would not take effect until something else\n // happened to rebuild it.\n disabledIntegrations,\n resolvedTenantId,\n resolvedTenantMetadata,\n resolvedSubtenantId,\n resolvedSubtenantMetadata,\n resolvedTags,\n toolSchemas,\n onMessageSent,\n onFileUpload,\n ]\n );\n\n // Clear chat\n const clearChat = useCallback(() => {\n setShouldPoll(false);\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n setMessages([]);\n setChatUid(null);\n setIsLoading(false);\n setStatus('idle');\n setError(null);\n setLimitExceeded(null);\n setRecalledMemories([]);\n pendingWidgetCallsRef.current = [];\n setPendingWidgetCalls([]);\n }, []);\n\n // Load existing chat\n const loadChat = useCallback(\n async (loadChatUid: string) => {\n if (!clientRef.current) {\n const err = new Error('API client not configured');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n // Reset any active polling/handoff state from previous conversation\n setShouldPoll(false);\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n pendingWidgetCallsRef.current = [];\n setPendingWidgetCalls([]);\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n\n setIsLoading(true);\n setError(null);\n setRecalledMemories([]);\n\n try {\n const history = await clientRef.current.getChatHistory(\n assistantId,\n loadChatUid,\n { tenantId: resolvedTenantId }\n );\n\n setMessages(history.chatContent);\n mergeRecalledMemories(history.recalledMemories);\n setChatUid(loadChatUid);\n\n // Check realtime status to resume in-progress conversations\n await resumeFromRealtimeStatus(loadChatUid);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n setIsLoading(false);\n }\n },\n [assistantId, resolvedTenantId, resumeFromRealtimeStatus, mergeRecalledMemories]\n );\n\n // Handoff polling: while handedOff is true, poll the realtime endpoint every\n // 5s (or the configured cadence) to detect when the parent thread is no\n // longer in handed_off state.\n useEffect(() => {\n if (!handedOff || !chatUid || !clientRef.current) return;\n\n const pollHandoff = async () => {\n try {\n const realtime = await clientRef.current!.getRealtimeHistory(assistantId, chatUid!);\n logRef.current.log('[useDevicChat] Handoff poll - realtime status:', realtime.status);\n if (realtime.status !== 'handed_off') {\n // Handoff completed — clear handoff state and resume main polling\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n // Resume main polling to pick up the parent thread's continuation\n setShouldPoll(true);\n }\n } catch {}\n };\n\n handoffPollRef.current = setInterval(pollHandoff, handoffPollingInterval);\n return () => {\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n };\n }, [handedOff, chatUid, assistantId, handoffPollingInterval]);\n\n // Called by HandoffSubagentWidget when the subthread reaches a terminal state\n const onHandoffCompleted = useCallback(() => {\n logRef.current.log('[useDevicChat] onHandoffCompleted called');\n // Clear the handoff polling\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n // Clear handoff state and resume main polling\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n setShouldPoll(true);\n }, []);\n\n // Submit a response for a pending widget tool call\n const submitWidgetResponse = useCallback(\n async (toolCallId: string, response: any) => {\n const uid = chatUidRef.current;\n if (!clientRef.current || !uid) return;\n\n // Check pending widgets via ref (state updates are async)\n const current = pendingWidgetCallsRef.current;\n const found = current.some((c) => c.toolCall.id === toolCallId);\n if (!found) return;\n\n // Remove the widget call from pending list\n const remaining = current.filter((c) => c.toolCall.id !== toolCallId);\n pendingWidgetCallsRef.current = remaining;\n setPendingWidgetCalls(remaining);\n\n try {\n logRef.current.log('[useDevicChat] sending widget tool response', toolCallId);\n await clientRef.current.sendToolResponses(assistantId, uid, [\n { tool_call_id: toolCallId, content: response, role: 'tool' },\n ]);\n // Resume polling only if no more widget calls are blocking\n if (remaining.length === 0) {\n setShouldPoll(true);\n setIsLoading(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n logRef.current.error('[useDevicChat] submitWidgetResponse failed', error);\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [assistantId]\n );\n\n // Cancel a pending widget tool call (sends an error response to the model)\n const cancelWidgetCall = useCallback(\n async (toolCallId: string, reason?: string) => {\n await submitWidgetResponse(toolCallId, {\n error: reason || 'User cancelled the tool call',\n });\n },\n [submitWidgetResponse]\n );\n\n // Stop current conversation — calls the server-side stop endpoint\n // then stops polling and resets loading state.\n const stopChat = useCallback(async () => {\n const uid = chatUidRef.current;\n logRef.current.log('[useDevicChat] stopChat called, chatUid:', uid);\n if (clientRef.current && uid) {\n try {\n await clientRef.current.stopChat(assistantId, uid);\n logRef.current.log('[useDevicChat] stopChat API call succeeded');\n } catch (err) {\n logRef.current.warn('[useDevicChat] stopChat API call failed:', err);\n }\n }\n setShouldPoll(false);\n setIsLoading(false);\n setStatus('idle');\n }, [assistantId]);\n\n return {\n messages,\n chatUid,\n isLoading,\n status,\n error,\n limitExceeded,\n recalledMemories,\n handedOff,\n handedOffSubThreadId,\n sendMessage,\n clearChat,\n loadChat,\n onHandoffCompleted,\n stopChat,\n pendingWidgetCalls,\n submitWidgetResponse,\n cancelWidgetCall,\n };\n}\n"],"names":["useOptionalDevicContext","useMemo","resolvePollingInterval","createLogger","useRef","useState","useCallback","useEffect","DevicApiClient","useModelInterface","usePolling","DevicApiError"],"mappings":";;;;;;;;;;AAiBA;;;;AAIG;AACH,MAAM,gCAAgC,GAAG,IAAI;AAwO7C;;;;;;;;;;;;;;;;;;;;;AAqBG;AACG,SAAU,YAAY,CAAC,OAA4B,EAAA;IACvD,MAAM,EACJ,WAAW,EACX,OAAO,EAAE,cAAc,EACvB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,IAAI,EACJ,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,GAAG,EAAE,EACxB,eAAe,EAAE,oBAAoB,EACrC,aAAa,EACb,iBAAiB,EACjB,UAAU,EACV,OAAO,EACP,aAAa,EACb,YAAY,EACZ,KAAK,EAAE,UAAU,GAClB,GAAG,OAAO;;AAGX,IAAA,MAAM,OAAO,GAAGA,oCAAuB,EAAE;;AAGzC,IAAA,MAAM,MAAM,GAAG,WAAW,IAAI,OA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AAoB,CAAC,UAAU,EAAE;YACrC,KAAK,EAAE,MAAM,IAAI,8BAA8B;AAChD,SAAA,CAAC;AACJ,IAAA,CAAC,EACD,CAAC,oBAAoB,CAAC,CACvB;;;AAID,IAAA,MAAM,QAAQ,GAAGA,iBAAW,CAAC,YAAW;AACtC,QAAA,MAAM,GAAG,GAAG,UAAU,CAAC,OAAO;QAC9B,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,0CAA0C,EAAE,GAAG,CAAC;AACnE,QAAA,IAAI,SAAS,CAAC,OAAO,IAAI,GAAG,EAAE;AAC5B,YAAA,IAAI;gBACF,MAAM,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,GAAG,CAAC;AAClD,gBAAA,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC;YAClE;YAAE,OAAO,GAAG,EAAE;gBACZ,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,0CAA0C,EAAE,GAAG,CAAC;YACtE;QACF;QACA,aAAa,CAAC,KAAK,CAAC;QACpB,YAAY,CAAC,KAAK,CAAC;QACnB,SAAS,CAAC,MAAM,CAAC;AACnB,IAAA,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;IAEjB,OAAO;QACL,QAAQ;QACR,OAAO;QACP,SAAS;QACT,MAAM;QACN,KAAK;QACL,aAAa;QACb,gBAAgB;QAChB,SAAS;QACT,oBAAoB;QACpB,WAAW;QACX,SAAS;QACT,QAAQ;QACR,kBAAkB;QAClB,QAAQ;QACR,kBAAkB;QAClB,oBAAoB;QACpB,gBAAgB;KACjB;AACH;;;;"}
1
+ {"version":3,"file":"useDevicChat.js","sources":["../../../../src/hooks/useDevicChat.ts"],"sourcesContent":["import { useState, useCallback, useEffect, useRef, useMemo } from 'react';\nimport { useOptionalDevicContext } from '../provider';\nimport type { TenantMetadata, SubtenantMetadata } from '../provider';\nimport { DevicApiClient, DevicApiError } from '../api/client';\nimport { usePolling, resolvePollingInterval } from './usePolling';\nimport { useModelInterface, type PendingWidgetCall } from './useModelInterface';\nimport { createLogger } from '../utils/logger';\nimport type {\n ChatMessage,\n ChatFile,\n ModelInterfaceTool,\n RealtimeChatHistory,\n RealtimeStatus,\n RecalledMemoryRecord,\n TenantLimitExceeded,\n} from '../api/types';\n\n/**\n * Cadence for the handoff watch, which only waits for the parent thread to\n * leave `handed_off` and so does not need the main conversation's rhythm.\n * A configured `pollingInterval` still wins over it.\n */\nconst DEFAULT_HANDOFF_POLL_INTERVAL_MS = 5000;\n\nexport interface UseDevicChatOptions {\n /**\n * Assistant identifier\n */\n assistantId: string;\n\n /**\n * Existing chat UID to continue a conversation\n */\n chatUid?: string;\n\n /**\n * API key (overrides provider context)\n */\n apiKey?: string;\n\n /**\n * Base URL (overrides provider context)\n */\n baseUrl?: string;\n\n /**\n * Tenant ID for multi-tenant environments\n */\n tenantId?: string;\n\n /**\n * Tenant metadata (e.g. { name, email, imageUrl })\n */\n tenantMetadata?: TenantMetadata;\n\n /**\n * Subtenant ID identifying a user/entity inside the tenant\n */\n subtenantId?: string;\n\n /**\n * Subtenant metadata (e.g. { id, name, email, imageUrl })\n */\n subtenantMetadata?: SubtenantMetadata;\n\n /**\n * Tags applied to the conversation. Sent as the top-level `tags` of each\n * message (distinct from metadata). Falls back to the DevicProvider's `tags`\n * and is merged (deduped) with any per-message tags passed to `sendMessage`.\n */\n tags?: string[];\n\n /**\n * Tools enabled from the assistant's configured tool groups\n */\n enabledTools?: string[];\n\n /**\n * Apps the end user connected that should sit out the messages sent from\n * here, by slug (`[\"gmail\"]`).\n *\n * A deny list over their own connected apps, not over the assistant's tools:\n * what is not named stays available. Sent with every message while it is set,\n * so it lasts as long as the caller keeps it set — the server keeps nothing\n * and the account is never disconnected.\n */\n disabledIntegrations?: string[];\n\n /**\n * Client-side tools for model interface protocol\n */\n modelInterfaceTools?: ModelInterfaceTool[];\n\n /**\n * How often (ms) the conversation in progress is polled for new content.\n * Overrides the DevicProvider's `pollingInterval`. Values below 250 ms are\n * clamped.\n * @default 1000\n */\n pollingInterval?: number;\n\n /**\n * Callback when a message is sent\n */\n onMessageSent?: (message: ChatMessage) => void;\n\n /**\n * Callback when a message is received\n */\n onMessageReceived?: (message: ChatMessage) => void;\n\n /**\n * Callback when a tool is called\n */\n onToolCall?: (toolName: string, params: any) => void;\n\n /**\n * Callback when an error occurs\n */\n onError?: (error: Error) => void;\n\n /**\n * Callback when a new chat is created\n */\n onChatCreated?: (chatUid: string) => void;\n\n /**\n * Custom file upload handler. When provided, replaces the default\n * upload to Devic API. Receives the raw File objects and must return\n * an array of ChatFile with downloadUrl set.\n */\n onFileUpload?: (files: File[]) => Promise<ChatFile[]>;\n\n /**\n * Enable debug logging to the browser console.\n * Overrides the provider-level debug setting when provided.\n * @default false\n */\n debug?: boolean;\n}\n\nexport interface UseDevicChatResult {\n /**\n * Current chat messages\n */\n messages: ChatMessage[];\n\n /**\n * Current chat UID\n */\n chatUid: string | null;\n\n /**\n * Whether a message is being processed\n */\n isLoading: boolean;\n\n /**\n * Current status\n */\n status: RealtimeStatus | 'idle';\n\n /**\n * Last error\n */\n error: Error | null;\n\n /**\n * Set when the last message was blocked by a tenant/subtenant usage limit\n * (HTTP 429 / realtime status `limit_exceeded`). Carries the blocking rule,\n * current vs. limit and when the window resets. `null` while not limited.\n * Cleared when a new message is sent or the chat is cleared.\n */\n limitExceeded: TenantLimitExceeded | null;\n\n /**\n * Structured long-term-memory recall events of the conversation, streamed\n * in while the assistant is still processing (via the realtime poll) and\n * hydrated from the persisted history on load. Empty for assistants\n * without memory.\n */\n recalledMemories: RecalledMemoryRecord[];\n\n /**\n * Whether the assistant has handed off to a subagent\n */\n handedOff: boolean;\n\n /**\n * The subthread ID when a handoff is active\n */\n handedOffSubThreadId: string | null;\n\n /**\n * Send a message\n */\n sendMessage: (\n message: string,\n options?: {\n files?: File[];\n metadata?: Record<string, any>;\n /** Id of a speech-to-text transcript that seeded this message. */\n transcriptId?: string;\n /** Per-message tags, merged (deduped) with the resolved conversation tags. */\n tags?: string[];\n /**\n * Connected apps to leave out of this one message, by slug. Replaces the\n * hook's own `disabledIntegrations` rather than adding to it, so a caller\n * can send one message with everything on by passing `[]`.\n */\n disabledIntegrations?: string[];\n }\n ) => Promise<void>;\n\n /**\n * Clear the chat and start a new conversation\n */\n clearChat: () => void;\n\n /**\n * Load an existing chat\n */\n loadChat: (chatUid: string) => Promise<void>;\n\n /**\n * Called when the handoff subagent completes.\n * Triggers reload of full chat content.\n */\n onHandoffCompleted: () => void;\n\n /**\n * Stop the current conversation processing (client-side only).\n * Stops polling and resets loading state.\n */\n stopChat: () => void;\n\n /**\n * Pending tool calls that require user interaction via a response widget\n */\n pendingWidgetCalls: PendingWidgetCall[];\n\n /**\n * Submit a response for a pending widget tool call.\n * Sends the response to the API and resumes the conversation.\n */\n submitWidgetResponse: (toolCallId: string, response: any) => Promise<void>;\n\n /**\n * Cancel a pending widget tool call.\n * Sends an error response so the model can continue.\n */\n cancelWidgetCall: (toolCallId: string, reason?: string) => Promise<void>;\n}\n\n/**\n * Main hook for managing chat with a Devic assistant\n *\n * @example\n * ```tsx\n * const {\n * messages,\n * isLoading,\n * sendMessage,\n * } = useDevicChat({\n * assistantId: 'my-assistant',\n * modelInterfaceTools: [\n * {\n * toolName: 'get_user_location',\n * schema: { ... },\n * callback: async () => ({ lat: 40.7, lng: -74.0 })\n * }\n * ],\n * onMessageReceived: (msg) => console.log('Received:', msg),\n * });\n * ```\n */\nexport function useDevicChat(options: UseDevicChatOptions): UseDevicChatResult {\n const {\n assistantId,\n chatUid: initialChatUid,\n apiKey: propsApiKey,\n baseUrl: propsBaseUrl,\n tenantId,\n tenantMetadata,\n subtenantId,\n subtenantMetadata,\n tags,\n enabledTools,\n disabledIntegrations,\n modelInterfaceTools = [],\n pollingInterval: propsPollingInterval,\n onMessageSent,\n onMessageReceived,\n onToolCall,\n onError,\n onChatCreated,\n onFileUpload,\n debug: propsDebug,\n } = options;\n\n // Get context (may be null if not wrapped in provider)\n const context = useOptionalDevicContext();\n\n // Resolve configuration\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 resolvedSubtenantId = subtenantId || context?.subtenantId;\n const resolvedSubtenantMetadata = {\n ...context?.subtenantMetadata,\n ...subtenantMetadata,\n };\n // Provider tags + hook tags, deduped. Per-message tags are merged at send time.\n const resolvedTags = useMemo(\n () => Array.from(new Set([...(context?.tags ?? []), ...(tags ?? [])])),\n [context?.tags, tags]\n );\n const pollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval\n );\n const handoffPollingInterval = resolvePollingInterval(\n propsPollingInterval,\n context?.pollingInterval,\n DEFAULT_HANDOFF_POLL_INTERVAL_MS\n );\n const debug = propsDebug ?? context?.debug ?? false;\n const log = useMemo(() => createLogger(debug), [debug]);\n const logRef = useRef(log);\n logRef.current = log;\n\n // State\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [chatUid, setChatUid] = useState<string | null>(initialChatUid || null);\n const [isLoading, setIsLoading] = useState(false);\n const [status, setStatus] = useState<RealtimeStatus | 'idle'>('idle');\n const [error, setError] = useState<Error | null>(null);\n const [limitExceeded, setLimitExceeded] = useState<TenantLimitExceeded | null>(\n null\n );\n\n // Long-term-memory recall events of the conversation. The realtime blob\n // only carries the in-flight run's records, so incoming batches merge (by\n // uid) instead of replacing — earlier runs' recalls stay visible.\n const [recalledMemories, setRecalledMemories] = useState<RecalledMemoryRecord[]>([]);\n const mergeRecalledMemories = useCallback(\n (incoming?: RecalledMemoryRecord[]) => {\n if (!incoming?.length) return;\n setRecalledMemories((prev) => {\n const known = new Set(prev.map((r) => r.uid));\n const fresh = incoming.filter((r) => !known.has(r.uid));\n return fresh.length ? [...prev, ...fresh] : prev;\n });\n },\n []\n );\n\n // Handoff state\n const [handedOff, setHandedOff] = useState(false);\n const [handedOffSubThreadId, setHandedOffSubThreadId] = useState<string | null>(null);\n const handoffPollRef = useRef<ReturnType<typeof setInterval> | null>(null);\n\n // Polling state\n const [shouldPoll, setShouldPoll] = useState(false);\n\n // Keep a ref to chatUid so async callbacks always read the latest value\n const chatUidRef = useRef(chatUid);\n chatUidRef.current = chatUid;\n\n // Refs for callbacks\n const onMessageReceivedRef = useRef(onMessageReceived);\n const onErrorRef = useRef(onError);\n const onChatCreatedRef = useRef(onChatCreated);\n\n useEffect(() => {\n onMessageReceivedRef.current = onMessageReceived;\n onErrorRef.current = onError;\n onChatCreatedRef.current = onChatCreated;\n });\n\n // Create 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 // Update client config if it changes\n useEffect(() => {\n if (clientRef.current && apiKey) {\n clientRef.current.setConfig({ apiKey, baseUrl });\n }\n }, [apiKey, baseUrl]);\n\n // Resume chat state based on realtime status.\n // Called after loading chat history to detect in-progress conversations.\n const resumeFromRealtimeStatus = useCallback(\n async (targetChatUid: string) => {\n if (!clientRef.current) return;\n try {\n const realtime = await clientRef.current.getRealtimeHistory(assistantId, targetChatUid);\n logRef.current.log('[useDevicChat] resumeFromRealtimeStatus:', realtime.status);\n\n // Update messages with realtime data (may be fresher than static history)\n if (realtime.chatHistory?.length) {\n setMessages(realtime.chatHistory);\n }\n mergeRecalledMemories(realtime.recalledMemories);\n setStatus(realtime.status);\n\n if (realtime.status === 'processing') {\n // Chat is still processing — resume polling\n setIsLoading(true);\n setShouldPoll(true);\n } else if (realtime.status === 'waiting_for_tool_response') {\n // Chat is waiting for tool response — resume polling to trigger tool handling\n setIsLoading(true);\n setShouldPoll(true);\n } else if (realtime.status === 'handed_off') {\n // Chat has an active handoff\n setIsLoading(true);\n setHandedOff(true);\n const subThreadId = realtime.handedOffSubThreadId || null;\n logRef.current.log('[useDevicChat] Resuming handoff state:', { subThreadId });\n if (subThreadId) {\n setHandedOffSubThreadId(subThreadId);\n }\n } else {\n // completed or error — just stop\n setIsLoading(false);\n }\n } catch (err) {\n // If realtime fetch fails (e.g. chat has no realtime entry), just stay idle\n logRef.current.warn('[useDevicChat] resumeFromRealtimeStatus failed:', err);\n setIsLoading(false);\n }\n },\n [assistantId, mergeRecalledMemories]\n );\n\n // Load initial chat history if chatUid prop is provided\n // This runs once on mount (or when initialChatUid changes) to fetch existing conversation\n const initialChatLoadedRef = useRef(false);\n useEffect(() => {\n if (initialChatUid && clientRef.current && !initialChatLoadedRef.current) {\n initialChatLoadedRef.current = true;\n\n const loadInitialChat = async () => {\n setIsLoading(true);\n setError(null);\n try {\n const history = await clientRef.current!.getChatHistory(\n assistantId,\n initialChatUid,\n { tenantId: resolvedTenantId }\n );\n setMessages(history.chatContent);\n mergeRecalledMemories(history.recalledMemories);\n setChatUid(initialChatUid);\n\n // Check realtime status to resume in-progress conversations\n await resumeFromRealtimeStatus(initialChatUid);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n setIsLoading(false);\n }\n };\n\n loadInitialChat();\n }\n }, [initialChatUid, assistantId, resolvedTenantId, resumeFromRealtimeStatus]);\n\n // Model interface hook\n const {\n toolSchemas,\n handleToolCalls,\n extractPendingToolCalls,\n } = useModelInterface({\n tools: modelInterfaceTools,\n onToolExecute: onToolCall,\n });\n\n // Pending widget calls awaiting user interaction\n const [pendingWidgetCalls, setPendingWidgetCalls] = useState<PendingWidgetCall[]>([]);\n const pendingWidgetCallsRef = useRef<PendingWidgetCall[]>([]);\n useEffect(() => {\n pendingWidgetCallsRef.current = pendingWidgetCalls;\n }, [pendingWidgetCalls]);\n\n // Polling hook - uses callbacks for side effects, return value not needed\n logRef.current.log('[useDevicChat] Render - shouldPoll:', shouldPoll, 'chatUid:', chatUid);\n usePolling(\n shouldPoll ? chatUid : null,\n async () => {\n logRef.current.log('[useDevicChat] fetchFn called, chatUid:', chatUid);\n if (!clientRef.current || !chatUid) {\n throw new Error('Cannot poll without client or chatUid');\n }\n const result = await clientRef.current.getRealtimeHistory(assistantId, chatUid);\n logRef.current.log('[useDevicChat] getRealtimeHistory result:', result);\n return result;\n },\n {\n interval: pollingInterval,\n enabled: shouldPoll,\n stopStatuses: [\n 'completed',\n 'error',\n 'waiting_for_tool_response',\n 'handed_off',\n 'limit_exceeded',\n ],\n onUpdate: async (data: RealtimeChatHistory) => {\n logRef.current.log('[useDevicChat] onUpdate called, status:', data.status);\n\n // Merge realtime data with optimistic messages.\n // When a server user message matches an optimistic one by text, adopt the\n // optimistic uid so React's key stays stable (avoids unmount/remount flicker).\n setMessages((prev) => {\n const normalize = (t?: string) => (t ?? '').trim();\n const optimisticUserByText = new Map(\n prev\n .filter((m) => m.role === 'user' && m.uid.startsWith('temp-'))\n .map((m) => [normalize(m.content?.message), m.uid])\n );\n\n const adoptedTempUids = new Set<string>();\n const merged = data.chatHistory.map((m) => {\n if (m.role === 'user') {\n const tempUid = optimisticUserByText.get(normalize(m.content?.message));\n if (tempUid) {\n adoptedTempUids.add(tempUid);\n // Keep the server uid around: recall anchors reference it.\n return { ...m, uid: tempUid, serverUid: m.uid };\n }\n }\n return m;\n });\n\n const mergedUIDs = new Set(merged.map((m) => m.uid));\n const optimistic = prev.filter(\n (m) => !mergedUIDs.has(m.uid) && !adoptedTempUids.has(m.uid)\n );\n\n return [...merged, ...optimistic];\n });\n // Surface recall events while the run is still processing, so the\n // \"recalled memories\" strip shows before the first response lands.\n mergeRecalledMemories(data.recalledMemories);\n setStatus(data.status);\n\n // Notify about new messages\n const lastMessage = data.chatHistory[data.chatHistory.length - 1];\n if (lastMessage && lastMessage.role === 'assistant') {\n onMessageReceivedRef.current?.(lastMessage);\n }\n\n // Handle model interface - check for pending tool calls\n if (data.status === 'waiting_for_tool_response' || data.pendingToolCalls?.length) {\n await handlePendingToolCalls(data);\n }\n },\n onStop: (data) => {\n logRef.current.log('[useDevicChat] onStop called, status:', data?.status);\n setShouldPoll(false);\n\n if (data?.status === 'limit_exceeded') {\n // The message was blocked by a tenant/subtenant usage limit before\n // reaching the LLM. Surface the details so the UI can show a banner.\n setIsLoading(false);\n const details: TenantLimitExceeded = data.limitExceeded || {\n message: 'Usage limit reached.',\n };\n setLimitExceeded(details);\n const err = new Error(\n details.message || 'Usage limit reached.'\n ) as Error & { errorType?: string; details?: TenantLimitExceeded };\n err.errorType = 'TENANT_LIMIT_EXCEEDED';\n err.details = details;\n setError(err);\n onErrorRef.current?.(err);\n } else if (data?.status === 'error') {\n setIsLoading(false);\n const err = new Error('Chat processing failed');\n setError(err);\n onErrorRef.current?.(err);\n } else if (data?.status === 'completed') {\n setIsLoading(false);\n } else if (data?.status === 'handed_off') {\n // Subagent is working — keep isLoading true so the UI stays in loading state.\n // Set handoff state directly from the realtime status.\n setHandedOff(true);\n\n const subThreadId = data.handedOffSubThreadId || null;\n logRef.current.log('[useDevicChat] Handoff state set:', { handedOff: true, subThreadId });\n if (subThreadId) {\n setHandedOffSubThreadId(subThreadId);\n }\n }\n // Note: waiting_for_tool_response is handled in onUpdate to avoid double execution\n },\n onError: (err) => {\n logRef.current.error('[useDevicChat] onError called:', err);\n setError(err);\n setIsLoading(false);\n setShouldPoll(false);\n onErrorRef.current?.(err);\n },\n debug,\n }\n );\n\n // Handle pending tool calls from model interface\n const handlePendingToolCalls = useCallback(\n async (data: RealtimeChatHistory) => {\n if (!clientRef.current || !chatUid) return;\n\n // Get pending tool calls\n const pendingCalls = data.pendingToolCalls || extractPendingToolCalls(data.chatHistory);\n\n if (pendingCalls.length === 0) return;\n\n try {\n // Execute client-side tools (partitioned into immediate responses and widget-driven)\n const { responses, widgetCalls } = await handleToolCalls(pendingCalls);\n\n // Queue widget-driven tool calls for user interaction\n if (widgetCalls.length > 0) {\n const existingIds = new Set(pendingWidgetCallsRef.current.map((c) => c.toolCall.id));\n const deduped = widgetCalls.filter((c) => !existingIds.has(c.toolCall.id));\n const next = [...pendingWidgetCallsRef.current, ...deduped];\n pendingWidgetCallsRef.current = next;\n setPendingWidgetCalls(next);\n // Stop polling while we wait for the user to submit the widget response.\n // The widget submission will re-trigger polling via submitWidgetResponse.\n setShouldPoll(false);\n setIsLoading(false);\n }\n\n if (responses.length > 0) {\n // Send tool responses back to the API, restating the tools so the\n // continuation keeps them on offer\n await clientRef.current.sendToolResponses(\n assistantId,\n chatUid,\n responses,\n toolSchemas\n );\n\n // Only resume polling if no widgets are blocking\n if (widgetCalls.length === 0) {\n setShouldPoll(true);\n setIsLoading(true);\n }\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, handleToolCalls, extractPendingToolCalls, toolSchemas]\n );\n\n // Send a message\n const sendMessage = useCallback(\n async (\n message: string,\n sendOptions?: {\n files?: File[];\n metadata?: Record<string, any>;\n transcriptId?: string;\n tags?: string[];\n disabledIntegrations?: string[];\n }\n ) => {\n if (!clientRef.current) {\n const err = new Error(\n 'API client not configured. Please provide an API key.'\n );\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n setIsLoading(true);\n setError(null);\n setLimitExceeded(null);\n setStatus('processing');\n\n // Add user message optimistically (show file names before upload)\n const userMessage: ChatMessage = {\n uid: `temp-${Date.now()}`,\n role: 'user',\n content: {\n message,\n files: sendOptions?.files?.map((f) => ({\n name: f.name,\n url: '',\n type: f.type.split('/')[0] || 'other',\n })),\n },\n timestamp: Date.now(),\n ...(sendOptions?.transcriptId && {\n transcriptId: sendOptions.transcriptId,\n }),\n };\n\n setMessages((prev) => [...prev, userMessage]);\n onMessageSent?.(userMessage);\n\n try {\n // Upload files if provided\n let uploadedFiles: ChatFile[] | undefined;\n if (sendOptions?.files && sendOptions.files.length > 0) {\n logRef.current.log('[useDevicChat] Uploading files...');\n if (onFileUpload) {\n // Use custom upload handler\n uploadedFiles = await onFileUpload(sendOptions.files);\n } else {\n // Default: upload via Devic API\n const uploadResults = await Promise.all(\n sendOptions.files.map((file) => clientRef.current!.uploadFile(file))\n );\n uploadedFiles = uploadResults.map((r) => ({\n name: r.name,\n downloadUrl: r.downloadUrl,\n fileType: r.fileType as ChatFile['fileType'],\n }));\n }\n logRef.current.log('[useDevicChat] Files uploaded:', uploadedFiles);\n\n // Update optimistic message with download URLs\n setMessages((prev) =>\n prev.map((m) =>\n m.uid === userMessage.uid\n ? {\n ...m,\n content: {\n ...m.content,\n files: uploadedFiles!.map((f) => ({\n name: f.name,\n url: f.downloadUrl || '',\n type: f.fileType || 'other',\n })),\n },\n }\n : m\n )\n );\n }\n\n // Build request DTO\n const hasSubtenantMetadata =\n resolvedSubtenantMetadata &&\n Object.keys(resolvedSubtenantMetadata).length > 0;\n const dto = {\n message,\n chatUid: chatUid || undefined,\n files: uploadedFiles,\n metadata: {\n ...resolvedTenantMetadata,\n ...(hasSubtenantMetadata && {\n subtenantMetadata: resolvedSubtenantMetadata,\n }),\n ...sendOptions?.metadata,\n },\n tenantId: resolvedTenantId,\n ...(resolvedSubtenantId && { subtenantId: resolvedSubtenantId }),\n // Conversation tags: provider + hook + per-message, deduped\n ...(() => {\n const merged = Array.from(\n new Set([...resolvedTags, ...(sendOptions?.tags ?? [])])\n );\n return merged.length > 0 ? { tags: merged } : {};\n })(),\n enabledTools,\n // The end user's own apps that sit this message out. Sent only when\n // some are switched off: an older API ignores the field, and there is\n // no reason to put an empty array in every request.\n ...(() => {\n const off = sendOptions?.disabledIntegrations ?? disabledIntegrations;\n return off?.length ? { disabledIntegrations: off } : {};\n })(),\n // Include model interface tools if any\n ...(toolSchemas.length > 0 && { tools: toolSchemas }),\n // Link to the speech-to-text transcript that seeded this message, if any\n ...(sendOptions?.transcriptId && { transcriptId: sendOptions.transcriptId }),\n };\n\n // Send message in async mode\n logRef.current.log('[useDevicChat] Sending message async...');\n const response = await clientRef.current.sendMessageAsync(assistantId, dto);\n logRef.current.log('[useDevicChat] sendMessageAsync response:', response);\n\n // Update chat UID if this is a new chat\n if (response.chatUid && response.chatUid !== chatUid) {\n logRef.current.log('[useDevicChat] Setting chatUid:', response.chatUid);\n setChatUid(response.chatUid);\n onChatCreatedRef.current?.(response.chatUid);\n }\n\n // Start polling for results\n logRef.current.log('[useDevicChat] Setting shouldPoll to true');\n setShouldPoll(true);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n\n // A synchronous usage-limit block surfaces as HTTP 429 /\n // TENANT_LIMIT_EXCEEDED (sync send path). Async sends surface it via the\n // realtime `limit_exceeded` status instead — both are handled.\n if (\n err instanceof DevicApiError &&\n (err.statusCode === 429 || err.errorType === 'TENANT_LIMIT_EXCEEDED')\n ) {\n const details: TenantLimitExceeded =\n (err.details as TenantLimitExceeded) || { message: err.message };\n if (!details.message) details.message = err.message;\n setLimitExceeded(details);\n }\n\n setError(error);\n setIsLoading(false);\n setStatus('error');\n onErrorRef.current?.(error);\n\n // Remove optimistic user message on error\n setMessages((prev) => prev.filter((m) => m.uid !== userMessage.uid));\n }\n },\n [\n chatUid,\n assistantId,\n enabledTools,\n // Without this, the callback keeps the list from the render that created\n // it: switching an app off would not take effect until something else\n // happened to rebuild it.\n disabledIntegrations,\n resolvedTenantId,\n resolvedTenantMetadata,\n resolvedSubtenantId,\n resolvedSubtenantMetadata,\n resolvedTags,\n toolSchemas,\n onMessageSent,\n onFileUpload,\n ]\n );\n\n // Clear chat\n const clearChat = useCallback(() => {\n setShouldPoll(false);\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n setMessages([]);\n setChatUid(null);\n setIsLoading(false);\n setStatus('idle');\n setError(null);\n setLimitExceeded(null);\n setRecalledMemories([]);\n pendingWidgetCallsRef.current = [];\n setPendingWidgetCalls([]);\n }, []);\n\n // Load existing chat\n const loadChat = useCallback(\n async (loadChatUid: string) => {\n if (!clientRef.current) {\n const err = new Error('API client not configured');\n setError(err);\n onErrorRef.current?.(err);\n return;\n }\n\n // Reset any active polling/handoff state from previous conversation\n setShouldPoll(false);\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n pendingWidgetCallsRef.current = [];\n setPendingWidgetCalls([]);\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n\n setIsLoading(true);\n setError(null);\n setRecalledMemories([]);\n\n try {\n const history = await clientRef.current.getChatHistory(\n assistantId,\n loadChatUid,\n { tenantId: resolvedTenantId }\n );\n\n setMessages(history.chatContent);\n mergeRecalledMemories(history.recalledMemories);\n setChatUid(loadChatUid);\n\n // Check realtime status to resume in-progress conversations\n await resumeFromRealtimeStatus(loadChatUid);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setError(error);\n onErrorRef.current?.(error);\n setIsLoading(false);\n }\n },\n [assistantId, resolvedTenantId, resumeFromRealtimeStatus, mergeRecalledMemories]\n );\n\n // Handoff polling: while handedOff is true, poll the realtime endpoint every\n // 5s (or the configured cadence) to detect when the parent thread is no\n // longer in handed_off state.\n useEffect(() => {\n if (!handedOff || !chatUid || !clientRef.current) return;\n\n const pollHandoff = async () => {\n try {\n const realtime = await clientRef.current!.getRealtimeHistory(assistantId, chatUid!);\n logRef.current.log('[useDevicChat] Handoff poll - realtime status:', realtime.status);\n if (realtime.status !== 'handed_off') {\n // Handoff completed — clear handoff state and resume main polling\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n // Resume main polling to pick up the parent thread's continuation\n setShouldPoll(true);\n }\n } catch {}\n };\n\n handoffPollRef.current = setInterval(pollHandoff, handoffPollingInterval);\n return () => {\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n };\n }, [handedOff, chatUid, assistantId, handoffPollingInterval]);\n\n // Called by HandoffSubagentWidget when the subthread reaches a terminal state\n const onHandoffCompleted = useCallback(() => {\n logRef.current.log('[useDevicChat] onHandoffCompleted called');\n // Clear the handoff polling\n if (handoffPollRef.current) {\n clearInterval(handoffPollRef.current);\n handoffPollRef.current = null;\n }\n // Clear handoff state and resume main polling\n setHandedOff(false);\n setHandedOffSubThreadId(null);\n setShouldPoll(true);\n }, []);\n\n // Submit a response for a pending widget tool call\n const submitWidgetResponse = useCallback(\n async (toolCallId: string, response: any) => {\n const uid = chatUidRef.current;\n if (!clientRef.current || !uid) return;\n\n // Check pending widgets via ref (state updates are async)\n const current = pendingWidgetCallsRef.current;\n const found = current.some((c) => c.toolCall.id === toolCallId);\n if (!found) return;\n\n // Remove the widget call from pending list\n const remaining = current.filter((c) => c.toolCall.id !== toolCallId);\n pendingWidgetCallsRef.current = remaining;\n setPendingWidgetCalls(remaining);\n\n try {\n logRef.current.log('[useDevicChat] sending widget tool response', toolCallId);\n await clientRef.current.sendToolResponses(\n assistantId,\n uid,\n [{ tool_call_id: toolCallId, content: response, role: 'tool' }],\n toolSchemas\n );\n // Resume polling only if no more widget calls are blocking\n if (remaining.length === 0) {\n setShouldPoll(true);\n setIsLoading(true);\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n logRef.current.error('[useDevicChat] submitWidgetResponse failed', error);\n setError(error);\n onErrorRef.current?.(error);\n }\n },\n [assistantId, toolSchemas]\n );\n\n // Cancel a pending widget tool call (sends an error response to the model)\n const cancelWidgetCall = useCallback(\n async (toolCallId: string, reason?: string) => {\n await submitWidgetResponse(toolCallId, {\n error: reason || 'User cancelled the tool call',\n });\n },\n [submitWidgetResponse]\n );\n\n // Stop current conversation — calls the server-side stop endpoint\n // then stops polling and resets loading state.\n const stopChat = useCallback(async () => {\n const uid = chatUidRef.current;\n logRef.current.log('[useDevicChat] stopChat called, chatUid:', uid);\n if (clientRef.current && uid) {\n try {\n await clientRef.current.stopChat(assistantId, uid);\n logRef.current.log('[useDevicChat] stopChat API call succeeded');\n } catch (err) {\n logRef.current.warn('[useDevicChat] stopChat API call failed:', err);\n }\n }\n setShouldPoll(false);\n setIsLoading(false);\n setStatus('idle');\n }, [assistantId]);\n\n return {\n messages,\n chatUid,\n isLoading,\n status,\n error,\n limitExceeded,\n recalledMemories,\n handedOff,\n handedOffSubThreadId,\n sendMessage,\n clearChat,\n loadChat,\n onHandoffCompleted,\n stopChat,\n pendingWidgetCalls,\n submitWidgetResponse,\n cancelWidgetCall,\n };\n}\n"],"names":["useOptionalDevicContext","useMemo","resolvePollingInterval","createLogger","useRef","useState","useCallback","useEffect","DevicApiClient","useModelInterface","usePolling","DevicApiError"],"mappings":";;;;;;;;;;AAiBA;;;;AAIG;AACH,MAAM,gCAAgC,GAAG,IAAI;AAwO7C;;;;;;;;;;;;;;;;;;;;;AAqBG;AACG,SAAU,YAAY,CAAC,OAA4B,EAAA;IACvD,MAAM,EACJ,WAAW,EACX,OAAO,EAAE,cAAc,EACvB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,QAAQ,EACR,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,IAAI,EACJ,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,GAAG,EAAE,EACxB,eAAe,EAAE,oBAAoB,EACrC,aAAa,EACb,iBAAiB,EACjB,UAAU,EACV,OAAO,EACP,aAAa,EACb,YAAY,EACZ,KAAK,EAAE,UAAU,GAClB,GAAG,OAAO;;AAGX,IAAA,MAAM,OAAO,GAAGA,oCAAuB,EAAE;;AAGzC,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,G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;QAC9B,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,0CAA0C,EAAE,GAAG,CAAC;AACnE,QAAA,IAAI,SAAS,CAAC,OAAO,IAAI,GAAG,EAAE;AAC5B,YAAA,IAAI;gBACF,MAAM,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,GAAG,CAAC;AAClD,gBAAA,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC;YAClE;YAAE,OAAO,GAAG,EAAE;gBACZ,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,0CAA0C,EAAE,GAAG,CAAC;YACtE;QACF;QACA,aAAa,CAAC,KAAK,CAAC;QACpB,YAAY,CAAC,KAAK,CAAC;QACnB,SAAS,CAAC,MAAM,CAAC;AACnB,IAAA,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC;IAEjB,OAAO;QACL,QAAQ;QACR,OAAO;QACP,SAAS;QACT,MAAM;QACN,KAAK;QACL,aAAa;QACb,gBAAgB;QAChB,SAAS;QACT,oBAAoB;QACpB,WAAW;QACX,SAAS;QACT,QAAQ;QACR,kBAAkB;QAClB,QAAQ;QACR,kBAAkB;QAClB,oBAAoB;QACpB,gBAAgB;KACjB;AACH;;;;"}
@@ -1,4 +1,4 @@
1
- import type { ProcessMessageDto, ChatMessage, AsyncResponse, RealtimeChatHistory, ChatHistory, AssistantSpecialization, ApiError, ToolCallResponse, ListConversationsResponse, FeedbackSubmission, FeedbackEntry, AgentThreadDto, AgentDto, WhisperTranscriptionResponse, TenantUsage, TenantUsageHistoryRow, TenantUsageHistoryQuery, CoreMemoryList, CoreMemoryEntry, Integration, IntegrationAuthScheme, IntegrationSetupRequired } from "./types";
1
+ import type { ProcessMessageDto, ChatMessage, AsyncResponse, RealtimeChatHistory, ChatHistory, AssistantSpecialization, ApiError, ToolCallResponse, ListConversationsResponse, FeedbackSubmission, FeedbackEntry, AgentThreadDto, AgentDto, WhisperTranscriptionResponse, TenantUsage, TenantUsageHistoryRow, TenantUsageHistoryQuery, CoreMemoryList, CoreMemoryEntry, Integration, IntegrationAuthScheme, IntegrationSetupRequired, ModelInterfaceToolSchema } from "./types";
2
2
  /**
3
3
  * A tenant session, as the integrator's backend hands it over.
4
4
  *
@@ -123,9 +123,14 @@ export declare class DevicApiClient {
123
123
  limit?: number;
124
124
  }): Promise<ListConversationsResponse>;
125
125
  /**
126
- * Send tool call responses back to the assistant
126
+ * Send tool call responses back to the assistant.
127
+ *
128
+ * `toolSchemas` re-states the client-side tools for the continuation. The
129
+ * API takes them from the first response of the batch, and without them the
130
+ * turn resumes with no client tools at all — the model stops being able to
131
+ * call them after the first round.
127
132
  */
128
- sendToolResponses(assistantId: string, chatUid: string, responses: ToolCallResponse[]): Promise<AsyncResponse>;
133
+ sendToolResponses(assistantId: string, chatUid: string, responses: ToolCallResponse[], toolSchemas?: ModelInterfaceToolSchema[]): Promise<AsyncResponse>;
129
134
  /**
130
135
  * Submit feedback for a chat message
131
136
  */
@@ -233,12 +233,20 @@ class DevicApiClient {
233
233
  return this.request(`/api/v1/assistants/${assistantId}/chats${query ? `?${query}` : ""}`);
234
234
  }
235
235
  /**
236
- * Send tool call responses back to the assistant
237
- */
238
- async sendToolResponses(assistantId, chatUid, responses) {
236
+ * Send tool call responses back to the assistant.
237
+ *
238
+ * `toolSchemas` re-states the client-side tools for the continuation. The
239
+ * API takes them from the first response of the batch, and without them the
240
+ * turn resumes with no client tools at all — the model stops being able to
241
+ * call them after the first round.
242
+ */
243
+ async sendToolResponses(assistantId, chatUid, responses, toolSchemas) {
244
+ const body = toolSchemas?.length && responses.length > 0
245
+ ? responses.map((response, index) => index === 0 ? { ...response, tools: toolSchemas } : response)
246
+ : responses;
239
247
  return this.request(`/api/v1/assistants/${assistantId}/chats/${chatUid}/tool-response`, {
240
248
  method: "POST",
241
- body: JSON.stringify({ responses }),
249
+ body: JSON.stringify({ responses: body }),
242
250
  });
243
251
  }
244
252
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../../src/api/client.ts"],"sourcesContent":["import type {\n ProcessMessageDto,\n ChatMessage,\n AsyncResponse,\n RealtimeChatHistory,\n ChatHistory,\n AssistantSpecialization,\n ApiError,\n ToolCallResponse,\n ConversationSummary,\n ListConversationsResponse,\n FeedbackSubmission,\n FeedbackEntry,\n AgentThreadDto,\n AgentDto,\n WhisperTranscriptionResponse,\n TenantUsage,\n TenantUsageHistoryRow,\n TenantUsageHistoryQuery,\n CoreMemoryList,\n CoreMemoryEntry,\n Integration,\n IntegrationAuthScheme,\n IntegrationSetupRequired,\n} from \"./types\";\n\n/**\n * A tenant session, as the integrator's backend hands it over.\n *\n * A bare string is accepted too — the expiry is then read out of the token\n * itself, so the simplest possible source still gets proactive renewal.\n */\nexport interface TenantSessionToken {\n token: string;\n /** Epoch milliseconds. */\n expiresAt?: number;\n /** Seconds from now. Used when `expiresAt` is absent. */\n expiresIn?: number;\n}\n\nexport interface DevicApiClientConfig {\n /**\n * The public API key. Optional when `getTenantSession` is supplied — a page\n * using tenant sessions has no reason to carry one.\n */\n apiKey?: string;\n baseUrl: string;\n /**\n * Where the tenant session comes from.\n *\n * Supplying this changes what the tenant IS: with an API key alone the tenant\n * is whatever the page says it is, and the page can say anything. With a\n * session it is what your server signed.\n *\n * A function rather than a value because it is called again on its own —\n * before the token expires and after the API rejects one. It does not have to\n * reach your backend: reading a cookie your login already set is a perfectly\n * good answer, and then the whole thing is `async () => readCookie(…)`.\n *\n * It is called with `force: true` when the API has just rejected the token in\n * hand, meaning a cached answer is known to be dead. Your own function can\n * ignore the argument — `DevicProvider` uses it to share one session across\n * every component without ever serving a refused token back.\n */\n getTenantSession?: (force?: boolean) => Promise<string | TenantSessionToken>;\n /**\n * Called when the session is dead and cannot be replaced — the API rejected\n * it and `getTenantSession` handed back the same expired token.\n *\n * Matters most when the session comes from a cookie with no way to renew it:\n * without this the widget simply stops answering, at the exact moment the\n * user's own login has also expired. Refresh the page, send them to log in,\n * or say something — but say it.\n */\n onSessionExpired?: () => void;\n}\n\n/** Renew this long before expiry, so a request never leaves with a dead token. */\nconst RENEWAL_MARGIN_MS = 60_000;\n\n/**\n * The expiry inside a JWT, in epoch milliseconds.\n *\n * Read rather than required, so the session source can return just the string.\n * Any failure means \"no idea\", and the token is then renewed only when the API\n * rejects it — correct, just less graceful.\n */\nfunction expiryOf(token: string): number | undefined {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return undefined;\n const json = atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const exp = JSON.parse(json)?.exp;\n return typeof exp === \"number\" ? exp * 1000 : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Devic API client using native fetch\n */\nexport class DevicApiClient {\n private config: DevicApiClientConfig;\n private session?: { token: string; expiresAt?: number };\n /** In flight renewal, shared so a burst of calls fetches one token. */\n private renewing?: Promise<string>;\n /** So a page full of widgets reports one expiry, not one per widget. */\n private expiryReported = false;\n\n constructor(config: DevicApiClientConfig) {\n this.config = config;\n }\n\n /**\n * Update client configuration\n */\n setConfig(config: Partial<DevicApiClientConfig>): void {\n const previous = this.config;\n this.config = { ...this.config, ...config };\n // A new session source speaks for a different end user; keeping the old\n // token would show them the previous one's conversations.\n if (\n config.getTenantSession &&\n config.getTenantSession !== previous.getTenantSession\n ) {\n this.session = undefined;\n this.expiryReported = false;\n }\n }\n\n /** The credential for the next request, renewed if it is about to expire. */\n private async authorization(force = false): Promise<string> {\n if (!this.config.getTenantSession) return this.config.apiKey ?? \"\";\n\n const current = this.session;\n const stillGood =\n current &&\n (current.expiresAt === undefined ||\n current.expiresAt - Date.now() > RENEWAL_MARGIN_MS);\n if (stillGood && !force) return current.token;\n\n return this.renew(force);\n }\n\n private renew(force = false): Promise<string> {\n if (!this.renewing) {\n this.renewing = Promise.resolve(this.config.getTenantSession!(force))\n .then((result) => {\n const token = typeof result === \"string\" ? result : result.token;\n const declared =\n typeof result === \"string\"\n ? undefined\n : (result.expiresAt ??\n (result.expiresIn\n ? Date.now() + result.expiresIn * 1000\n : undefined));\n this.session = { token, expiresAt: declared ?? expiryOf(token) };\n return token;\n })\n .finally(() => {\n this.renewing = undefined;\n });\n }\n return this.renewing;\n }\n\n /**\n * Whether a rejected request is worth retrying, having got a live session.\n *\n * Takes the token the request actually went out with, not the current one:\n * with several requests in flight another may already have replaced it, and\n * comparing against the current one would read that success as a failure.\n *\n * False means the session is dead and cannot be replaced — a cookie set at\n * login, now expired, with nowhere to renew it from. That is worth telling\n * the host application about, once.\n */\n private async recoverSession(rejected: string): Promise<boolean> {\n if (this.session && this.session.token !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n let fresh: string | undefined;\n try {\n // Forced: whatever is cached upstream is the token that was just\n // refused, so asking for it again would only confirm the refusal.\n fresh = await this.renew(true);\n } catch {\n fresh = undefined;\n }\n if (fresh && fresh !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n if (!this.expiryReported) {\n this.expiryReported = true;\n this.config.onSessionExpired?.();\n }\n return false;\n }\n\n /**\n * Make an authenticated request to the API\n */\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n isRetry = false,\n ): Promise<T> {\n const url = `${this.config.baseUrl}${endpoint}`;\n const credential = await this.authorization();\n\n const headers: HeadersInit = {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n ...options.headers,\n };\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n // A session can die between being checked and being used — a clock adrift,\n // a tab asleep for an hour, the key revoked. One retry with a fresh token\n // turns that into a pause instead of a broken conversation.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.request<T>(endpoint, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: ApiError;\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n throw new DevicApiError(errorData);\n }\n\n // Handle responses that may have a wrapper structure\n const data = await response.json();\n\n // If the response has a data property, extract it (common wrapper pattern)\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data as T;\n }\n\n return data as T;\n }\n\n /**\n * Get all assistant specializations\n */\n async getAssistants(external = false): Promise<AssistantSpecialization[]> {\n const query = external ? \"?external=true\" : \"\";\n return this.request<AssistantSpecialization[]>(\n `/api/v1/assistants${query}`,\n );\n }\n\n /**\n * Get a specific assistant specialization\n */\n async getAssistant(identifier: string): Promise<AssistantSpecialization> {\n return this.request<AssistantSpecialization>(\n `/api/v1/assistants/${identifier}`,\n );\n }\n\n /**\n * Send a message to an assistant (sync mode)\n */\n async sendMessage(\n assistantId: string,\n dto: ProcessMessageDto,\n signal?: AbortSignal,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/messages${dto.skipSummarization ? \"?skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n signal,\n },\n );\n }\n\n /**\n * Send a message to an assistant (async mode)\n */\n async sendMessageAsync(\n assistantId: string,\n dto: ProcessMessageDto,\n ): Promise<AsyncResponse> {\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/messages?async=true${dto.skipSummarization ? \"&skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n },\n );\n }\n\n /**\n * Get the list of unique tags used across this account's chat histories.\n * Backed by GET /api/v1/assistants/tags. Useful for autocompletion / filters.\n */\n async getChatTags(): Promise<string[]> {\n return this.request<string[]>(`/api/v1/assistants/tags`);\n }\n\n /**\n * Get real-time chat history (for polling in async mode)\n */\n async getRealtimeHistory(\n assistantId: string,\n chatUid: string,\n ): Promise<RealtimeChatHistory> {\n return this.request<RealtimeChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/realtime`,\n );\n }\n\n /**\n * Get chat history for a specific conversation\n */\n async getChatHistory(\n assistantId: string,\n chatUid: string,\n options?: { tenantId?: string },\n ): Promise<ChatHistory> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n const query = params.toString();\n return this.request<ChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * List conversations for an assistant\n */\n async listConversations(\n assistantId: string,\n options?: {\n tenantId?: string;\n subtenantId?: string;\n offset?: number;\n limit?: number;\n },\n ): Promise<ListConversationsResponse> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n if (options?.subtenantId) {\n params.set(\"subtenantId\", options.subtenantId);\n }\n if (options?.offset != null) {\n params.set(\"offset\", String(options.offset));\n }\n if (options?.limit != null) {\n params.set(\"limit\", String(options.limit));\n }\n params.set(\"omitContent\", \"true\");\n const query = params.toString();\n return this.request<ListConversationsResponse>(\n `/api/v1/assistants/${assistantId}/chats${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * Send tool call responses back to the assistant\n */\n async sendToolResponses(\n assistantId: string,\n chatUid: string,\n responses: ToolCallResponse[],\n ): Promise<AsyncResponse> {\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/tool-response`,\n {\n method: \"POST\",\n body: JSON.stringify({ responses }),\n },\n );\n }\n\n /**\n * Submit feedback for a chat message\n */\n async submitChatFeedback(\n assistantId: string,\n chatUid: string,\n data: FeedbackSubmission,\n ): Promise<FeedbackEntry> {\n return this.request<FeedbackEntry>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n {\n method: \"POST\",\n body: JSON.stringify(data),\n },\n );\n }\n\n /**\n * Get all feedback for a chat\n */\n async getChatFeedback(\n assistantId: string,\n chatUid: string,\n ): Promise<FeedbackEntry[]> {\n return this.request<FeedbackEntry[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n );\n }\n\n /**\n * Get an agent thread by ID\n */\n async getThreadById(\n threadId: string,\n withTasks = false,\n ): Promise<AgentThreadDto> {\n const query = withTasks ? \"?withTasks=true\" : \"\";\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}${query}`,\n );\n }\n\n /**\n * Get agent details\n */\n async getAgentDetails(agentId: string): Promise<AgentDto> {\n return this.request<AgentDto>(`/api/v1/agents/${agentId}`);\n }\n\n /**\n * Get an AI-generated explanation of a thread's execution\n */\n async explainAgentThread(threadId: string): Promise<string> {\n return this.request<string>(\n `/api/v1/agents/threads/${threadId}/explain`,\n );\n }\n\n /**\n * Pause or resume a thread\n */\n async pauseResumeThread(\n threadId: string,\n action: \"paused\" | \"queued\",\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/pause-resume`,\n {\n method: \"POST\",\n body: JSON.stringify({ action }),\n },\n );\n }\n\n /**\n * Handle thread approval (approve/reject)\n */\n async handleThreadApproval(\n threadId: string,\n approved: boolean,\n retry: boolean,\n message: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/approval`,\n {\n method: \"POST\",\n body: JSON.stringify({\n action: approved ? \"approved\" : \"rejected\",\n message,\n retry,\n }),\n },\n );\n }\n\n /**\n * Manually complete a thread\n */\n async completeThread(\n threadId: string,\n completionState: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/complete`,\n {\n method: \"POST\",\n body: JSON.stringify({ state: completionState }),\n },\n );\n }\n\n /**\n * Continue an existing thread with a new user message. The backend decides how\n * to apply it based on the thread state: a finished/failed/waiting thread is\n * re-queued and re-run with the message appended, while a running/queued thread\n * receives it on its next turn (right after the pending tool response). Returns\n * the updated thread.\n */\n async sendThreadMessage(\n threadId: string,\n message: string | Record<string, unknown>,\n ): Promise<AgentThreadDto> {\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}/messages`,\n {\n method: \"POST\",\n body: JSON.stringify({ message }),\n },\n );\n }\n\n /**\n * Stop an in-progress async chat.\n * The current LLM call or tool execution will finish, then the chat\n * will be marked as completed with the history accumulated so far.\n */\n async stopChat(\n assistantId: string,\n chatUid: string,\n ): Promise<{ chatUid: string; message: string }> {\n return this.request<{ chatUid: string; message: string }>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/stop`,\n { method: \"POST\" },\n );\n }\n\n /**\n * Upload a file and get a download URL\n */\n async uploadFile(\n file: File,\n isRetry = false,\n ): Promise<{ name: string; downloadUrl: string; fileType: string }> {\n const url = `${this.config.baseUrl}/api/v1/files/upload`;\n\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n // The FormData is rebuilt from `file` on the way back in, so unlike a\n // consumed stream this retry is safe.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) return this.uploadFile(file, true);\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Transcribe audio to text using the /whisper endpoint.\n * Accepts either an audio binary (Blob/File, sent as multipart/form-data) or\n * a download URL string (sent as `audioUrl`). The backend stores the binary\n * and runs speech-to-text with Devic's own OpenAI key. Returns the text and a\n * `transcriptId` to attach to the resulting message.\n */\n async transcribeAudio(\n audio: Blob | string,\n options?: {\n language?: string;\n messageUid?: string;\n chatUid?: string;\n tenantId?: string;\n fileName?: string;\n },\n isRetry = false,\n ): Promise<WhisperTranscriptionResponse> {\n const url = `${this.config.baseUrl}/api/v1/whisper`;\n\n const formData = new FormData();\n if (typeof audio === \"string\") {\n formData.append(\"audioUrl\", audio);\n } else {\n formData.append(\"audio\", audio, options?.fileName || \"recording.webm\");\n }\n if (options?.language) formData.append(\"language\", options.language);\n if (options?.messageUid) formData.append(\"messageUid\", options.messageUid);\n if (options?.chatUid) formData.append(\"chatUid\", options.chatUid);\n if (options?.tenantId) formData.append(\"tenantId\", options.tenantId);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.transcribeAudio(audio, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Fetch a single speech-to-text transcript by its id (the `transcriptId`\n * stored on a message). Returns the transcribed text and the download URL of\n * the source audio so the chat can offer playback of a dictated message.\n */\n async getTranscript(\n transcriptId: string,\n ): Promise<WhisperTranscriptionResponse> {\n return this.request<WhisperTranscriptionResponse>(\n `/api/v1/whisper/${encodeURIComponent(transcriptId)}`,\n );\n }\n\n /**\n * Get chat history content (full conversation after handoff)\n */\n async getChatHistoryContent(\n assistantId: string,\n chatUid: string,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/content`,\n );\n }\n\n /**\n * Get the current usage limits + consumption for a tenant (or a specific\n * subtenant). Read-only — backed by `GET /api/v1/tenant-usage/:tenantId`\n * (or `/:tenantId/subtenants/:subtenantId`), which is part of the devic-ui\n * key preset. Returns the effective rules with their live consumption and the\n * active tier. Use it to render a usage bar.\n */\n async getTenantUsage(\n tenantId: string,\n subtenantId?: string,\n ): Promise<TenantUsage> {\n const path = subtenantId\n ? `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/subtenants/${encodeURIComponent(subtenantId)}`\n : `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}`;\n return this.request<TenantUsage>(path);\n }\n\n /**\n * Get the durable per-window usage history for a tenant (or subtenant).\n * Read-only — backed by `GET /api/v1/tenant-usage/:tenantId/history`.\n */\n async getTenantUsageHistory(\n tenantId: string,\n options?: TenantUsageHistoryQuery,\n ): Promise<TenantUsageHistoryRow[]> {\n const params = new URLSearchParams();\n if (options?.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options?.scope) params.set(\"scope\", options.scope);\n if (options?.metric) params.set(\"metric\", options.metric);\n if (options?.windowUnit) params.set(\"windowUnit\", options.windowUnit);\n if (options?.from != null) params.set(\"from\", String(options.from));\n if (options?.to != null) params.set(\"to\", String(options.to));\n if (options?.limit != null) params.set(\"limit\", String(options.limit));\n if (options?.skip != null) params.set(\"skip\", String(options.skip));\n const query = params.toString();\n return this.request<TenantUsageHistoryRow[]>(\n `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/history${query ? `?${query}` : \"\"}`,\n );\n }\n\n private coreMemoryPath(\n assistantId: string,\n tenantId?: string,\n subtenantId?: string,\n entryId?: number,\n ): string {\n const params = new URLSearchParams();\n if (tenantId) params.set(\"tenantId\", tenantId);\n if (subtenantId) params.set(\"subtenantId\", subtenantId);\n const query = params.toString();\n return `/api/v1/memory/assistants/${encodeURIComponent(assistantId)}/core${\n entryId != null ? `/${entryId}` : \"\"\n }${query ? `?${query}` : \"\"}`;\n }\n\n /**\n * Core memory entries of the bucket the assistant resolves for a\n * tenant/subtenant combination — what the assistant permanently remembers\n * there. `enabled: false` when the assistant has no core memory tier.\n */\n async getCoreMemory(\n assistantId: string,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryList> {\n return this.request<CoreMemoryList>(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n );\n }\n\n /** Add a standing core memory entry to the assistant's resolved bucket. */\n async addCoreMemoryEntry(\n assistantId: string,\n entry: { content: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ entry?: CoreMemoryEntry; deduped: boolean }> {\n return this.request(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n { method: \"POST\", body: JSON.stringify(entry) },\n );\n }\n\n /** Edit the text, section or pinned flag of a core memory entry. */\n async updateCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n patch: { content?: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryEntry> {\n return this.request<CoreMemoryEntry>(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"PATCH\", body: JSON.stringify(patch) },\n );\n }\n\n /** Remove (archive) a core memory entry. */\n async deleteCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ removed: boolean; id?: number }> {\n return this.request(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"DELETE\" },\n );\n }\n\n // ── Connected apps of the end user ────────────────────────────────\n //\n // Backed by `/api/v1/tenant-integrations`: the tenant is resolved on the\n // server and never taken from the path. The tenant/subtenant sent here\n // identify the end user in front of the widget, so one tenant's accounts are\n // never reachable from another's.\n\n private integrationsQuery(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n }): string {\n const params = new URLSearchParams({ assistantId: options.assistantId });\n if (options.tenantId) params.set(\"tenantId\", options.tenantId);\n if (options.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options.returnTo) params.set(\"returnTo\", options.returnTo);\n return params.toString();\n }\n\n /** Apps this assistant offers, with the end user's own connection status. */\n async getIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<Integration[]> {\n return this.request<Integration[]>(\n `/api/v1/tenant-integrations?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * How this app can be connected, and what it asks the end user for.\n *\n * Scoped like everything else here: the schemes of an app this assistant\n * does not offer cannot be read by asking for them.\n */\n async getIntegrationAuth(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ schemes: IntegrationAuthScheme[] }> {\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/auth?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * Connects an account, in one of two ways.\n *\n * `connected: true` means it is done: the app authenticates with a key the\n * user supplied, so there is nobody to authorise with. Otherwise\n * `authorizationUrl` must be opened in a popup.\n *\n * `returnTo` is where the callback posts the result back to, and the server\n * refuses any value that does not match the origin this request came from —\n * so it cannot be turned into an open redirector.\n *\n * Rejects with a `DevicApiError` carrying `setupRequired` when the app needs\n * values that were not sent.\n */\n async connectIntegration(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n /** Which scheme to use, from {@link getIntegrationAuth}. */\n authScheme?: string;\n /** This account's own values: its API key, its subdomain. */\n accountFields?: Record<string, string>;\n },\n ): Promise<{ connected: boolean; authorizationUrl?: string }> {\n const { authScheme, accountFields, ...query } = options;\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/connect?${this.integrationsQuery(query)}`,\n {\n method: \"POST\",\n body: JSON.stringify({ authScheme, accountFields }),\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n /** Disconnects one of the end user's own accounts. */\n async disconnectIntegration(\n accountId: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ disconnected: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/accounts/${encodeURIComponent(accountId)}?${this.integrationsQuery(options)}`,\n { method: \"DELETE\" },\n );\n }\n\n /**\n * Drops the server's short-lived cache of the end user's connections.\n *\n * Called right after the OAuth popup closes: without it the freshly connected\n * app would keep reading as disconnected until the cache expires, which looks\n * like the connection silently failed.\n */\n async refreshIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<{ refreshed: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/refresh?${this.integrationsQuery(options)}`,\n { method: \"POST\" },\n );\n }\n}\n\n/**\n * Custom error class for API errors\n */\nexport class DevicApiError extends Error {\n public statusCode: number;\n public errorType?: string;\n /** Structured error details (e.g. usage-limit blocking info on a 429). */\n public details?: any;\n /** What connecting an app is still waiting for, when that is why it failed.\n * Carried whole because the fields *are* the form to render. */\n public setupRequired?: IntegrationSetupRequired;\n\n constructor(error: ApiError) {\n super(error.message);\n this.name = \"DevicApiError\";\n this.statusCode = error.statusCode;\n this.errorType = error.error;\n this.details = error.details;\n if ((error as any)?.code === \"INTEGRATION_SETUP_REQUIRED\") {\n this.setupRequired = error as unknown as IntegrationSetupRequired;\n }\n }\n}\n"],"names":[],"mappings":"AA6EA;AACA,MAAM,iBAAiB,GAAG,KAAM;AAEhC;;;;;;AAMG;AACH,SAAS,QAAQ,CAAC,KAAa,EAAA;AAC7B,IAAA,IAAI;QACF,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACnC,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,SAAS;QAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAChE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG;AACjC,QAAA,OAAO,OAAO,GAAG,KAAK,QAAQ,GAAG,GAAG,GAAG,IAAI,GAAG,SAAS;IACzD;AAAE,IAAA,MAAM;AACN,QAAA,OAAO,SAAS;IAClB;AACF;AAEA;;AAEG;MACU,cAAc,CAAA;AAQzB,IAAA,WAAA,CAAY,MAA4B,EAAA;;QAFhC,IAAA,CAAA,cAAc,GAAG,KAAK;AAG5B,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;IACtB;AAEA;;A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"],"sourcesContent":["import type {\n ProcessMessageDto,\n ChatMessage,\n AsyncResponse,\n RealtimeChatHistory,\n ChatHistory,\n AssistantSpecialization,\n ApiError,\n ToolCallResponse,\n ConversationSummary,\n ListConversationsResponse,\n FeedbackSubmission,\n FeedbackEntry,\n AgentThreadDto,\n AgentDto,\n WhisperTranscriptionResponse,\n TenantUsage,\n TenantUsageHistoryRow,\n TenantUsageHistoryQuery,\n CoreMemoryList,\n CoreMemoryEntry,\n Integration,\n IntegrationAuthScheme,\n IntegrationSetupRequired,\n ModelInterfaceToolSchema,\n} from \"./types\";\n\n/**\n * A tenant session, as the integrator's backend hands it over.\n *\n * A bare string is accepted too — the expiry is then read out of the token\n * itself, so the simplest possible source still gets proactive renewal.\n */\nexport interface TenantSessionToken {\n token: string;\n /** Epoch milliseconds. */\n expiresAt?: number;\n /** Seconds from now. Used when `expiresAt` is absent. */\n expiresIn?: number;\n}\n\nexport interface DevicApiClientConfig {\n /**\n * The public API key. Optional when `getTenantSession` is supplied — a page\n * using tenant sessions has no reason to carry one.\n */\n apiKey?: string;\n baseUrl: string;\n /**\n * Where the tenant session comes from.\n *\n * Supplying this changes what the tenant IS: with an API key alone the tenant\n * is whatever the page says it is, and the page can say anything. With a\n * session it is what your server signed.\n *\n * A function rather than a value because it is called again on its own —\n * before the token expires and after the API rejects one. It does not have to\n * reach your backend: reading a cookie your login already set is a perfectly\n * good answer, and then the whole thing is `async () => readCookie(…)`.\n *\n * It is called with `force: true` when the API has just rejected the token in\n * hand, meaning a cached answer is known to be dead. Your own function can\n * ignore the argument — `DevicProvider` uses it to share one session across\n * every component without ever serving a refused token back.\n */\n getTenantSession?: (force?: boolean) => Promise<string | TenantSessionToken>;\n /**\n * Called when the session is dead and cannot be replaced — the API rejected\n * it and `getTenantSession` handed back the same expired token.\n *\n * Matters most when the session comes from a cookie with no way to renew it:\n * without this the widget simply stops answering, at the exact moment the\n * user's own login has also expired. Refresh the page, send them to log in,\n * or say something — but say it.\n */\n onSessionExpired?: () => void;\n}\n\n/** Renew this long before expiry, so a request never leaves with a dead token. */\nconst RENEWAL_MARGIN_MS = 60_000;\n\n/**\n * The expiry inside a JWT, in epoch milliseconds.\n *\n * Read rather than required, so the session source can return just the string.\n * Any failure means \"no idea\", and the token is then renewed only when the API\n * rejects it — correct, just less graceful.\n */\nfunction expiryOf(token: string): number | undefined {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return undefined;\n const json = atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const exp = JSON.parse(json)?.exp;\n return typeof exp === \"number\" ? exp * 1000 : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Devic API client using native fetch\n */\nexport class DevicApiClient {\n private config: DevicApiClientConfig;\n private session?: { token: string; expiresAt?: number };\n /** In flight renewal, shared so a burst of calls fetches one token. */\n private renewing?: Promise<string>;\n /** So a page full of widgets reports one expiry, not one per widget. */\n private expiryReported = false;\n\n constructor(config: DevicApiClientConfig) {\n this.config = config;\n }\n\n /**\n * Update client configuration\n */\n setConfig(config: Partial<DevicApiClientConfig>): void {\n const previous = this.config;\n this.config = { ...this.config, ...config };\n // A new session source speaks for a different end user; keeping the old\n // token would show them the previous one's conversations.\n if (\n config.getTenantSession &&\n config.getTenantSession !== previous.getTenantSession\n ) {\n this.session = undefined;\n this.expiryReported = false;\n }\n }\n\n /** The credential for the next request, renewed if it is about to expire. */\n private async authorization(force = false): Promise<string> {\n if (!this.config.getTenantSession) return this.config.apiKey ?? \"\";\n\n const current = this.session;\n const stillGood =\n current &&\n (current.expiresAt === undefined ||\n current.expiresAt - Date.now() > RENEWAL_MARGIN_MS);\n if (stillGood && !force) return current.token;\n\n return this.renew(force);\n }\n\n private renew(force = false): Promise<string> {\n if (!this.renewing) {\n this.renewing = Promise.resolve(this.config.getTenantSession!(force))\n .then((result) => {\n const token = typeof result === \"string\" ? result : result.token;\n const declared =\n typeof result === \"string\"\n ? undefined\n : (result.expiresAt ??\n (result.expiresIn\n ? Date.now() + result.expiresIn * 1000\n : undefined));\n this.session = { token, expiresAt: declared ?? expiryOf(token) };\n return token;\n })\n .finally(() => {\n this.renewing = undefined;\n });\n }\n return this.renewing;\n }\n\n /**\n * Whether a rejected request is worth retrying, having got a live session.\n *\n * Takes the token the request actually went out with, not the current one:\n * with several requests in flight another may already have replaced it, and\n * comparing against the current one would read that success as a failure.\n *\n * False means the session is dead and cannot be replaced — a cookie set at\n * login, now expired, with nowhere to renew it from. That is worth telling\n * the host application about, once.\n */\n private async recoverSession(rejected: string): Promise<boolean> {\n if (this.session && this.session.token !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n let fresh: string | undefined;\n try {\n // Forced: whatever is cached upstream is the token that was just\n // refused, so asking for it again would only confirm the refusal.\n fresh = await this.renew(true);\n } catch {\n fresh = undefined;\n }\n if (fresh && fresh !== rejected) {\n this.expiryReported = false;\n return true;\n }\n\n if (!this.expiryReported) {\n this.expiryReported = true;\n this.config.onSessionExpired?.();\n }\n return false;\n }\n\n /**\n * Make an authenticated request to the API\n */\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n isRetry = false,\n ): Promise<T> {\n const url = `${this.config.baseUrl}${endpoint}`;\n const credential = await this.authorization();\n\n const headers: HeadersInit = {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n ...options.headers,\n };\n\n const response = await fetch(url, {\n ...options,\n headers,\n });\n\n // A session can die between being checked and being used — a clock adrift,\n // a tab asleep for an hour, the key revoked. One retry with a fresh token\n // turns that into a pause instead of a broken conversation.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.request<T>(endpoint, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: ApiError;\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n throw new DevicApiError(errorData);\n }\n\n // Handle responses that may have a wrapper structure\n const data = await response.json();\n\n // If the response has a data property, extract it (common wrapper pattern)\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data as T;\n }\n\n return data as T;\n }\n\n /**\n * Get all assistant specializations\n */\n async getAssistants(external = false): Promise<AssistantSpecialization[]> {\n const query = external ? \"?external=true\" : \"\";\n return this.request<AssistantSpecialization[]>(\n `/api/v1/assistants${query}`,\n );\n }\n\n /**\n * Get a specific assistant specialization\n */\n async getAssistant(identifier: string): Promise<AssistantSpecialization> {\n return this.request<AssistantSpecialization>(\n `/api/v1/assistants/${identifier}`,\n );\n }\n\n /**\n * Send a message to an assistant (sync mode)\n */\n async sendMessage(\n assistantId: string,\n dto: ProcessMessageDto,\n signal?: AbortSignal,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/messages${dto.skipSummarization ? \"?skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n signal,\n },\n );\n }\n\n /**\n * Send a message to an assistant (async mode)\n */\n async sendMessageAsync(\n assistantId: string,\n dto: ProcessMessageDto,\n ): Promise<AsyncResponse> {\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/messages?async=true${dto.skipSummarization ? \"&skipSummarization=true\" : \"\"}`,\n {\n method: \"POST\",\n body: JSON.stringify(dto),\n },\n );\n }\n\n /**\n * Get the list of unique tags used across this account's chat histories.\n * Backed by GET /api/v1/assistants/tags. Useful for autocompletion / filters.\n */\n async getChatTags(): Promise<string[]> {\n return this.request<string[]>(`/api/v1/assistants/tags`);\n }\n\n /**\n * Get real-time chat history (for polling in async mode)\n */\n async getRealtimeHistory(\n assistantId: string,\n chatUid: string,\n ): Promise<RealtimeChatHistory> {\n return this.request<RealtimeChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/realtime`,\n );\n }\n\n /**\n * Get chat history for a specific conversation\n */\n async getChatHistory(\n assistantId: string,\n chatUid: string,\n options?: { tenantId?: string },\n ): Promise<ChatHistory> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n const query = params.toString();\n return this.request<ChatHistory>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * List conversations for an assistant\n */\n async listConversations(\n assistantId: string,\n options?: {\n tenantId?: string;\n subtenantId?: string;\n offset?: number;\n limit?: number;\n },\n ): Promise<ListConversationsResponse> {\n const params = new URLSearchParams();\n if (options?.tenantId) {\n params.set(\"tenantId\", options.tenantId);\n }\n if (options?.subtenantId) {\n params.set(\"subtenantId\", options.subtenantId);\n }\n if (options?.offset != null) {\n params.set(\"offset\", String(options.offset));\n }\n if (options?.limit != null) {\n params.set(\"limit\", String(options.limit));\n }\n params.set(\"omitContent\", \"true\");\n const query = params.toString();\n return this.request<ListConversationsResponse>(\n `/api/v1/assistants/${assistantId}/chats${query ? `?${query}` : \"\"}`,\n );\n }\n\n /**\n * Send tool call responses back to the assistant.\n *\n * `toolSchemas` re-states the client-side tools for the continuation. The\n * API takes them from the first response of the batch, and without them the\n * turn resumes with no client tools at all — the model stops being able to\n * call them after the first round.\n */\n async sendToolResponses(\n assistantId: string,\n chatUid: string,\n responses: ToolCallResponse[],\n toolSchemas?: ModelInterfaceToolSchema[],\n ): Promise<AsyncResponse> {\n const body =\n toolSchemas?.length && responses.length > 0\n ? responses.map((response, index) =>\n index === 0 ? { ...response, tools: toolSchemas } : response,\n )\n : responses;\n\n return this.request<AsyncResponse>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/tool-response`,\n {\n method: \"POST\",\n body: JSON.stringify({ responses: body }),\n },\n );\n }\n\n /**\n * Submit feedback for a chat message\n */\n async submitChatFeedback(\n assistantId: string,\n chatUid: string,\n data: FeedbackSubmission,\n ): Promise<FeedbackEntry> {\n return this.request<FeedbackEntry>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n {\n method: \"POST\",\n body: JSON.stringify(data),\n },\n );\n }\n\n /**\n * Get all feedback for a chat\n */\n async getChatFeedback(\n assistantId: string,\n chatUid: string,\n ): Promise<FeedbackEntry[]> {\n return this.request<FeedbackEntry[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/feedback`,\n );\n }\n\n /**\n * Get an agent thread by ID\n */\n async getThreadById(\n threadId: string,\n withTasks = false,\n ): Promise<AgentThreadDto> {\n const query = withTasks ? \"?withTasks=true\" : \"\";\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}${query}`,\n );\n }\n\n /**\n * Get agent details\n */\n async getAgentDetails(agentId: string): Promise<AgentDto> {\n return this.request<AgentDto>(`/api/v1/agents/${agentId}`);\n }\n\n /**\n * Get an AI-generated explanation of a thread's execution\n */\n async explainAgentThread(threadId: string): Promise<string> {\n return this.request<string>(\n `/api/v1/agents/threads/${threadId}/explain`,\n );\n }\n\n /**\n * Pause or resume a thread\n */\n async pauseResumeThread(\n threadId: string,\n action: \"paused\" | \"queued\",\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/pause-resume`,\n {\n method: \"POST\",\n body: JSON.stringify({ action }),\n },\n );\n }\n\n /**\n * Handle thread approval (approve/reject)\n */\n async handleThreadApproval(\n threadId: string,\n approved: boolean,\n retry: boolean,\n message: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/approval`,\n {\n method: \"POST\",\n body: JSON.stringify({\n action: approved ? \"approved\" : \"rejected\",\n message,\n retry,\n }),\n },\n );\n }\n\n /**\n * Manually complete a thread\n */\n async completeThread(\n threadId: string,\n completionState: string,\n ): Promise<void> {\n return this.request<void>(\n `/api/v1/agents/threads/${threadId}/complete`,\n {\n method: \"POST\",\n body: JSON.stringify({ state: completionState }),\n },\n );\n }\n\n /**\n * Continue an existing thread with a new user message. The backend decides how\n * to apply it based on the thread state: a finished/failed/waiting thread is\n * re-queued and re-run with the message appended, while a running/queued thread\n * receives it on its next turn (right after the pending tool response). Returns\n * the updated thread.\n */\n async sendThreadMessage(\n threadId: string,\n message: string | Record<string, unknown>,\n ): Promise<AgentThreadDto> {\n return this.request<AgentThreadDto>(\n `/api/v1/agents/threads/${threadId}/messages`,\n {\n method: \"POST\",\n body: JSON.stringify({ message }),\n },\n );\n }\n\n /**\n * Stop an in-progress async chat.\n * The current LLM call or tool execution will finish, then the chat\n * will be marked as completed with the history accumulated so far.\n */\n async stopChat(\n assistantId: string,\n chatUid: string,\n ): Promise<{ chatUid: string; message: string }> {\n return this.request<{ chatUid: string; message: string }>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/stop`,\n { method: \"POST\" },\n );\n }\n\n /**\n * Upload a file and get a download URL\n */\n async uploadFile(\n file: File,\n isRetry = false,\n ): Promise<{ name: string; downloadUrl: string; fileType: string }> {\n const url = `${this.config.baseUrl}/api/v1/files/upload`;\n\n const formData = new FormData();\n formData.append(\"file\", file);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n // The FormData is rebuilt from `file` on the way back in, so unlike a\n // consumed stream this retry is safe.\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) return this.uploadFile(file, true);\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Transcribe audio to text using the /whisper endpoint.\n * Accepts either an audio binary (Blob/File, sent as multipart/form-data) or\n * a download URL string (sent as `audioUrl`). The backend stores the binary\n * and runs speech-to-text with Devic's own OpenAI key. Returns the text and a\n * `transcriptId` to attach to the resulting message.\n */\n async transcribeAudio(\n audio: Blob | string,\n options?: {\n language?: string;\n messageUid?: string;\n chatUid?: string;\n tenantId?: string;\n fileName?: string;\n },\n isRetry = false,\n ): Promise<WhisperTranscriptionResponse> {\n const url = `${this.config.baseUrl}/api/v1/whisper`;\n\n const formData = new FormData();\n if (typeof audio === \"string\") {\n formData.append(\"audioUrl\", audio);\n } else {\n formData.append(\"audio\", audio, options?.fileName || \"recording.webm\");\n }\n if (options?.language) formData.append(\"language\", options.language);\n if (options?.messageUid) formData.append(\"messageUid\", options.messageUid);\n if (options?.chatUid) formData.append(\"chatUid\", options.chatUid);\n if (options?.tenantId) formData.append(\"tenantId\", options.tenantId);\n\n const credential = await this.authorization();\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${credential}`,\n \"devic-api-source\": \"ui\",\n },\n body: formData,\n });\n\n if (response.status === 401 && this.config.getTenantSession && !isRetry) {\n if (await this.recoverSession(credential)) {\n return this.transcribeAudio(audio, options, true);\n }\n }\n\n if (!response.ok) {\n let errorData: { statusCode: number; message: string };\n try {\n errorData = await response.json();\n } catch {\n errorData = {\n statusCode: response.status,\n message: response.statusText,\n };\n }\n throw new DevicApiError(errorData);\n }\n\n const data = await response.json();\n if (data && typeof data === \"object\" && \"data\" in data) {\n return data.data;\n }\n return data;\n }\n\n /**\n * Fetch a single speech-to-text transcript by its id (the `transcriptId`\n * stored on a message). Returns the transcribed text and the download URL of\n * the source audio so the chat can offer playback of a dictated message.\n */\n async getTranscript(\n transcriptId: string,\n ): Promise<WhisperTranscriptionResponse> {\n return this.request<WhisperTranscriptionResponse>(\n `/api/v1/whisper/${encodeURIComponent(transcriptId)}`,\n );\n }\n\n /**\n * Get chat history content (full conversation after handoff)\n */\n async getChatHistoryContent(\n assistantId: string,\n chatUid: string,\n ): Promise<ChatMessage[]> {\n return this.request<ChatMessage[]>(\n `/api/v1/assistants/${assistantId}/chats/${chatUid}/content`,\n );\n }\n\n /**\n * Get the current usage limits + consumption for a tenant (or a specific\n * subtenant). Read-only — backed by `GET /api/v1/tenant-usage/:tenantId`\n * (or `/:tenantId/subtenants/:subtenantId`), which is part of the devic-ui\n * key preset. Returns the effective rules with their live consumption and the\n * active tier. Use it to render a usage bar.\n */\n async getTenantUsage(\n tenantId: string,\n subtenantId?: string,\n ): Promise<TenantUsage> {\n const path = subtenantId\n ? `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/subtenants/${encodeURIComponent(subtenantId)}`\n : `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}`;\n return this.request<TenantUsage>(path);\n }\n\n /**\n * Get the durable per-window usage history for a tenant (or subtenant).\n * Read-only — backed by `GET /api/v1/tenant-usage/:tenantId/history`.\n */\n async getTenantUsageHistory(\n tenantId: string,\n options?: TenantUsageHistoryQuery,\n ): Promise<TenantUsageHistoryRow[]> {\n const params = new URLSearchParams();\n if (options?.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options?.scope) params.set(\"scope\", options.scope);\n if (options?.metric) params.set(\"metric\", options.metric);\n if (options?.windowUnit) params.set(\"windowUnit\", options.windowUnit);\n if (options?.from != null) params.set(\"from\", String(options.from));\n if (options?.to != null) params.set(\"to\", String(options.to));\n if (options?.limit != null) params.set(\"limit\", String(options.limit));\n if (options?.skip != null) params.set(\"skip\", String(options.skip));\n const query = params.toString();\n return this.request<TenantUsageHistoryRow[]>(\n `/api/v1/tenant-usage/${encodeURIComponent(tenantId)}/history${query ? `?${query}` : \"\"}`,\n );\n }\n\n private coreMemoryPath(\n assistantId: string,\n tenantId?: string,\n subtenantId?: string,\n entryId?: number,\n ): string {\n const params = new URLSearchParams();\n if (tenantId) params.set(\"tenantId\", tenantId);\n if (subtenantId) params.set(\"subtenantId\", subtenantId);\n const query = params.toString();\n return `/api/v1/memory/assistants/${encodeURIComponent(assistantId)}/core${\n entryId != null ? `/${entryId}` : \"\"\n }${query ? `?${query}` : \"\"}`;\n }\n\n /**\n * Core memory entries of the bucket the assistant resolves for a\n * tenant/subtenant combination — what the assistant permanently remembers\n * there. `enabled: false` when the assistant has no core memory tier.\n */\n async getCoreMemory(\n assistantId: string,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryList> {\n return this.request<CoreMemoryList>(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n );\n }\n\n /** Add a standing core memory entry to the assistant's resolved bucket. */\n async addCoreMemoryEntry(\n assistantId: string,\n entry: { content: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ entry?: CoreMemoryEntry; deduped: boolean }> {\n return this.request(\n this.coreMemoryPath(assistantId, options?.tenantId, options?.subtenantId),\n { method: \"POST\", body: JSON.stringify(entry) },\n );\n }\n\n /** Edit the text, section or pinned flag of a core memory entry. */\n async updateCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n patch: { content?: string; section?: string; pinned?: boolean },\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<CoreMemoryEntry> {\n return this.request<CoreMemoryEntry>(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"PATCH\", body: JSON.stringify(patch) },\n );\n }\n\n /** Remove (archive) a core memory entry. */\n async deleteCoreMemoryEntry(\n assistantId: string,\n entryId: number,\n options?: { tenantId?: string; subtenantId?: string },\n ): Promise<{ removed: boolean; id?: number }> {\n return this.request(\n this.coreMemoryPath(\n assistantId,\n options?.tenantId,\n options?.subtenantId,\n entryId,\n ),\n { method: \"DELETE\" },\n );\n }\n\n // ── Connected apps of the end user ────────────────────────────────\n //\n // Backed by `/api/v1/tenant-integrations`: the tenant is resolved on the\n // server and never taken from the path. The tenant/subtenant sent here\n // identify the end user in front of the widget, so one tenant's accounts are\n // never reachable from another's.\n\n private integrationsQuery(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n }): string {\n const params = new URLSearchParams({ assistantId: options.assistantId });\n if (options.tenantId) params.set(\"tenantId\", options.tenantId);\n if (options.subtenantId) params.set(\"subtenantId\", options.subtenantId);\n if (options.returnTo) params.set(\"returnTo\", options.returnTo);\n return params.toString();\n }\n\n /** Apps this assistant offers, with the end user's own connection status. */\n async getIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<Integration[]> {\n return this.request<Integration[]>(\n `/api/v1/tenant-integrations?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * How this app can be connected, and what it asks the end user for.\n *\n * Scoped like everything else here: the schemes of an app this assistant\n * does not offer cannot be read by asking for them.\n */\n async getIntegrationAuth(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ schemes: IntegrationAuthScheme[] }> {\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/auth?${this.integrationsQuery(options)}`,\n );\n }\n\n /**\n * Connects an account, in one of two ways.\n *\n * `connected: true` means it is done: the app authenticates with a key the\n * user supplied, so there is nobody to authorise with. Otherwise\n * `authorizationUrl` must be opened in a popup.\n *\n * `returnTo` is where the callback posts the result back to, and the server\n * refuses any value that does not match the origin this request came from —\n * so it cannot be turned into an open redirector.\n *\n * Rejects with a `DevicApiError` carrying `setupRequired` when the app needs\n * values that were not sent.\n */\n async connectIntegration(\n app: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n returnTo?: string;\n /** Which scheme to use, from {@link getIntegrationAuth}. */\n authScheme?: string;\n /** This account's own values: its API key, its subdomain. */\n accountFields?: Record<string, string>;\n },\n ): Promise<{ connected: boolean; authorizationUrl?: string }> {\n const { authScheme, accountFields, ...query } = options;\n return this.request(\n `/api/v1/tenant-integrations/${encodeURIComponent(app)}/connect?${this.integrationsQuery(query)}`,\n {\n method: \"POST\",\n body: JSON.stringify({ authScheme, accountFields }),\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n /** Disconnects one of the end user's own accounts. */\n async disconnectIntegration(\n accountId: string,\n options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n },\n ): Promise<{ disconnected: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/accounts/${encodeURIComponent(accountId)}?${this.integrationsQuery(options)}`,\n { method: \"DELETE\" },\n );\n }\n\n /**\n * Drops the server's short-lived cache of the end user's connections.\n *\n * Called right after the OAuth popup closes: without it the freshly connected\n * app would keep reading as disconnected until the cache expires, which looks\n * like the connection silently failed.\n */\n async refreshIntegrations(options: {\n assistantId: string;\n tenantId?: string;\n subtenantId?: string;\n }): Promise<{ refreshed: boolean }> {\n return this.request(\n `/api/v1/tenant-integrations/refresh?${this.integrationsQuery(options)}`,\n { method: \"POST\" },\n );\n }\n}\n\n/**\n * Custom error class for API errors\n */\nexport class DevicApiError extends Error {\n public statusCode: number;\n public errorType?: string;\n /** Structured error details (e.g. usage-limit blocking info on a 429). */\n public details?: any;\n /** What connecting an app is still waiting for, when that is why it failed.\n * Carried whole because the fields *are* the form to render. */\n public setupRequired?: IntegrationSetupRequired;\n\n constructor(error: ApiError) {\n super(error.message);\n this.name = \"DevicApiError\";\n this.statusCode = error.statusCode;\n this.errorType = error.error;\n this.details = error.details;\n if ((error as any)?.code === \"INTEGRATION_SETUP_REQUIRED\") {\n this.setupRequired = error as unknown as IntegrationSetupRequired;\n }\n }\n}\n"],"names":[],"mappings":"AA8EA;AACA,MAAM,iBAAiB,GAAG,KAAM;AAEhC;;;;;;AAMG;AACH,SAAS,QAAQ,CAAC,KAAa,EAAA;AAC7B,IAAA,IAAI;QACF,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACnC,QAAA,IAAI,CAAC,OAAO;AAAE,YAAA,OAAO,SAAS;QAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAChE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG;AACjC,QAAA,OAAO,OAAO,GAAG,KAAK,QAAQ,GAAG,GAAG,GAAG,IAAI,GAAG,SAA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AACG,MAAO,aAAc,SAAQ,KAAK,CAAA;AAStC,IAAA,WAAA,CAAY,KAAe,EAAA;AACzB,QAAA,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC;AACpB,QAAA,IAAI,CAAC,IAAI,GAAG,eAAe;AAC3B,QAAA,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU;AAClC,QAAA,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC,KAAK;AAC5B,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO;AAC5B,QAAA,IAAK,KAAa,EAAE,IAAI,KAAK,4BAA4B,EAAE;AACzD,YAAA,IAAI,CAAC,aAAa,GAAG,KAA4C;QACnE;IACF;AACD;;;;"}
@@ -162,6 +162,12 @@ export interface ToolCallResponse {
162
162
  tool_call_id: string;
163
163
  content: any;
164
164
  role: 'tool';
165
+ /**
166
+ * The client-side tools still on offer for the rest of the turn. The API
167
+ * reads them off the first response of the batch: leaving them out drops
168
+ * the tools from the continuation, so the model cannot call them again.
169
+ */
170
+ tools?: ModelInterfaceToolSchema[];
165
171
  }
166
172
  /**
167
173
  * DTO for sending messages to the assistant