@alquimia-ai/tools 2.5.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +603 -23
- package/dist/actions/index.d.mts +1 -1
- package/dist/actions/index.d.ts +1 -1
- package/dist/adapters/fetch.d.mts +1 -0
- package/dist/adapters/fetch.d.ts +1 -0
- package/dist/adapters/fetch.js +4 -0
- package/dist/adapters/fetch.js.map +1 -1
- package/dist/adapters/fetch.mjs +4 -0
- package/dist/adapters/fetch.mjs.map +1 -1
- package/dist/adapters/index.d.mts +1 -0
- package/dist/adapters/index.d.ts +1 -0
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/next.d.mts +1 -0
- package/dist/adapters/next.d.ts +1 -0
- package/dist/adapters/next.js +4 -0
- package/dist/adapters/next.js.map +1 -1
- package/dist/adapters/next.mjs +4 -0
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/approvals-CcnmqUkQ.d.ts +59 -0
- package/dist/approvals-dn4sd_Ot.d.mts +59 -0
- package/dist/hooks/index.d.mts +36 -5
- package/dist/hooks/index.d.ts +36 -5
- package/dist/hooks/index.js +269 -17
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +269 -17
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/next/index.d.mts +7 -0
- package/dist/next/index.d.ts +7 -0
- package/dist/next/index.js +56 -37
- package/dist/next/index.js.map +1 -1
- package/dist/next/index.mjs +56 -37
- package/dist/next/index.mjs.map +1 -1
- package/dist/providers/index.d.mts +3 -3
- package/dist/providers/index.d.ts +3 -3
- package/dist/{providers-b5_yMyMo.d.ts → providers-J_Z9rQ3Q.d.ts} +1 -1
- package/dist/{providers-DiR9cgyo.d.mts → providers-YKiEag2L.d.mts} +1 -1
- package/dist/proxy.d.mts +2 -0
- package/dist/proxy.d.ts +2 -0
- package/dist/proxy.js +47 -37
- package/dist/proxy.js.map +1 -1
- package/dist/proxy.mjs +47 -37
- package/dist/proxy.mjs.map +1 -1
- package/dist/sdk/index.d.mts +60 -5
- package/dist/sdk/index.d.ts +60 -5
- package/dist/sdk/index.js +115 -15
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/index.mjs +115 -15
- package/dist/sdk/index.mjs.map +1 -1
- package/dist/services/index.d.mts +1 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/{type-xksRnBUW.d.ts → type-BFtGEEb4.d.ts} +45 -1
- package/dist/{type-DqX3-9QS.d.mts → type-C_sKpIM1.d.mts} +45 -1
- package/dist/types/index.d.mts +28 -5
- package/dist/types/index.d.ts +28 -5
- package/dist/types/index.js.map +1 -1
- package/dist/types/index.mjs.map +1 -1
- package/dist/{types-C-6fgK1_.d.mts → types-lOliroPw.d.mts} +1 -1
- package/dist/{types-C-6fgK1_.d.ts → types-lOliroPw.d.ts} +1 -1
- package/dist/utils/index.d.mts +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/worklog/index.d.mts +3 -2
- package/dist/worklog/index.d.ts +3 -2
- package/dist/worklog/index.js +94 -2
- package/dist/worklog/index.js.map +1 -1
- package/dist/worklog/index.mjs +94 -2
- package/dist/worklog/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/hooks/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/alquimia.hook.tsx","../../src/sdk/alquimia-sdk.ts","../../src/utils/utils.ts","../../src/worklog/types.ts","../../src/worklog/registry.ts","../../src/worklog/reducer.ts","../../src/worklog/use-worklog.ts","../../src/worklog/from-frame.ts","../../src/hooks/pending-client-tool.ts","../../src/genui/style.ts","../../src/genui/registry.ts","../../src/genui/catalog.ts","../../src/genui/actions.ts","../../src/genui/validate.ts","../../src/genui/tool-schema.ts","../../src/genui/clause.ts","../../src/genui/emit.ts","../../src/hooks/useRatings.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport AlquimiaSDK from '../sdk/alquimia-sdk';\nimport type { AlquimiaAdapter } from '../adapters';\nimport {\n WhisperProvider,\n StableDiffusionProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport {\n AIMessageChunk,\n AlquimiaMessage,\n AlquimiaEventData,\n AssistantInferenceResponse,\n ToolEvent,\n GenuiSurfaceItem,\n} from '../types/type';\nimport { createMessageId, mergeThinkingsByControlId, mergeToolEvents, resolveGenuiAllow } from '../utils';\nimport { reduceWorklog, initialWorklogState, frameToRecord, type WorklogState } from '../worklog';\nimport { extractPendingClientTool, type PendingClientTool } from './pending-client-tool';\nimport type { ToolExecutionResponse, UIAction, CatalogManifest } from '../genui';\nimport {\n validateSurface,\n buildRenderUiSchema,\n buildGenuiClause,\n coreCatalog,\n buildSurfaceResult,\n buildDismissResult,\n} from '../genui';\n\nexport interface UseAlquimiaConfig {\n assistantId: string;\n adapter: AlquimiaAdapter;\n providers?: {\n whisper?: WhisperProvider;\n stableDiffusion?: StableDiffusionProvider;\n characterization?: CharacterizationProvider;\n ratings?: RatingsProvider;\n logger?: LoggerProvider;\n };\n options?: {\n enforceCharacterization?: boolean;\n userId?: string;\n extraInstructions?: Record<string, string>;\n worklog?: boolean;\n };\n genui?: {\n catalog?: CatalogManifest;\n allow?: string[] | 'all';\n source?: 'client' | 'agent';\n };\n}\n\n\nexport function useAlquimia(config: UseAlquimiaConfig) {\n const sdk = useMemo(() => {\n const instance = new AlquimiaSDK(config.assistantId, config.adapter, {\n enforceCharacterization: config.options?.enforceCharacterization,\n });\n\n if (config.providers?.whisper) instance.withWhisperProvider(config.providers.whisper);\n if (config.providers?.stableDiffusion) instance.withStableDiffusionProvider(config.providers.stableDiffusion);\n if (config.providers?.characterization) instance.withAnalyzeCharacterizationProvider(config.providers.characterization);\n if (config.providers?.ratings) instance.withRatingsProvider(config.providers.ratings);\n if (config.providers?.logger) instance.withLoggerProvider(config.providers.logger);\n if (config.options?.userId) instance.withUserId(config.options.userId);\n if (config.options?.extraInstructions) instance.withExtraInstructions(config.options.extraInstructions);\n\n if (config.genui && (config.genui.source ?? 'client') === 'client') {\n const cat = config.genui.catalog ?? coreCatalog;\n const allow = resolveGenuiAllow(cat, config.genui.allow);\n instance.withTools([buildRenderUiSchema(cat, allow)]);\n instance.withExtraInstructions({\n ...(config.options?.extraInstructions ?? {}),\n genui: buildGenuiClause(cat, allow),\n });\n }\n\n return instance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [config.assistantId, config.adapter]);\n\n const [input, setInput] = useState<string>('');\n const [isMessageLoading, setIsMessageLoading] = useState<boolean>(false);\n const [isStreamingLoading, setIsStreamingLoading] = useState<boolean>(false);\n const [isMessageStreaming, setIsMessageStreaming] = useState<boolean>(false);\n const [streamingMessageId, setStreamingMessageId] = useState<string | null>(null);\n const [isAudioRecording, setIsAudioRecording] = useState<boolean>(false);\n const [messages, setMessages] = useState<AlquimiaMessage[]>([]);\n const eventSourceRef = useRef<EventSource | null>(null);\n const streamUserCancelledRef = useRef(false);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [activeTool, setActiveTool] = useState<any | null>(null);\n const [lastRequest, setLastRequest] = useState<string | null>(null);\n const [hasThinkings, setHasThinkings] = useState<boolean>(false);\n const worklogEnabled = config.options?.worklog ?? false;\n const [worklog, setWorklog] = useState<WorklogState | undefined>(\n worklogEnabled ? initialWorklogState() : undefined\n );\n const [attachments, setAttachments] = useState<File[]>([]);\n const [isUploadingAttachments, setIsUploadingAttachments] = useState<boolean>(false);\n const [pendingClientTool, setPendingClientTool] = useState<PendingClientTool | null>(null);\n // Tracks control_ids already completed so a re-render never double-submits.\n const completedToolsRef = useRef<Set<string>>(new Set());\n // GenUI surface lifecycle state.\n const genuiCatalog = config.genui?.catalog ?? coreCatalog;\n const [genuiSurfaces, setGenuiSurfaces] = useState<GenuiSurfaceItem[]>([]);\n const messagesLenRef = useRef(0);\n messagesLenRef.current = messages.length;\n // Anchor a surface right after the last USER message — BEFORE any assistant output\n // (including the streaming placeholder). Otherwise the surface anchors after the\n // placeholder and the agent's reply (and its loader) render ABOVE the surface.\n const genuiAnchorRef = useRef(0);\n {\n let anchor = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n if ((messages[i] as { role?: string }).role === 'user') {\n anchor = i + 1;\n break;\n }\n }\n genuiAnchorRef.current = anchor;\n }\n\n const isLoading = isMessageLoading || isStreamingLoading || isUploadingAttachments;\n\n function cleanMessages() {\n setMessages([]);\n setHasThinkings(false);\n }\n\n function addAttachment(file: File) {\n setAttachments((prev) => [...prev, file]);\n }\n\n function addAttachments(files: File[]) {\n setAttachments((prev) => [...prev, ...files]);\n }\n\n function removeAttachment(index: number) {\n setAttachments((prev) => prev.filter((_, i) => i !== index));\n }\n\n function clearAttachments() {\n setAttachments([]);\n }\n\n function processMessageChunk(\n messageId: string,\n chunk: string,\n error_code?: string,\n error_detail?: string,\n taskid?: string,\n additionalInfo?: string,\n loading?: boolean,\n tooler?: ToolEvent[],\n thinkings?: any[]\n ) {\n setMessages((currentMessages) => {\n const messageIndex = currentMessages.findIndex((message) => message?.id === messageId);\n if (messageIndex !== -1) {\n const updatedMessages = [...currentMessages];\n const updatedMessage: AlquimiaMessage = {\n ...updatedMessages[messageIndex],\n content: `${updatedMessages[messageIndex]?.content || ''}${chunk}`,\n id: updatedMessages[messageIndex]?.id || '',\n role: updatedMessages[messageIndex]?.role || 'assistant',\n error_code,\n error_detail,\n taskid,\n additionalInfo,\n created_at: new Date().getTime().toString(),\n loading,\n tooler: mergeToolEvents(updatedMessages[messageIndex]?.tooler || [], tooler),\n thinkings: mergeThinkingsByControlId(\n updatedMessages[messageIndex]?.thinkings || [],\n thinkings || []\n ),\n };\n updatedMessages[messageIndex] = updatedMessage;\n return updatedMessages;\n } else {\n return [\n ...currentMessages,\n {\n content: `${chunk}`,\n role: 'assistant',\n id: messageId,\n error_code,\n error_detail,\n taskid,\n created_at: new Date().getTime().toString(),\n loading,\n tooler: mergeToolEvents([], tooler),\n thinkings,\n },\n ];\n }\n });\n }\n\n async function processAndSendMessage(\n message: string,\n options?: {\n messageType?: string;\n traceParentId?: string;\n sessionId?: string;\n additionalInfo?: string;\n }\n ) {\n addUserMessage(message, options?.messageType);\n\n const messageId = createMessageId();\n setStreamingMessageId(messageId);\n\n await sendMessage(\n message,\n (chunk: AIMessageChunk) => {\n processMessageChunk(\n messageId,\n chunk?.answer || '',\n chunk?.error_code,\n chunk?.error_detail,\n chunk?.taskid,\n options?.additionalInfo,\n chunk?.loading,\n chunk?.tooler,\n chunk?.thinkings\n );\n },\n options?.traceParentId,\n options?.sessionId\n );\n\n setInput('');\n }\n\n async function handleSubmit(\n event: React.FormEvent<HTMLFormElement>,\n traceParentId?: string,\n sessionId?: string,\n additionalInfo?: string\n ) {\n setIsMessageLoading(true);\n event.preventDefault();\n\n if (input) {\n await processAndSendMessage(input, { traceParentId, sessionId, additionalInfo });\n }\n\n setIsMessageLoading(false);\n }\n\n async function handleSystemMessage(\n message: string,\n options?: {\n traceParentId?: string;\n sessionId?: string;\n additionalInfo?: string;\n messageType?: string;\n }\n ) {\n setIsMessageLoading(true);\n\n await processAndSendMessage(message, {\n messageType: options?.messageType || 'system',\n traceParentId: options?.traceParentId,\n sessionId: options?.sessionId,\n additionalInfo: options?.additionalInfo,\n });\n\n setIsMessageLoading(false);\n }\n\n function handleInputChange(event: React.ChangeEvent<HTMLTextAreaElement>) {\n setInput(event.target.value);\n }\n\n function handleReplaceInput(input: string) {\n setInput(input);\n }\n\n function populateMessages(messages: AlquimiaMessage[]) {\n setMessages(messages);\n }\n\n function handleLoadingCancel() {\n streamUserCancelledRef.current = true;\n eventSourceRef.current?.close();\n eventSourceRef.current = null;\n setIsMessageLoading(false);\n setIsMessageStreaming(false);\n setStreamingMessageId(null);\n setIsStreamingLoading(false);\n setIsUploadingAttachments(false);\n setInput('');\n }\n\n function addUserMessage(message: string, type?: string) {\n setMessages((prevMessages: AlquimiaMessage[]) => [\n ...prevMessages,\n {\n content: message,\n role: 'user',\n type: type,\n id: createMessageId(),\n created_at: new Date().getTime().toString(),\n },\n ]);\n }\n\n function getCookie(name: string): string | null {\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const [cookieName, cookieValue] = cookie.trim().split('=');\n if (cookieName === name) {\n return decodeURIComponent(cookieValue as string);\n }\n }\n return null;\n }\n\n function cleanup(isStreaming: boolean, event: EventSource) {\n setIsMessageStreaming(isStreaming);\n setStreamingMessageId(null);\n setIsStreamingLoading(false);\n event.close();\n }\n\n async function sendMessage(\n message: string,\n callBack: (_chunk: AIMessageChunk) => void,\n traceParentId?: string,\n sessionId?: string\n ) {\n setIsStreamingLoading(true);\n callBack({ type: 'loading', loading: true });\n const conversationId = sessionId || getCookie('alquimia-session');\n setIsMessageStreaming(true);\n setActiveTool(null);\n setLastRequest(message);\n\n try {\n const hasAttachments = attachments.length > 0;\n const sdkCall = sdk.withConversationId(conversationId || '');\n\n if (hasAttachments) {\n sdkCall.withAttachments(\n attachments.map((f) => ({\n filename: f.name,\n content_type: f.type,\n content_size: f.size,\n }))\n );\n }\n\n const response = await sdkCall.sendMessage(message, traceParentId);\n\n if (hasAttachments) {\n setIsUploadingAttachments(true);\n try {\n const attachmentResponses = response.getAttachmentResponses();\n await Promise.all(\n attachments.map((file, i) => response.uploadAttachment(file, attachmentResponses[i]))\n );\n } catch (uploadError: any) {\n setIsUploadingAttachments(false);\n setIsMessageStreaming(false);\n setStreamingMessageId(null);\n setIsStreamingLoading(false);\n callBack({\n type: 'error',\n error_code: 'ATTACHMENT_UPLOAD_ERROR',\n error_detail: uploadError.message || 'Failed to upload attachment',\n });\n return;\n }\n setIsUploadingAttachments(false);\n clearAttachments();\n }\n\n const streamUrl = response.getUrlStream();\n const streamId = response.getStreamId() || '';\n streamUserCancelledRef.current = false;\n const streamState = {\n streamId,\n connectedAt: Date.now(),\n openedAt: null as number | null,\n messagesReceived: 0,\n lastMessageAt: null as number | null,\n closedByClient: false,\n };\n\n if (worklogEnabled) setWorklog(initialWorklogState());\n\n const eventSource = new EventSource(streamUrl);\n eventSourceRef.current = eventSource;\n\n eventSource.onopen = () => {\n streamState.openedAt = Date.now();\n };\n\n eventSource.onmessage = (event) => {\n streamState.messagesReceived++;\n streamState.lastMessageAt = Date.now();\n handleMessageEvent(event, callBack, eventSource, streamState);\n };\n\n eventSource.onerror = () => {\n if (streamState.closedByClient) return;\n if (streamUserCancelledRef.current) {\n streamUserCancelledRef.current = false;\n return;\n }\n\n streamState.closedByClient = true;\n\n const elapsed = Date.now() - streamState.connectedAt;\n const sinceLastMessage = streamState.lastMessageAt\n ? Date.now() - streamState.lastMessageAt\n : null;\n\n cleanup(false, eventSource);\n\n let errorDetail: string;\n if (!streamState.openedAt) {\n errorDetail =\n 'Could not open the live response. Check your connection and try again.';\n } else if (streamState.messagesReceived === 0) {\n errorDetail = 'No response was received. Try again in a moment.';\n } else {\n errorDetail = 'The response was interrupted. Try again.';\n }\n\n if (typeof console !== 'undefined' && console.debug) {\n console.debug('[Alquimia] SSE transport error', {\n streamUrl,\n taskId: streamId,\n opened: Boolean(streamState.openedAt),\n messagesReceived: streamState.messagesReceived,\n elapsedMs: elapsed,\n sinceLastMessageMs: sinceLastMessage,\n });\n }\n\n callBack({\n type: 'error',\n error_code: 'STREAM_ERROR',\n error_detail: errorDetail,\n taskid: streamId,\n });\n };\n } catch (error: any) {\n console.error('Error sending message:', error);\n const errMessage =\n error.response?.data?.detail || error.message || 'Error initiating the stream.';\n setIsUploadingAttachments(false);\n setIsMessageStreaming(false);\n setStreamingMessageId(null);\n callBack({\n type: 'error',\n error_code:\n error.response?.status != null\n ? String(error.response.status)\n : 'REQUEST_ERROR',\n error_detail: errMessage,\n });\n }\n }\n\n function handleMessageEvent(\n event: MessageEvent,\n callBack: (_chunk: AIMessageChunk) => void,\n eventSource: EventSource,\n streamState?: {\n streamId: string;\n closedByClient: boolean;\n messagesReceived: number;\n }\n ) {\n const data: AlquimiaEventData = JSON.parse(event.data);\n if (worklogEnabled) {\n setWorklog((prev) => reduceWorklog(prev ?? initialWorklogState(), frameToRecord(data)));\n }\n\n // A client tool (e.g. render_ui) arrived on the stream. Surface it so the UI\n // can render the A2UI surface and complete it via `completeToolExecution`.\n // Inference is paused server-side until the completion POST lands.\n const pending = extractPendingClientTool(data);\n if (pending) {\n setPendingClientTool(pending);\n return;\n }\n\n const eventTaskId = data.taskid || '';\n\n if (data.errors?.length) {\n for (const error of data.errors) {\n const detail =\n error.error_detail ||\n (error.data != null\n ? `${error.data} (controlId: ${error.control_id})`\n : 'Unknown error');\n callBack({\n type: 'error',\n error_code: error.event_class || error.status || 'UNKNOWN_ERROR',\n error_detail: detail,\n taskid: eventTaskId,\n });\n }\n if (streamState) streamState.closedByClient = true;\n cleanup(false, eventSource);\n return;\n }\n\n if (data.tools_output?.length) {\n callBack({ type: 'answer', answer: '', tooler: data.tools_output });\n }\n\n if (data.thinkings?.length) {\n setHasThinkings(true);\n callBack({ type: 'answer', thinkings: data.thinkings });\n }\n\n if (data.event_class === 'AssistantInferenceResponse') {\n const final = data as AssistantInferenceResponse;\n callBack({ type: 'answer', answer: final.data });\n if (streamState) streamState.closedByClient = true;\n cleanup(false, eventSource);\n }\n }\n\n /**\n * Complete a pending client-tool execution. Interactive `render_ui` surfaces\n * pass the user's data as `result`; display-only surfaces pass `{ shown: true }`.\n * Idempotent per `control_id` (a second call for the same id is a no-op) and\n * stable across renders, so consumers can call it from an effect without\n * guarding against double-submits themselves. Clears the pending state on\n * success so inference can resume.\n */\n const completeToolExecution = useCallback(\n async (controlId: string, result: ToolExecutionResponse) => {\n if (completedToolsRef.current.has(controlId)) return;\n completedToolsRef.current.add(controlId);\n try {\n await sdk.submitToolResult({ ...result, control_id: controlId });\n setPendingClientTool((cur) => (cur?.controlId === controlId ? null : cur));\n } catch (err) {\n // Allow a retry if the submit failed.\n completedToolsRef.current.delete(controlId);\n throw err;\n }\n },\n [sdk],\n );\n\n // ---- GenUI surface lifecycle (only active when config.genui is set) ----\n useEffect(() => {\n if (!config.genui) return;\n if (!pendingClientTool || pendingClientTool.toolName !== 'render_ui') return;\n const { controlId } = pendingClientTool;\n // Stamp the active catalog id if the agent omitted it, so the client always knows\n // which catalog version to render against (Tier 2 authoritative catalogId).\n const parameters =\n pendingClientTool.parameters && typeof pendingClientTool.parameters === 'object'\n ? { catalogId: genuiCatalog.id, ...(pendingClientTool.parameters as Record<string, unknown>) }\n : pendingClientTool.parameters;\n\n const res = validateSurface(parameters, genuiCatalog);\n if (!res.ok || !res.value) {\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'error',\n message:\n 'Surface failed client validation: ' + res.errors.map((e) => `${e.path} ${e.message}`).join('; '),\n result: { errors: res.errors },\n });\n return;\n }\n\n const surface = res.value;\n setGenuiSurfaces((prev) =>\n prev.some((s) => s.controlId === controlId)\n ? prev\n : [...prev, { controlId, surface, afterCount: genuiAnchorRef.current }]\n );\n\n const interactive = surface.components.some((c) => c.action?.wantResponse === true);\n if (!interactive) {\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'success',\n result: {\n shown: true,\n instruction:\n 'The UI is rendered and visible to the user. Do NOT restate it as text/markdown/ASCII; reply with at most one short sentence.',\n },\n });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingClientTool, completeToolExecution, config.genui]);\n\n const genuiOnAgentAction = useCallback(\n (controlId: string) => (action: UIAction) => {\n setGenuiSurfaces((prev) =>\n prev.map((s) => (s.controlId === controlId ? { ...s, submitted: true } : s)),\n );\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'success',\n // Includes componentId, so the agent can tell which element was acted on when\n // several share one action name (a grid of option cards, say).\n result: buildSurfaceResult(action),\n });\n },\n [completeToolExecution],\n );\n\n /**\n * Let the user answer an interactive surface in words instead of using it.\n */\n const genuiDismiss = useCallback(\n (userMessage?: string) => {\n if (!pendingClientTool || pendingClientTool.toolName !== 'render_ui') return;\n const { controlId } = pendingClientTool;\n const said = typeof userMessage === 'string' ? userMessage.trim() : '';\n const item = genuiSurfaces.find((s) => s.controlId === controlId);\n\n setGenuiSurfaces((prev) =>\n prev.map((s) =>\n s.controlId === controlId ? { ...s, submitted: true, dismissedWith: said || undefined } : s,\n ),\n );\n if (said) setInput('');\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'success',\n result: buildDismissResult(item?.surface.surfaceId ?? '', said),\n });\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [pendingClientTool, genuiSurfaces, completeToolExecution],\n );\n\n const genuiAwaitingUser = !!(\n pendingClientTool &&\n pendingClientTool.toolName === 'render_ui' &&\n genuiSurfaces.some(\n (s) =>\n s.controlId === pendingClientTool.controlId &&\n s.surface.components.some((c) => c.action?.wantResponse === true),\n )\n );\n\n const genui = config.genui\n ? {\n surfaces: genuiSurfaces,\n onAgentAction: genuiOnAgentAction,\n awaitingUser: genuiAwaitingUser,\n dismiss: genuiDismiss,\n }\n : undefined;\n\n return {\n sdk,\n activeTool,\n pendingClientTool,\n completeToolExecution,\n genui,\n cleanMessages,\n createMessageId,\n handleInputChange,\n handleReplaceInput,\n handleSubmit,\n handleSystemMessage,\n handleLoadingCancel,\n input,\n isLoading,\n isMessageLoading,\n isMessageStreaming,\n isStreamingLoading,\n streamingMessageId,\n isAudioRecording,\n lastRequest,\n messages,\n populateMessages,\n processMessageChunk,\n sendMessage,\n sessionId,\n setActiveTool,\n setSessionId,\n setLastRequest,\n setIsAudioRecording,\n hasThinkings,\n worklog,\n attachments,\n addAttachment,\n addAttachments,\n removeAttachment,\n clearAttachments,\n isUploadingAttachments,\n };\n}\n","import axios, { AxiosInstance } from 'axios';\nimport {\n StableDiffusionProvider,\n WhisperProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport { AttachmentPayload, TTSResult, type CommonAttributes } from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\n\nclass AlquimiaSDK {\n private adapter: AlquimiaAdapter;\n private assistantId: string;\n private axiosInstance: AxiosInstance;\n private conversationId: string | null = null;\n private sessionId: string | null = null;\n // Internal subscription id from infer (`taskid` on the wire).\n private streamId: string | null = null;\n // W3C traceparent for the current turn, so infer and stream share one trace.\n private traceParent: string | null = null;\n private tools: any = [];\n private extraInstructions: Record<string, string> | null = null;\n private assistantConfig: any = null;\n private userId: string | null = null;\n private whisperProvider?: WhisperProvider;\n private stableDiffusionProvider?: StableDiffusionProvider;\n private analyzeCharacterizationProvider?: CharacterizationProvider;\n private ratingsProvider?: RatingsProvider;\n private loggerProvider?: LoggerProvider;\n private enforceCharacterization?: boolean;\n private attachments: AttachmentPayload[] = [];\n private attachmentResponses: string[] = [];\n\n constructor(\n assistantId: string,\n adapter: AlquimiaAdapter,\n options: AlquimiaSDKOptions = {}\n ) {\n if (!assistantId) {\n throw new Error('AlquimiaSDK: assistantId is required');\n }\n if (!adapter) {\n throw new Error(\n 'AlquimiaSDK: adapter is required. Use createNextJsAdapter() or createFetchAdapter()'\n );\n }\n\n this.assistantId = assistantId;\n this.adapter = adapter;\n this.enforceCharacterization = options.enforceCharacterization ?? true;\n\n this.axiosInstance = axios.create();\n this.axiosInstance.interceptors.response.use(\n (response) => response,\n async (error) => {\n if (error.response?.status && this.loggerProvider) {\n await this.loggerProvider.logError('Server Error', error, {\n url: error.config.url,\n method: error.config.method,\n data: error.config.data,\n status: error.response.status,\n responseData: error.response.data,\n });\n }\n return Promise.reject(error);\n }\n );\n\n this.textToSpeech = this.textToSpeech.bind(this);\n this.speechToText = this.speechToText.bind(this);\n }\n\n withConversationId(conversationId: string): AlquimiaSDK {\n this.conversationId = conversationId;\n return this;\n }\n\n withAttachments(attachments: AttachmentPayload[]): AlquimiaSDK {\n this.attachments = attachments;\n return this;\n }\n\n withWhisperProvider(provider: WhisperProvider): AlquimiaSDK {\n this.whisperProvider = provider;\n return this;\n }\n\n withStableDiffusionProvider(provider: StableDiffusionProvider): AlquimiaSDK {\n this.stableDiffusionProvider = provider;\n return this;\n }\n\n withAnalyzeCharacterizationProvider(provider: CharacterizationProvider): AlquimiaSDK {\n this.analyzeCharacterizationProvider = provider;\n return this;\n }\n\n withRatingsProvider(provider: RatingsProvider): AlquimiaSDK {\n this.ratingsProvider = provider;\n return this;\n }\n\n withLoggerProvider(provider: LoggerProvider): AlquimiaSDK {\n this.loggerProvider = provider;\n return this;\n }\n\n withTools(tools: any): AlquimiaSDK {\n this.tools = tools;\n return this;\n }\n\n withExtraInstructions(extraInstructions: Record<string, string>): AlquimiaSDK {\n this.extraInstructions = extraInstructions;\n return this;\n }\n\n withAssistantConfig(assistantConfig: any): AlquimiaSDK {\n this.assistantConfig = assistantConfig;\n return this;\n }\n\n withUserId(userId: string): AlquimiaSDK {\n this.userId = userId;\n return this;\n }\n\n getEnforceCharacterization(): boolean {\n return this.enforceCharacterization ?? true;\n }\n\n textToSpeech(text: string): Promise<TTSResult> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.textToSpeech(text);\n }\n\n speechToText(audio: string): Promise<string> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.speechToText(audio);\n }\n\n async sendMessage(query: string, traceParent?: string): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n const inferUrl = this.adapter.resolveInferUrl(this.assistantId);\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;\n\n const initMessage: Record<string, unknown> = {\n query,\n session_id: this.conversationId,\n user_id: this.userId,\n ...(this.extraInstructions && { extra_instructions: this.extraInstructions }),\n ...(this.assistantConfig && { config: this.assistantConfig }),\n ...(hasClientTools && {\n evaluation_strategy: {\n evaluation_strategy_id: 'native',\n tool_schemas: this.tools,\n },\n }),\n };\n\n const result = (\n await this.axiosInstance.post(inferUrl, initMessage, {\n headers: {\n 'Content-Type': 'application/json',\n ...(traceParent && { 'x-trace-parent': traceParent }),\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.traceParent = traceParent ?? null;\n this.streamId = result.taskid ?? null;\n this.attachmentResponses = result.attachments ?? [];\n this.attachments = [];\n\n return this;\n }\n\n /**\n * Complete a pending client-tool execution (the missing \"submit half\" of the\n * client-tool loop). POSTs a {@link ToolExecutionResponse} to the runtime's\n * `/event/tool-completion`. For interactive `render_ui` surfaces `result` is\n * the user's data; for display-only surfaces the SDK sends `{ shown: true }`.\n * The pending call is correlated by `control_id` in the body + the\n * `context-metadata` header (taskid + sessionid).\n */\n async submitToolResult(response: ToolExecutionResponse): Promise<void> {\n const url = this.adapter.resolveToolCompletionUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)'\n );\n }\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n assistantid: this.assistantId,\n ...(this.streamId && { taskid: this.streamId }),\n ...(this.conversationId && { sessionid: this.conversationId }),\n ...(this.userId && { userid: this.userId }),\n ...adapterHeaders,\n };\n await this.axiosInstance.post(url, response, { headers });\n }\n\n async generateImage(query: string): Promise<string> {\n if (!this.stableDiffusionProvider) {\n throw new Error('Stable Diffusion provider not initialized');\n }\n return this.stableDiffusionProvider.generateImage(query);\n }\n\n async analyzeCharacterization(text: string): Promise<Record<string, any>> {\n if (!this.analyzeCharacterizationProvider) {\n throw new Error('Analyze characterization provider not initialized');\n }\n return this.analyzeCharacterizationProvider.analyzeCharacterization(text);\n }\n\n async rate(data: any): Promise<Record<string, any>> {\n if (!this.ratingsProvider) {\n throw new Error('Ratings provider not initialized');\n }\n return this.ratingsProvider.rate(data);\n }\n\n async logInfo(message: string, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logInfo(message, data);\n }\n\n async logError(message: string, error: Error, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logError(message, error, data);\n }\n\n /**\n * @deprecated The runtime no longer returns attachment IDs from the infer\n * response — attachments are uploaded as standalone blobs and linked to the\n * session via headers. Always returns `[]`; kept for source compatibility.\n */\n getAttachmentResponses(): string[] {\n return this.attachmentResponses;\n }\n\n async uploadAttachment(file: File, _attachmentId?: string): Promise<void> {\n void _attachmentId;\n const url = this.adapter.resolveBlobUploadUrl();\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n const formData = new FormData();\n formData.append('file', file);\n await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\n }\n\n /**\n * Identity headers (kebab-case) required by `/context/blob/upload` and\n * the rest of the runtime's internal endpoints introduced in v0.2.0→next.\n */\n private buildIdentityHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'assistant-id': this.assistantId,\n };\n if (this.conversationId) headers['session-id'] = this.conversationId;\n if (this.userId) headers['user-id'] = this.userId;\n if (this.streamId) headers['task-id'] = this.streamId;\n return headers;\n }\n\n getUrlStream(): string {\n if (!this.streamId) {\n throw new Error('Stream ID not initialized. Call sendMessage() first');\n }\n\n const url = this.adapter.resolveStreamUrl(this.streamId);\n if (!this.traceParent) return url;\n\n // `EventSource` cannot set request headers, so the turn's traceparent rides\n // the URL. The proxy turns it back into `x-trace-parent` and does not pass\n // the param upstream; without this the stream leg — where the whole\n // inference actually happens — lands in a different trace than the infer.\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;\n }\n\n getStreamId(): string | null {\n return this.streamId;\n }\n\n /** Alias for {@link getStreamId} — same value as infer `taskid`. */\n getTaskId(): string | null {\n return this.streamId;\n }\n}\n\nexport default AlquimiaSDK;\n","import {\n BaseAPIConfig,\n ApiError,\n ConversationsMap,\n ThinkingsInferenceResponse,\n Tooler,\n ToolEvent,\n} from \"../types/type\";\nimport { CatalogManifest } from \"../genui\";\n\nexport function generateTranslatePrompt(text: string) {\n const prompt = `\n Arrange the following text according to the given object structure and return it as plain json, values summarized to one word, no formatting:\n {\n restrictions: {\n value: [''],\n description: 'Restrictions to certain foods'\n },\n alergies: {\n value: [''],\n description: 'Alergies to certain foods'\n },\n wine_preference: {\n value: [''],\n description: 'Preferences for the wine'\n },\n meal_preference: {\n value: [''],\n description: 'Preferences for the meal'\n }\n }\n\n Text: \"${text}\"\n\n Output:\n `;\n\n return prompt;\n}\n\nexport function getCookies(name: string) {\n if (typeof document === \"undefined\") return undefined;\n const value = `; ${document.cookie}`;\n const parts = value.split(`; ${name}=`);\n if (parts.length === 2) return parts.pop()?.split(\";\").shift();\n}\n\nexport function generateHeaders(config: BaseAPIConfig): HeadersInit {\n const headers: HeadersInit = {\n \"Content-Type\": \"application/json\",\n };\n\n if (config.token) {\n headers[\"Authorization\"] = `Bearer ${config.token}`;\n }\n\n if (config.headers) {\n Object.entries(config.headers).forEach(([key, value]) => {\n headers[key] = value;\n });\n }\n\n return headers;\n}\n\nexport function isTextContent(buffer: ArrayBuffer): boolean {\n try {\n const text = new TextDecoder().decode(buffer);\n const trimmedText = text.trim();\n\n return (\n /^[\\w#\\-*|[\\]+=\\s\\n\\r\\t!]/.test(trimmedText) ||\n trimmedText.startsWith(\"#\") ||\n trimmedText.startsWith(\"![\") ||\n trimmedText.startsWith(\"```\") ||\n trimmedText.startsWith(\"---\") ||\n /^[a-zA-Z0-9\\s\\n\\r\\t]/.test(trimmedText) ||\n /^!\\[.*\\]\\(.*\\)/.test(trimmedText)\n );\n } catch {\n return false;\n }\n}\n\nexport function getQueryParam(param: string): string | null {\n if (typeof window !== \"undefined\") {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get(param);\n }\n return null;\n}\n\nexport function defineAssistantId(defaultId: string): string {\n if (typeof window !== \"undefined\" && window.location.pathname === \"/\") {\n const queryAssistantId = getQueryParam(\"talkwith\");\n if (queryAssistantId) {\n localStorage.setItem(\"assistantId\", queryAssistantId);\n return queryAssistantId;\n }\n const storedAssistantId = localStorage.getItem(\"assistantId\");\n return storedAssistantId || defaultId;\n }\n return defaultId;\n}\n\nexport function formatTimeWithUnit(timeMs: number): string {\n if (timeMs >= 1000) {\n return `${(timeMs / 1000).toFixed(1)}s`;\n }\n return `${Math.round(timeMs)}ms`;\n}\n\nexport function serializeAxiosError(error: unknown) {\n if (error instanceof Error) {\n const customError = error as ApiError;\n return {\n message: customError?.message,\n name: customError?.name,\n stack: customError?.stack,\n code: customError?.code,\n status: customError?.status,\n };\n }\n return {\n message: String(error),\n name: \"Unknown Error\",\n };\n}\n\nexport function parseConversationsMapCookie(\n cookieValue: string\n): ConversationsMap {\n try {\n const decodedValue = decodeURIComponent(cookieValue);\n return JSON.parse(decodedValue) as ConversationsMap;\n } catch (e) {\n console.error(\"Error parsing conversations cookie:\", e);\n return {};\n }\n}\n\nexport function getTopicSessionId(topicId: string): string {\n const conversationsStr = getCookies(\"alquimia-sessions\") || \"{}\";\n if (!conversationsStr) {\n const sessionCookie = getCookies(\"alquimia-session\");\n return sessionCookie || \"\";\n }\n\n const conversationsMap = parseConversationsMapCookie(conversationsStr);\n return conversationsMap[topicId] || \"\";\n}\n\nexport function createMessageId() {\n return Math.floor(Math.random() * 1000000).toString();\n}\n\nexport function hasToolSummary(data: any) {\n return data.tool_summary && Object.keys(data.tool_summary).length > 0;\n}\n\nexport function mergeThinkingsByControlId(\n existingThinkings: ThinkingsInferenceResponse[] = [],\n newThinkings: ThinkingsInferenceResponse[] = []\n): ThinkingsInferenceResponse[] {\n const thinkingsMap = new Map(existingThinkings.map((t) => [t.control_id, t]));\n for (const t of newThinkings) {\n if (t && t.control_id) {\n thinkingsMap.set(t.control_id, t);\n }\n }\n return Array.from(thinkingsMap.values());\n}\n\n\nexport function mergeToolerByControlId(\n currentTooler: Tooler[],\n toolEvent: ToolEvent\n): Tooler[] {\n const { event_class, control_id, data, status } = toolEvent;\n const existingTool = currentTooler.find((t) => t.control_id === control_id);\n const base: Tooler = existingTool || { control_id };\n\n let updated: Tooler;\n switch (event_class) {\n case \"ServerToolExecutionCommand\":\n updated = {\n ...base,\n tool_summary: {\n name: data.name,\n parameters: data,\n },\n };\n break;\n case \"ToolExecutionResponse\":\n updated = {\n ...base,\n tool_output: {\n result: data,\n status,\n },\n };\n break;\n case \"A2AInferenceCommand\":\n updated = {\n ...base,\n tool_summary: {\n name: data.name,\n parameters: { ...data, type: \"A2A\" },\n },\n };\n break;\n default:\n return currentTooler;\n }\n\n return currentTooler.some(tool => tool.control_id === control_id)\n ? currentTooler.map(tool => (tool.control_id === control_id ? updated : tool))\n : [...currentTooler, updated];\n}\n\nexport function mergeToolEvents(\n initial: Tooler[],\n toolEvents?: ToolEvent[]\n): Tooler[] {\n return (toolEvents ?? []).reduce(\n (acc, toolEvent) => mergeToolerByControlId(acc, toolEvent),\n initial\n );\n}\n\nexport function resolveGenuiAllow(catalog: CatalogManifest, allow?: string[] | 'all'): string[] {\n return !allow || allow === 'all' ? Object.keys(catalog.components) : allow;\n}\n","/** One granular Runtime worklog record (a `bus_mode` SSE frame or a `/worklog/{task_id}/events` item). */\nexport interface WorklogRecord {\n /** Runtime v0.5.0+ tamper-evident hash chain fields (optional on SSE frames). */\n entry_hash?: string | null;\n previous_hash?: string | null;\n event_class: string;\n control_id: string | null;\n data: unknown;\n status: \"success\" | \"error\" | null;\n date_submitted: string;\n}\n\n/** Runtime v0.5.0 worklog audit summary returned by `GET /worklog/`. */\nexport interface WorklogSummary {\n task_id: string;\n parent_task_id?: string | null;\n session_id?: string | null;\n user_id?: string | null;\n assistant_id?: string | null;\n agentspace_id?: string | null;\n channel_id?: string | null;\n depth?: number;\n final_status?: string | null;\n started_at: string;\n finished_at?: string | null;\n}\n\n/** Runtime v0.5.0 full worklog detail returned by `GET /worklog/{task_id}`. */\nexport interface WorklogDetail extends WorklogSummary {\n final_result?: string | null;\n error_message?: string | null;\n}\n\n/** Runtime v0.5.0 single worklog event returned by `GET /worklog/{task_id}/events`. */\nexport interface WorklogEventDetail {\n id: number;\n task_id: string;\n previous_hash?: string | null;\n entry_hash?: string | null;\n event_class: string;\n control_id?: string | null;\n status?: string | null;\n data?: unknown;\n submitted_at: string;\n}\n\n/** Runtime v0.5.0 paginated list of worklog summaries. */\nexport interface WorklogPage {\n items: WorklogSummary[];\n total: number;\n limit: number;\n offset: number;\n}\n\n/** Runtime v0.5.0 paginated list of worklog events for a single task. */\nexport interface WorklogEventPage {\n task_id: string;\n items: WorklogEventDetail[];\n total: number;\n}\n\n/** Runtime v0.5.0 hash-chain verification result returned by `GET /worklog/{task_id}/verify`. */\nexport interface WorklogVerificationResult {\n valid: boolean;\n task_id: string;\n event_count: number;\n first_broken_event_id?: number | null;\n first_broken_index?: number | null;\n expected_hash?: string | null;\n actual_hash?: string | null;\n message: string;\n}\n\n/** Semantic bucket a node belongs to. */\nexport type NodeKind =\n | \"safeguard\"\n | \"reasoning\"\n | \"tool\"\n | \"a2a\"\n | \"memory\"\n | \"answer\"\n | \"unknown\";\n\n/** Lifecycle state of a single node. */\nexport type NodeStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"skipped\";\n\n/** Overall run status. */\nexport type RunStatus = \"idle\" | \"running\" | \"success\" | \"error\";\n\n/** A single step in the execution chain (command + its response merged by control_id). */\nexport interface WorklogNode {\n id: string;\n kind: NodeKind;\n eventClass: string;\n status: NodeStatus;\n title: string;\n startedAt?: string;\n endedAt?: string;\n depth: number;\n parentId?: string;\n children: WorklogNode[];\n command?: unknown;\n response?: unknown;\n error?: string;\n raw: WorklogRecord[];\n}\n\n/** Normalized execution model produced by the reducer. */\nexport interface WorklogState {\n taskId: string | null;\n status: RunStatus;\n answer: string | null;\n nodes: WorklogNode[];\n index: Record<string, number>;\n raw: WorklogRecord[];\n}\n\n/** How a record acts on the model. */\nexport type EventRole = \"open\" | \"close\" | \"run-open\" | \"run-close\" | \"ignore\";\n\n/** Registry descriptor for one event_class. */\nexport interface EventInterpreter {\n kind: NodeKind;\n role: EventRole;\n title: (_record: WorklogRecord) => string;\n /** If true, an opened node starts in \"pending\" (awaiting external input) rather than \"running\". */\n pending?: boolean;\n}\n\nexport function initialWorklogState(taskId: string | null = null): WorklogState {\n return { taskId, status: \"idle\", answer: null, nodes: [], index: {}, raw: [] };\n}\n","import type { EventInterpreter, WorklogRecord } from \"./types\";\n\nconst asRecord = (data: unknown): Record<string, unknown> =>\n data && typeof data === \"object\" ? (data as Record<string, unknown>) : {};\n\nconst toolTitle = (r: WorklogRecord): string => {\n const name = asRecord(r.data).name;\n return typeof name === \"string\" && name.length > 0 ? `Tool: ${name}` : \"Tool\";\n};\n\nconst agentTitle = (r: WorklogRecord): string => {\n const name = asRecord(r.data).name;\n return typeof name === \"string\" && name.length > 0 ? `Agent: ${name}` : \"Agent-to-agent\";\n};\n\nconst constTitle = (label: string) => () => label;\n\nexport const EVENT_REGISTRY: Record<string, EventInterpreter> = {\n // Run envelope\n AssistantInference: { kind: \"answer\", role: \"run-open\", title: constTitle(\"Inference started\") },\n AssistantInferenceResponse: { kind: \"answer\", role: \"run-close\", title: constTitle(\"Answer\") },\n\n // Safeguard\n ShieldInference: { kind: \"safeguard\", role: \"open\", title: constTitle(\"Safeguard\") },\n ShieldInferenceResponse: { kind: \"safeguard\", role: \"close\", title: constTitle(\"Safeguard\") },\n\n // Reasoning\n ResponseInference: { kind: \"reasoning\", role: \"open\", title: constTitle(\"Reasoning\") },\n ResponseInferenceResponse: { kind: \"reasoning\", role: \"close\", title: constTitle(\"Reasoning\") },\n\n // Tools (server + subclasses) and their responses\n ServerToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle },\n BuiltinToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle },\n UnknownToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle },\n ClientToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle, pending: true },\n ToolExecutionResponse: { kind: \"tool\", role: \"close\", title: toolTitle },\n BuiltinToolExecutionResponse: { kind: \"tool\", role: \"close\", title: toolTitle },\n\n // Tool schema discovery\n ToolSchema: { kind: \"tool\", role: \"open\", title: constTitle(\"Tool schema\") },\n ToolSchemaResponse: { kind: \"tool\", role: \"close\", title: constTitle(\"Tool schema\") },\n\n // Agent-to-agent\n A2AInference: { kind: \"a2a\", role: \"open\", title: agentTitle },\n AgentDiscovery: { kind: \"a2a\", role: \"open\", title: constTitle(\"Agent discovery\") },\n AgentDiscoveryResponse: { kind: \"a2a\", role: \"close\", title: constTitle(\"Agent discovery\") },\n\n // Memory / persistence\n ContextPersistence: { kind: \"memory\", role: \"open\", title: constTitle(\"Memory persistence\") },\n ContextFlush: { kind: \"memory\", role: \"open\", title: constTitle(\"Memory flush\") },\n ContextFlushResponse: { kind: \"memory\", role: \"close\", title: constTitle(\"Memory flush\") },\n\n // Human approval\n HumanApprovalRequired: {\n kind: \"tool\",\n role: \"open\",\n title: constTitle(\"Human approval required\"),\n pending: true,\n },\n HumanApprovalRequiredResponse: { kind: \"tool\", role: \"close\", title: constTitle(\"Human approval\") },\n};\n\nexport function resolveInterpreter(eventClass: string): EventInterpreter {\n if (Object.prototype.hasOwnProperty.call(EVENT_REGISTRY, eventClass)) {\n return EVENT_REGISTRY[eventClass];\n }\n return {\n kind: \"unknown\",\n role: \"open\",\n title: (r: WorklogRecord) => r.event_class,\n };\n}\n","import { resolveInterpreter } from \"./registry\";\nimport type { EventInterpreter, WorklogNode, WorklogRecord, WorklogState } from \"./types\";\nimport { initialWorklogState } from \"./types\";\n\nconst asString = (v: unknown): string =>\n typeof v === \"string\" ? v : v == null ? \"\" : JSON.stringify(v);\n\nconst nodeDepth = (record: WorklogRecord): number => {\n const d = record.data && typeof record.data === \"object\"\n ? (record.data as Record<string, unknown>).depth\n : undefined;\n return typeof d === \"number\" ? d : 0;\n};\n\nconst makeOpenNode = (record: WorklogRecord, interp: EventInterpreter, id: string): WorklogNode => ({\n id,\n kind: interp.kind,\n eventClass: record.event_class,\n status: interp.pending ? \"pending\" : \"running\",\n title: interp.title(record),\n startedAt: record.date_submitted,\n depth: nodeDepth(record),\n children: [],\n command: record.data,\n raw: [record],\n});\n\nconst makeClosedNode = (record: WorklogRecord, interp: EventInterpreter, id: string): WorklogNode => ({\n id,\n kind: interp.kind,\n eventClass: record.event_class,\n status: record.status === \"error\" ? \"failed\" : \"completed\",\n title: interp.title(record),\n startedAt: record.date_submitted,\n endedAt: record.date_submitted,\n depth: nodeDepth(record),\n children: [],\n response: record.data,\n error: record.status === \"error\" ? asString(record.data) : undefined,\n raw: [record],\n});\n\nexport function reduceWorklog(state: WorklogState, record: WorklogRecord): WorklogState {\n const interp = resolveInterpreter(record.event_class);\n const next: WorklogState = {\n ...state,\n nodes: state.nodes.slice(),\n index: { ...state.index },\n raw: [...state.raw, record],\n };\n\n if (interp.role === \"ignore\") return next;\n\n if (interp.role === \"run-open\") {\n next.status = \"running\";\n return next;\n }\n\n if (interp.role === \"run-close\") {\n next.answer = asString(record.data) || null;\n next.status = record.status === \"error\" ? \"error\" : \"success\";\n return next;\n }\n\n const key = record.control_id ?? `${record.event_class}-${next.raw.length}`;\n\n if (interp.role === \"close\") {\n const pos = Object.prototype.hasOwnProperty.call(next.index, key) ? next.index[key] : undefined;\n if (pos != null) {\n const existing = next.nodes[pos];\n next.nodes[pos] = {\n ...existing,\n status: record.status === \"error\" ? \"failed\" : \"completed\",\n endedAt: record.date_submitted,\n response: record.data,\n error: record.status === \"error\" ? asString(record.data) : existing.error,\n raw: [...existing.raw, record],\n };\n } else {\n // response arrived without a seen command — create it already closed\n next.index[key] = next.nodes.length;\n next.nodes.push(makeClosedNode(record, interp, key));\n }\n if (record.status === \"error\") next.status = \"error\";\n return next;\n }\n\n // role === \"open\"\n const pos = Object.prototype.hasOwnProperty.call(next.index, key) ? next.index[key] : undefined;\n if (pos != null) {\n const existing = next.nodes[pos];\n next.nodes[pos] = { ...existing, raw: [...existing.raw, record] };\n } else {\n next.index[key] = next.nodes.length;\n next.nodes.push(makeOpenNode(record, interp, key));\n }\n return next;\n}\n\nexport function foldWorklog(records: WorklogRecord[], taskId: string | null = null): WorklogState {\n return records.reduce(reduceWorklog, initialWorklogState(taskId));\n}\n","import { useCallback, useReducer } from \"react\";\nimport { reduceWorklog } from \"./reducer\";\nimport { initialWorklogState, type WorklogRecord, type WorklogState } from \"./types\";\n\ntype Action =\n | { type: \"ingest\"; record: WorklogRecord }\n | { type: \"ingestMany\"; records: WorklogRecord[] }\n | { type: \"reset\"; taskId: string | null };\n\nfunction hookReducer(state: WorklogState, action: Action): WorklogState {\n switch (action.type) {\n case \"ingest\":\n return reduceWorklog(state, action.record);\n case \"ingestMany\":\n return action.records.reduce(reduceWorklog, state);\n case \"reset\":\n return initialWorklogState(action.taskId);\n }\n}\n\n/** Live worklog accumulator. Feed it `bus_mode` records via `ingest`; use `foldWorklog` for history. */\nexport function useWorklog(taskId: string | null = null) {\n const [worklog, dispatch] = useReducer(hookReducer, taskId, initialWorklogState);\n\n const ingest = useCallback((record: WorklogRecord) => dispatch({ type: \"ingest\", record }), []);\n const ingestMany = useCallback(\n (records: WorklogRecord[]) => dispatch({ type: \"ingestMany\", records }),\n [],\n );\n const reset = useCallback(\n (id: string | null = null) => dispatch({ type: \"reset\", taskId: id }),\n [],\n );\n\n return { worklog, ingest, ingestMany, reset };\n}\n","import type { WorklogRecord } from \"./types\";\n\n/** Loosely-typed shape of a parsed SSE `data:` frame from the granular Runtime stream. */\nexport interface RawFrame {\n event_class?: string;\n control_id?: string | null;\n data?: unknown;\n status?: string | null;\n date_submitted?: string;\n /** Runtime v0.5.0+ tamper-evident hash chain fields. */\n entry_hash?: string | null;\n previous_hash?: string | null;\n}\n\n/** Normalize a parsed SSE frame into a WorklogRecord (defaults missing fields; never throws). */\nexport function frameToRecord(frame: RawFrame): WorklogRecord {\n const status = frame.status === \"success\" || frame.status === \"error\" ? frame.status : null;\n return {\n event_class: typeof frame.event_class === \"string\" && frame.event_class.length > 0\n ? frame.event_class\n : \"Unknown\",\n control_id: frame.control_id ?? null,\n data: frame.data,\n status,\n date_submitted: typeof frame.date_submitted === \"string\" ? frame.date_submitted : \"\",\n entry_hash: frame.entry_hash ?? null,\n previous_hash: frame.previous_hash ?? null,\n };\n}\n","export interface PendingClientTool {\n controlId: string;\n toolName: string;\n parameters: unknown;\n}\n\n/** Extract a pending client-tool execution from a raw SSE frame. Returns null if not one. */\nexport function extractPendingClientTool(frame: unknown): PendingClientTool | null {\n if (!frame || typeof frame !== \"object\") return null;\n const f = frame as Record<string, any>;\n if (f.event_class !== \"ClientToolExecution\") return null;\n const name = f.data?.name;\n const parameters = f.data?.parameters;\n const controlId = f.control_id;\n if (typeof name !== \"string\" || parameters === undefined || typeof controlId !== \"string\") return null;\n return { controlId, toolName: name, parameters };\n}\n","import { z } from \"zod\";\n\n/**\n * The agent-facing \"style vocabulary\" — enum-constrained semantic props that let\n * the model style a surface via INTENT, never CSS. Shared across every catalog\n * component; the UI renderer maps these to the consumer's design tokens.\n * See docs/a2ui-approach.md §11.\n */\nexport const TONES = [\"default\", \"muted\", \"primary\", \"success\", \"warning\", \"danger\"] as const;\nexport const SIZES = [\"sm\", \"md\", \"lg\"] as const;\nexport const EMPHASES = [\"low\", \"medium\", \"high\"] as const;\nexport const ALIGNS = [\"start\", \"center\", \"end\"] as const;\nexport const DENSITIES = [\"compact\", \"comfortable\"] as const;\n\nexport type Tone = (typeof TONES)[number];\nexport type Size = (typeof SIZES)[number];\nexport type Emphasis = (typeof EMPHASES)[number];\nexport type Align = (typeof ALIGNS)[number];\nexport type Density = (typeof DENSITIES)[number];\n\nexport interface StyleProps {\n tone?: Tone;\n size?: Size;\n emphasis?: Emphasis;\n align?: Align;\n density?: Density;\n}\n\n/**\n * Raw zod shape merged into every component schema in the catalog.\n * `variant` is component-specific and added per component, not here.\n */\nexport const styleSchemaShape = {\n tone: z.enum(TONES).optional(),\n size: z.enum(SIZES).optional(),\n emphasis: z.enum(EMPHASES).optional(),\n align: z.enum(ALIGNS).optional(),\n density: z.enum(DENSITIES).optional(),\n};\n","import type { ZodType } from \"zod\";\n\nexport interface UIComponentDefinition {\n name: string;\n /** zod schema for the component's presentational props. */\n schema: ZodType;\n /** semantic action names this component may emit. */\n allowedActions?: string[];\n}\n\nexport interface CatalogManifest {\n id: string;\n components: Record<string, UIComponentDefinition>;\n}\n\n/** Marker used by the renderer when a component name is not in the catalog. */\nexport const UNKNOWN_COMPONENT = \"__unknown__\";\n\n/** Resolve a component name against the active catalog. Returns null on miss — never throws. */\nexport function resolveComponent(\n manifest: CatalogManifest,\n name: string,\n): UIComponentDefinition | null {\n if (!name || typeof name !== \"string\") return null;\n return manifest.components[name] ?? null;\n}\n","import { z } from \"zod\";\nimport type { CatalogManifest } from \"./registry\";\nimport { styleSchemaShape } from \"./style\";\n\n/** Versioned catalog id — a URI (A2UI convention). The version lives in the path. */\nexport const CORE_CATALOG_ID = \"https://alquimia.ai/catalogs/core/v1/catalog.json\";\n\n/** Merge shared style vocabulary + an optional component-specific variant enum + own props. */\nconst def = (\n name: string,\n own: z.ZodRawShape,\n opts?: { variant?: readonly [string, ...string[]]; allowedActions?: string[] },\n) => ({\n name,\n schema: z\n .object({\n ...styleSchemaShape,\n ...(opts?.variant ? { variant: z.enum(opts.variant).optional() } : {}),\n ...own,\n })\n .passthrough(),\n allowedActions: opts?.allowedActions,\n});\n\nconst option = z.object({ label: z.string(), value: z.union([z.string(), z.number()]) });\n\n/**\n * The default catalog: ~40 components across layout / content / inputs / data / actions.\n * Prop schemas describe ONLY presentational props; id/component/children/binding/action\n * are structural. Every component also accepts the shared style vocabulary.\n */\nexport const coreCatalog: CatalogManifest = {\n id: CORE_CATALOG_ID,\n components: {\n // ---- layout ----\n Stack: def(\"Stack\", {\n direction: z.enum([\"vertical\", \"horizontal\"]).optional(),\n gap: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n }),\n Grid: def(\"Grid\", {\n columns: z.number().int().min(1).max(6).optional(),\n gap: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n }),\n Row: def(\"Row\", { gap: z.enum([\"sm\", \"md\", \"lg\"]).optional(), wrap: z.boolean().optional() }),\n Column: def(\"Column\", { gap: z.enum([\"sm\", \"md\", \"lg\"]).optional() }),\n Divider: def(\"Divider\", { label: z.string().optional() }),\n Spacer: def(\"Spacer\", { size: z.enum([\"sm\", \"md\", \"lg\"]).optional() }),\n Card: def(\"Card\", { title: z.string().optional(), description: z.string().optional() }, {\n variant: [\"elevated\", \"outline\", \"ghost\"],\n }),\n Accordion: def(\"Accordion\", {\n items: z.array(z.object({ title: z.string(), value: z.string() })).optional(),\n }),\n Tabs: def(\"Tabs\", { tabs: z.array(z.object({ label: z.string(), value: z.string() })).min(1) }),\n // ---- content ----\n Text: def(\"Text\", { text: z.string() }, { variant: [\"body\", \"muted\", \"caption\", \"lead\"] }),\n Heading: def(\"Heading\", { text: z.string(), level: z.number().int().min(1).max(4).optional() }),\n Markdown: def(\"Markdown\", { text: z.string() }),\n Image: def(\"Image\", { src: z.string(), alt: z.string().optional() }),\n Icon: def(\"Icon\", { name: z.string() }),\n Badge: def(\"Badge\", { text: z.string() }, { variant: [\"solid\", \"outline\", \"subtle\"] }),\n Avatar: def(\"Avatar\", { src: z.string().optional(), fallback: z.string().optional() }),\n Alert: def(\"Alert\", { text: z.string(), title: z.string().optional() }, {\n variant: [\"info\", \"success\", \"warning\", \"danger\"],\n }),\n Stat: def(\"Stat\", { label: z.string(), value: z.union([z.string(), z.number()]), delta: z.string().optional() }),\n KeyValue: def(\"KeyValue\", {}),\n List: def(\"List\", { ordered: z.boolean().optional() }),\n Quote: def(\"Quote\", { text: z.string(), cite: z.string().optional() }),\n // ---- inputs ----\n TextField: def(\"TextField\", { label: z.string().optional(), placeholder: z.string().optional() }),\n TextArea: def(\"TextArea\", {\n label: z.string().optional(),\n placeholder: z.string().optional(),\n rows: z.number().int().optional(),\n }),\n NumberField: def(\"NumberField\", {\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n step: z.number().optional(),\n }),\n Select: def(\"Select\", {\n label: z.string().optional(),\n placeholder: z.string().optional(),\n options: z.array(option).min(1),\n }),\n MultiSelect: def(\"MultiSelect\", { label: z.string().optional(), options: z.array(option).min(1) }),\n Combobox: def(\"Combobox\", {\n label: z.string().optional(),\n placeholder: z.string().optional(),\n options: z.array(option).min(1),\n }),\n Checkbox: def(\"Checkbox\", { label: z.string().optional() }),\n CheckboxGroup: def(\"CheckboxGroup\", { label: z.string().optional(), options: z.array(option).min(1) }),\n Radio: def(\"Radio\", { label: z.string().optional(), options: z.array(option).min(1) }),\n Switch: def(\"Switch\", { label: z.string().optional() }),\n Slider: def(\"Slider\", {\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n step: z.number().optional(),\n }),\n DatePicker: def(\"DatePicker\", { label: z.string().optional() }),\n DateRange: def(\"DateRange\", { label: z.string().optional() }),\n FileUpload: def(\"FileUpload\", {\n label: z.string().optional(),\n accept: z.string().optional(),\n multiple: z.boolean().optional(),\n }),\n Rating: def(\"Rating\", { label: z.string().optional(), max: z.number().int().optional() }),\n // ---- data ----\n Table: def(\"Table\", {\n columns: z.array(z.object({ key: z.string(), header: z.string().optional() })).min(1),\n sortable: z.boolean().optional(),\n }, { allowedActions: [\"sort\", \"filter\"] }),\n Chart: def(\"Chart\", {\n kind: z.enum([\"bar\", \"line\", \"area\", \"pie\"]),\n x: z.string().optional(),\n series: z.array(z.object({ key: z.string(), label: z.string().optional() })).min(1),\n title: z.string().optional(),\n }),\n Progress: def(\"Progress\", { value: z.number(), max: z.number().optional(), label: z.string().optional() }),\n Timeline: def(\"Timeline\", {\n items: z\n .array(z.object({ title: z.string(), description: z.string().optional(), timestamp: z.string().optional() }))\n .min(1),\n }),\n // ---- actions ----\n Button: def(\"Button\", { text: z.string() }, {\n variant: [\"solid\", \"outline\", \"ghost\", \"link\"],\n allowedActions: [\"submit\", \"cancel\", \"reset\", \"select\", \"confirm\"],\n }),\n ButtonGroup: def(\"ButtonGroup\", {}),\n Link: def(\"Link\", { text: z.string(), href: z.string().optional() }),\n },\n};\n","import type { SurfaceAction } from \"./types\";\n\nexport type UIActionKind = \"agent-bound\" | \"local\";\n\nexport interface UIAction {\n surfaceId: string;\n componentId: string;\n action: string;\n kind: UIActionKind;\n payload?: Record<string, unknown>;\n}\n\n/**\n * The `result` body posted to /event/tool-completion for an agent-bound action.\n * Shape is part of the agent-facing contract — the prompt clause describes it.\n */\nexport interface SurfaceResult {\n /** The action's semantic name. */\n action: string;\n /** Which surface it came from. */\n surfaceId: string;\n /**\n * The id of the component that was acted on. This is what lets the agent tell WHICH\n * element fired when several share one action name — e.g. a grid of option cards that\n * all use `selectFlight`. Without it the agent has to ask the user what they just\n * clicked, which reads as a broken assistant.\n */\n componentId: string;\n /** The surface's collected data model (empty object when the surface binds no fields). */\n data: Record<string, unknown>;\n /**\n * Present only when the user declined the surface and answered in words instead\n * (see `buildDismissResult`). Absent on a normal submit or selection.\n */\n userMessage?: string;\n}\n\n/**\n * Action name reported when the user dismisses an interactive surface rather than using it.\n * Kept distinct from any model-authored action so the agent can tell the two apart.\n */\nexport const DISMISS_ACTION = \"userDismissedSurface\";\n\n/**\n * Complete a pending interactive surface *negatively*, optionally carrying the natural-language\n * reply the user typed instead of interacting.\n *\n * Why this exists: an interactive surface parks the inference until a tool result arrives. If\n * the UI is the only way to answer, a user who doesn't want any of the offered options is stuck\n * — they cannot type, and the task never resumes. Completing with this result unparks the\n * conversation and hands the agent the user's actual words, so it can respond to them.\n */\nexport function buildDismissResult(surfaceId: string, userMessage?: string): SurfaceResult {\n const said = typeof userMessage === \"string\" ? userMessage.trim() : \"\";\n return {\n action: DISMISS_ACTION,\n surfaceId,\n componentId: \"\",\n data: {},\n ...(said ? { userMessage: said } : {}),\n };\n}\n\n/** Build the tool-completion `result` for an agent-bound action. */\nexport function buildSurfaceResult(action: UIAction): SurfaceResult {\n return {\n action: action.action,\n surfaceId: action.surfaceId,\n componentId: action.componentId,\n data: action.payload ?? {},\n };\n}\n\n/** Agent-bound actions (wantResponse) return their payload to the agent; others stay local. */\nexport function classifyAction(action: SurfaceAction): UIActionKind {\n return action.wantResponse === true ? \"agent-bound\" : \"local\";\n}\n\nconst URL_LIKE = /^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/** Actions are semantic names, never URLs. Reject anything scheme- or protocol-relative. */\nexport function assertSafeActionName(name: string): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\"action.name must be a non-empty string\");\n }\n if (URL_LIKE.test(name)) {\n throw new Error(`action.name must be a semantic name, not a URL: ${name}`);\n }\n}\n","import { z } from \"zod\";\nimport type { A2uiComponent, A2uiSurface } from \"./types\";\nimport type { CatalogManifest, UIComponentDefinition } from \"./registry\";\nimport { resolveComponent } from \"./registry\";\nimport { assertSafeActionName } from \"./actions\";\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\nexport interface ValidationResult<T = unknown> {\n ok: boolean;\n value?: T;\n /** Fatal problems — the surface cannot be rendered. */\n errors: ValidationError[];\n /** Non-fatal problems — the surface still renders; these degrade gracefully. */\n warnings?: ValidationError[];\n}\n\nconst surfaceShape = z.object({\n surfaceId: z.string().min(1),\n // Tier 2 canonical id (versioned URI); `catalog` is the legacy alias. Both optional on the\n // wire — the SDK stamps `catalogId` if the agent omits it.\n catalogId: z.string().min(1).optional(),\n catalog: z.string().min(1).optional(),\n // Legacy explicit root. A2UI uses the component with id \"root\"; kept optional for back-compat.\n root: z.string().min(1).optional(),\n components: z.array(\n z\n .object({\n id: z.string().min(1),\n component: z.string().min(1),\n children: z.array(z.string()).optional(),\n child: z.string().optional(),\n binding: z.string().optional(),\n action: z.object({ name: z.string(), wantResponse: z.boolean().optional() }).optional(),\n })\n .passthrough(),\n ),\n dataModel: z.record(z.unknown()).optional(),\n});\n\n/** UAX#31 identifier rule (A2UI): XID_Start/underscore then XID_Continue. */\nconst UAX31_ID = /^[\\p{XID_Start}_][\\p{XID_Continue}]*$/u;\n\n/** Validate one node's presentational props against its catalog definition. */\nexport function validateProps(node: A2uiComponent, def: UIComponentDefinition): ValidationResult {\n const {\n id,\n component: _component,\n children: _children,\n child: _child,\n binding: _binding,\n action: _action,\n ...props\n } = node;\n const parsed = def.schema.safeParse(props);\n if (parsed.success) return { ok: true, value: parsed.data, errors: [] };\n return {\n ok: false,\n errors: parsed.error.issues.map((i) => ({ path: `${id}.${i.path.join(\".\")}`, message: i.message })),\n };\n}\n\n/** Full structural + catalog + prop + action validation of an incoming surface. */\nexport function validateSurface(input: unknown, manifest: CatalogManifest): ValidationResult<A2uiSurface> {\n const shape = surfaceShape.safeParse(input);\n if (!shape.success) {\n return { ok: false, errors: shape.error.issues.map((i) => ({ path: i.path.join(\".\"), message: i.message })) };\n }\n const surface = shape.data as A2uiSurface;\n const errors: ValidationError[] = []; // fatal — cannot render\n const warnings: ValidationError[] = []; // non-fatal — render anyway, degrade gracefully\n const ids = new Set(surface.components.map((c) => c.id));\n\n // Root = the component with id \"root\" (A2UI convention), falling back to the legacy `root` field.\n const rootId = ids.has(\"root\") ? \"root\" : surface.root;\n // Fatal: without a resolvable root node there is nothing to render.\n if (!rootId || !ids.has(rootId)) {\n errors.push({ path: \"root\", message: `no root component (expected a component with id \"root\")` });\n }\n\n // Non-fatal: catalogId should be present (the SDK stamps it if the agent omits it).\n if (!surface.catalogId && !surface.catalog) {\n warnings.push({ path: \"catalogId\", message: \"surface has no catalogId (SDK will stamp the active catalog)\" });\n }\n\n for (const node of surface.components) {\n // Non-fatal: A2UI mandates UAX#31 identifiers; a bad id still renders but is flagged.\n if (!UAX31_ID.test(node.id)) {\n warnings.push({ path: node.id, message: `id \"${node.id}\" is not a valid UAX#31 identifier` });\n }\n\n const def = resolveComponent(manifest, node.component);\n if (!def) {\n // Non-fatal: the renderer falls back to a text placeholder for unknown components.\n warnings.push({ path: node.id, message: `unknown component \"${node.component}\" (renders as text)` });\n continue;\n }\n\n // Non-fatal: invalid presentational props degrade to component defaults.\n warnings.push(...validateProps(node, def).errors);\n\n for (const childId of node.children ?? []) {\n if (!ids.has(childId)) {\n warnings.push({ path: node.id, message: `child \"${childId}\" does not exist (skipped)` });\n }\n }\n if (node.child && !ids.has(node.child)) {\n warnings.push({ path: node.id, message: `child \"${node.child}\" does not exist (skipped)` });\n }\n\n // Fatal (security invariant): an action name must be a semantic string, never a URL.\n if (node.action) {\n try {\n assertSafeActionName(node.action.name);\n } catch (e) {\n errors.push({ path: `${node.id}.action`, message: (e as Error).message });\n }\n }\n }\n\n return errors.length === 0\n ? { ok: true, value: surface, errors: [], warnings }\n : { ok: false, errors, warnings };\n}\n","import type { CatalogManifest } from \"./registry\";\nimport { TONES, SIZES, EMPHASES, ALIGNS, DENSITIES } from \"./style\";\n\n/**\n * The runtime expects each `tool_schemas` entry to be a flat JSON Schema of the\n * tool arguments: `title` is the tool name, `properties` are the arguments.\n * (Not the OpenAI `{ type:\"function\", function:{...} }` wrapper, and not a\n * `{ name, description, parameters }` envelope — both leave the runtime with an\n * empty argument schema.)\n */\nexport interface RenderUiToolSchema {\n title: \"render_ui\";\n name: \"render_ui\";\n description: string;\n type: \"object\";\n properties: Record<string, unknown>;\n required: string[];\n additionalProperties: boolean;\n}\n\nconst DESCRIPTION =\n \"Render a UI using A2UI. The arguments are a UI surface, NOT free-form. Shape: \" +\n \"{ surfaceId, root, components, dataModel? }. `components` is a FLAT array; every item is \" +\n \"{ id, component, children?, ...props } where `component` is one of the allowed names (use \" +\n \"`component`, never `type`) and `children` is an array of string ids referencing other items \" +\n \"(never nested objects). Inputs bind to the data model via `binding` (a JSON Pointer like \" +\n '\"/name\"). To collect input, include a Button with action { name, wantResponse: true } — its ' +\n \"result (the data model) is returned to you; a surface with no such button is display-only. \" +\n 'Example: { \"surfaceId\": \"signup\", \"root\": \"root\", \"components\": [ ' +\n '{ \"id\": \"root\", \"component\": \"Stack\", \"children\": [\"name\", \"desc\", \"submit\"] }, ' +\n '{ \"id\": \"name\", \"component\": \"TextField\", \"label\": \"Username\", \"binding\": \"/name\" }, ' +\n '{ \"id\": \"desc\", \"component\": \"TextField\", \"label\": \"Description\", \"binding\": \"/description\" }, ' +\n '{ \"id\": \"submit\", \"component\": \"Button\", \"text\": \"Save\", \"action\": { \"name\": \"save\", \"wantResponse\": true } } ' +\n '], \"dataModel\": { \"name\": \"\", \"description\": \"\" } }. ' +\n \"IMPORTANT: when you call render_ui, the rendered surface IS your reply — do NOT also \" +\n \"reproduce its content as text, markdown, or ASCII. Any accompanying message must be a brief \" +\n \"one-line intro at most, never a duplicate of the UI.\";\n\n/** Build the render_ui tool schema from a catalog, filtered to an allowlist of component names. */\nexport function buildRenderUiSchema(manifest: CatalogManifest, allowlist: string[]): RenderUiToolSchema {\n const allowed = allowlist.filter((name) => name in manifest.components);\n return {\n title: \"render_ui\",\n name: \"render_ui\",\n description: DESCRIPTION,\n type: \"object\",\n properties: {\n surfaceId: { type: \"string\" },\n // A2UI catalog id — a versioned URI. `const` nudges the model to echo it; the SDK\n // also stamps it if omitted, so the client always knows which catalog version to render.\n catalogId: { type: \"string\", const: manifest.id },\n catalog: { type: \"string\" }, // legacy alias (accepted, ignored)\n root: { type: \"string\" }, // legacy explicit root (accepted; A2UI uses the id:\"root\" component)\n components: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n component: { type: \"string\", enum: allowed },\n children: { type: \"array\", items: { type: \"string\" } },\n child: { type: \"string\" },\n binding: { type: \"string\" },\n action: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n wantResponse: { type: \"boolean\" },\n },\n required: [\"name\"],\n },\n tone: { type: \"string\", enum: [...TONES] },\n size: { type: \"string\", enum: [...SIZES] },\n emphasis: { type: \"string\", enum: [...EMPHASES] },\n align: { type: \"string\", enum: [...ALIGNS] },\n density: { type: \"string\", enum: [...DENSITIES] },\n variant: { type: \"string\" },\n text: { type: \"string\" },\n label: { type: \"string\" },\n placeholder: { type: \"string\" },\n title: { type: \"string\" },\n direction: { type: \"string\" },\n gap: { type: \"string\" },\n // Data props for data components. Several are legitimately polymorphic across\n // components — type them as their real unions so the runtime doesn't reject\n // valid output (adapters normalize each shape):\n // data: array (Chart/Table rows) | object (KeyValue)\n // rows: array (Table) | number (TextArea row count)\n // columns: array (Table col defs) | number (Grid column count)\n data: { type: [\"array\", \"object\"] },\n rows: { type: [\"array\", \"number\"] },\n items: { type: \"array\" },\n // Accept string OR object items — models routinely emit the terse string\n // form (e.g. series:[\"revenue\"], options:[\"A\",\"B\"]); adapters normalize.\n columns: { type: [\"array\", \"number\"], items: { type: [\"object\", \"string\"] } },\n series: { type: \"array\", items: { type: [\"object\", \"string\"] } },\n options: { type: \"array\", items: { type: [\"object\", \"string\"] } },\n kind: { type: \"string\" },\n x: { type: \"string\" },\n value: {},\n },\n required: [\"id\", \"component\"],\n },\n },\n dataModel: { type: \"object\" },\n },\n required: [\"surfaceId\", \"root\", \"components\"],\n additionalProperties: false,\n };\n}\n","import type { CatalogManifest } from \"./registry\";\nimport { TONES, SIZES } from \"./style\";\n\n/**\n * Build the compact GenUI prompt clause from the catalog, filtered to an allowlist.\n * Teaches the allowed components, the style vocabulary, the wantResponse round-trip\n * rule, and the \"don't reproduce the UI as text\" rule.\n */\nexport function buildGenuiClause(manifest: CatalogManifest, allowlist: string[]): string {\n const names = allowlist.filter((n) => n in manifest.components);\n return [\n \"You can render UI by calling render_ui with an A2UI surface (a flat components array; each item is { id, component, children?, ...props }; component is one of the allowed names; children are string ids referencing other items).\",\n `Components: ${names.join(\", \")}.`,\n `Style each component via the semantic vocabulary (never CSS, colors, or HTML): tone (${TONES.join(\"/\")}), size (${SIZES.join(\"/\")}), emphasis (low/medium/high), align (start/center/end), density (compact/comfortable), plus a component-specific variant where offered.`,\n \"Data components MUST carry their data: Chart takes `data` (an array of row objects) + `series` (keys to plot) + `x` (the category key); Table takes `rows` (array of row objects) + `columns` ([{ key, header }] matching the row keys); List takes `items` (array); Stat takes `label`+`value`; KeyValue takes `data` (an object). Put the data inline on the component (or in dataModel referenced via `binding`).\",\n \"To collect input, add a Button with an action { name, wantResponse: true }. You get back { action, surfaceId, componentId, data } — `data` is the collected data model and `componentId` is the id of the component that was acted on. A surface with no such button is display-only.\",\n \"When you render several options to choose from (a grid of cards, each with its own button), give every option component a MEANINGFUL id (e.g. flight-NH107, hotel-memmo-alfama): `componentId` tells you which one the user picked, so never ask them to repeat a choice they already made.\",\n 'The user may ignore an interactive surface and just type instead. You then receive action \"userDismissedSurface\" with their words in `userMessage` — treat it as their reply, answer it directly, and do not re-render the same surface or scold them for not using it.',\n \"IMPORTANT: the rendered surface IS your reply — do NOT reproduce its content as text, markdown, or ASCII; a one-line intro at most.\",\n \"Prefer plain text for simple replies.\",\n ].join(\" \");\n}\n","import { zodToJsonSchema } from \"zod-to-json-schema\";\nimport type { CatalogManifest } from \"./registry\";\n\n/**\n * `zodToJsonSchema`'s generic return type triggers TS2589 (excessively deep) during .d.ts\n * generation. Call it through a plain, non-generic signature — we only read properties/required.\n */\nconst toJsonSchema = zodToJsonSchema as unknown as (\n _schema: unknown,\n _opts?: unknown,\n) => { properties?: Record<string, unknown>; required?: string[] };\n\n/**\n * The A2UI-format catalog JSON — the published, versioned contract. Emitted from the\n * authoring catalog (the zod `CatalogManifest`) so the shipped artifact can never drift\n * from what the SDK validates against (guarded by emit.test.ts).\n */\nexport interface A2uiCatalogJson {\n $schema: string;\n catalogId: string;\n title: string;\n description: string;\n components: Record<string, unknown>;\n $defs: Record<string, unknown>;\n}\n\n/** Shared A2UI type defs referenced by (future, DynamicString-bound) components. */\nconst SHARED_DEFS: Record<string, unknown> = {\n DynamicString: {\n description: \"A literal string OR a data-model path reference { path }.\",\n oneOf: [\n { type: \"string\" },\n { type: \"object\", properties: { path: { type: \"string\" } }, required: [\"path\"], additionalProperties: false },\n ],\n },\n Action: {\n description: \"A semantic action (never a URL). wantResponse:true returns the data model to the agent.\",\n type: \"object\",\n properties: { name: { type: \"string\" }, wantResponse: { type: \"boolean\" } },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\n/**\n * Compile the authoring catalog to the A2UI v1.0 catalog format:\n * `{ catalogId, components: { Name: {type:object, properties:{ component:{const}, …}, required, unevaluatedProperties:false } }, $defs }`.\n */\nexport function emitA2uiCatalog(manifest: CatalogManifest, opts: { catalogId: string }): A2uiCatalogJson {\n const components: Record<string, unknown> = {};\n\n for (const [name, def] of Object.entries(manifest.components)) {\n const propsSchema = toJsonSchema(def.schema, { $refStrategy: \"none\", target: \"jsonSchema2020\" });\n const properties: Record<string, unknown> = {\n component: { const: name },\n ...(propsSchema.properties ?? {}),\n };\n const required = Array.from(new Set([\"component\", ...(propsSchema.required ?? [])]));\n components[name] = {\n type: \"object\",\n properties,\n required,\n // Presentational props are open at authoring time (zod .passthrough()); the tool\n // schema is where the model-facing prop set is fixed. Keep the catalog permissive.\n unevaluatedProperties: false,\n };\n }\n\n return {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n catalogId: opts.catalogId,\n title: \"Alquimia Core Catalog\",\n description:\n \"Alquimia's default A2UI catalog. Abstract, framework-agnostic component contract; \" +\n \"consumers map each component to their own (shadcn) renderer. Generated from the SDK authoring catalog.\",\n components,\n $defs: SHARED_DEFS,\n };\n}\n","\nimport { useState, useReducer } from \"react\";\nimport { RatingData } from \"../types/type\";\nimport { getTopicSessionId } from \"../utils/utils\";\n\ninterface RatingState {\n ratingStars: number;\n ratingThumbs: \"thumbsUp\" | \"thumbsDown\" | \"\";\n ratingComment: string;\n}\n\ntype RatingAction =\n | { type: \"SET_RATING_STARS\"; payload: number }\n | { type: \"SET_RATING_THUMBS\"; payload: \"thumbsUp\" | \"thumbsDown\" | \"\" }\n | { type: \"SET_RATING_COMMENT\"; payload: string };\n\nconst initialState: RatingState = {\n ratingStars: 0,\n ratingThumbs: \"\",\n ratingComment: \"\",\n};\n\nfunction ratingReducer(state: RatingState, action: RatingAction): RatingState {\n switch (action.type) {\n case \"SET_RATING_STARS\":\n return { ...state, ratingStars: action.payload };\n case \"SET_RATING_THUMBS\":\n return { ...state, ratingThumbs: action.payload };\n case \"SET_RATING_COMMENT\":\n return { ...state, ratingComment: action.payload };\n default:\n return state;\n }\n}\n\ninterface UseRatingsParams {\n assistantId: string;\n topicId: string;\n sendRating: (_ratingData: RatingData) => Promise<any>;\n onError?: (_componentName: string, _error: Error) => void;\n}\n\n\nexport function useRatings({ assistantId, sendRating, topicId, onError }: UseRatingsParams) {\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [hasReviewed, setHasReviewed] = useState<boolean>(false);\n const [state, dispatch] = useReducer(ratingReducer, initialState);\n\n const setRatingStars = (rating: number) => {\n dispatch({ type: \"SET_RATING_STARS\", payload: rating });\n };\n\n const _setRatingThumbs = (rating: \"thumbsUp\" | \"thumbsDown\" | \"\") => {\n dispatch({ type: \"SET_RATING_THUMBS\", payload: rating });\n };\n\n const setRatingComment = (comment: string) => {\n dispatch({ type: \"SET_RATING_COMMENT\", payload: comment });\n };\n\n const thumbsScore = (value: string) => {\n return value === \"thumbsUp\" ? 5 : value === \"thumbsDown\" ? 0 : 0;\n }\n\n const handleRate = async (key: string, value: any | string, onHandleRateSuccess: (_success: boolean, _err?: string) => void) => {\n setIsLoading(true);\n const sessionId = getTopicSessionId(topicId);\n\n const ratingObj: RatingData = {\n topicId: parseInt(topicId),\n sessionId: sessionId || \"\",\n assistantId: assistantId,\n score: key === \"score\" ? value : thumbsScore(value),\n description: key === \"description\" ? value : state.ratingComment,\n };\n\n try {\n const response = await sendRating(ratingObj);\n if (!response.success) {\n setIsLoading(false);\n const error = new Error(response.error?.message ?? \"Failed to send rating\");\n onHandleRateSuccess(false, error.message);\n onError?.(\"useRatings\", error);\n return;\n }\n\n if (key === \"score\") {\n setRatingStars(value);\n } else if (key === \"description\") {\n setRatingComment(value);\n }\n setHasReviewed(true);\n setIsLoading(false);\n onHandleRateSuccess(true);\n } catch (err) {\n setIsLoading(false);\n const error = err instanceof Error ? err : new Error(String(err));\n onHandleRateSuccess(false, error.message);\n onError?.(\"useRatings\", error);\n }\n };\n\n return {\n handleRate,\n ratingStars: state.ratingStars,\n ratingThumbs: state.ratingThumbs,\n ratingComment: state.ratingComment,\n isLoading,\n hasReviewed\n };\n}\n"],"mappings":";AAAA,SAAS,eAAAA,cAAa,WAAW,SAAS,QAAQ,gBAAgB;;;ACAlE,OAAO,WAA8B;AAYrC,IAAM,cAAN,MAAkB;AAAA,EAuBhB,YACE,aACA,SACA,UAA8B,CAAC,GAC/B;AAvBF,SAAQ,iBAAgC;AACxC,SAAQ,YAA2B;AAEnC;AAAA,SAAQ,WAA0B;AAElC;AAAA,SAAQ,cAA6B;AACrC,SAAQ,QAAa,CAAC;AACtB,SAAQ,oBAAmD;AAC3D,SAAQ,kBAAuB;AAC/B,SAAQ,SAAwB;AAOhC,SAAQ,cAAmC,CAAC;AAC5C,SAAQ,sBAAgC,CAAC;AAOvC,QAAI,CAAC,aAAa;AAChB,YAAM,IAAI,MAAM,sCAAsC;AAAA,IACxD;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,cAAc;AACnB,SAAK,UAAU;AACf,SAAK,0BAA0B,QAAQ,2BAA2B;AAElE,SAAK,gBAAgB,MAAM,OAAO;AAClC,SAAK,cAAc,aAAa,SAAS;AAAA,MACvC,CAAC,aAAa;AAAA,MACd,OAAO,UAAU;AACf,YAAI,MAAM,UAAU,UAAU,KAAK,gBAAgB;AACjD,gBAAM,KAAK,eAAe,SAAS,gBAAgB,OAAO;AAAA,YACxD,KAAK,MAAM,OAAO;AAAA,YAClB,QAAQ,MAAM,OAAO;AAAA,YACrB,MAAM,MAAM,OAAO;AAAA,YACnB,QAAQ,MAAM,SAAS;AAAA,YACvB,cAAc,MAAM,SAAS;AAAA,UAC/B,CAAC;AAAA,QACH;AACA,eAAO,QAAQ,OAAO,KAAK;AAAA,MAC7B;AAAA,IACF;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B,OAAO;AAE3C,UAAM,YAAwB;AAAA,MAC5B,SAAS,SAAS,OAAO;AAAA,MACzB,WAAY,aAAa;AAAA,MACzB;AAAA,MACA,OAAO,QAAQ,UAAU,QAAQ,YAAY,KAAK;AAAA,MAClD,aAAa,QAAQ,gBAAgB,QAAQ,MAAM;AAAA,IACrD;AAEA,QAAI;AACF,YAAM,WAAW,MAAM,WAAW,SAAS;AAC3C,UAAI,CAAC,SAAS,SAAS;AACrB,qBAAa,KAAK;AAClB,cAAM,QAAQ,IAAI,MAAM,SAAS,OAAO,WAAW,uBAAuB;AAC1E,4BAAoB,OAAO,MAAM,OAAO;AACxC,kBAAU,cAAc,KAAK;AAC7B;AAAA,MACF;AAEA,UAAI,QAAQ,SAAS;AACnB,uBAAe,KAAK;AAAA,MACtB,WAAW,QAAQ,eAAe;AAChC,yBAAiB,KAAK;AAAA,MACxB;AACA,qBAAe,IAAI;AACnB,mBAAa,KAAK;AAClB,0BAAoB,IAAI;AAAA,IAC1B,SAAS,KAAK;AACZ,mBAAa,KAAK;AAClB,YAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAChE,0BAAoB,OAAO,MAAM,OAAO;AACxC,gBAAU,cAAc,KAAK;AAAA,IAC/B;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,aAAa,MAAM;AAAA,IACnB,cAAc,MAAM;AAAA,IACpB,eAAe,MAAM;AAAA,IACrB;AAAA,IACA;AAAA,EACF;AACF;","names":["useCallback","pos","z","z","z","z","def","sessionId","input","messages","useCallback","useState","useReducer","useState","useReducer"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/alquimia.hook.tsx","../../src/sdk/alquimia-sdk.ts","../../src/utils/utils.ts","../../src/worklog/types.ts","../../src/worklog/registry.ts","../../src/worklog/reducer.ts","../../src/worklog/use-worklog.ts","../../src/worklog/from-frame.ts","../../src/worklog/approvals.ts","../../src/hooks/pending-client-tool.ts","../../src/genui/style.ts","../../src/genui/registry.ts","../../src/genui/catalog.ts","../../src/genui/actions.ts","../../src/genui/validate.ts","../../src/genui/tool-schema.ts","../../src/genui/clause.ts","../../src/genui/emit.ts","../../src/hooks/useRatings.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport AlquimiaSDK from '../sdk/alquimia-sdk';\nimport type { AlquimiaAdapter } from '../adapters';\nimport {\n WhisperProvider,\n StableDiffusionProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport {\n AIMessageChunk,\n AlquimiaMessage,\n AlquimiaEventData,\n AssistantInferenceResponse,\n ToolEvent,\n GenuiSurfaceItem,\n} from '../types/type';\nimport { createMessageId, mergeThinkingsByControlId, mergeToolEvents, resolveGenuiAllow } from '../utils';\nimport {\n reduceWorklog,\n initialWorklogState,\n frameToRecord,\n reduceApprovals,\n initialApprovalsState,\n listApprovals,\n type WorklogState,\n type ApprovalRequest,\n type ApprovalsState,\n} from '../worklog';\nimport type { ToolApprovalResult } from '../types';\nimport { extractPendingClientTool, type PendingClientTool } from './pending-client-tool';\nimport type { ToolExecutionResponse, UIAction, CatalogManifest } from '../genui';\nimport {\n validateSurface,\n buildRenderUiSchema,\n buildGenuiClause,\n coreCatalog,\n buildSurfaceResult,\n buildDismissResult,\n} from '../genui';\n\nexport interface UseAlquimiaConfig {\n assistantId: string;\n adapter: AlquimiaAdapter;\n providers?: {\n whisper?: WhisperProvider;\n stableDiffusion?: StableDiffusionProvider;\n characterization?: CharacterizationProvider;\n ratings?: RatingsProvider;\n logger?: LoggerProvider;\n };\n options?: {\n enforceCharacterization?: boolean;\n userId?: string;\n extraInstructions?: Record<string, string>;\n worklog?: boolean;\n };\n genui?: {\n catalog?: CatalogManifest;\n allow?: string[] | 'all';\n source?: 'client' | 'agent';\n };\n}\n\n\n/**\n * A human-approval gate as the hook exposes it: what the worklog says, overlaid\n * with this client's own submission.\n */\nexport interface ToolApproval extends ApprovalRequest {\n /**\n * `pending` until someone decides; `submitting` while this client's call is\n * in flight; `approved`/`rejected` once the runtime accepted a decision —\n * this client's (optimistically, before the stream confirms) or anyone's.\n */\n status: 'pending' | 'submitting' | 'approved' | 'rejected';\n /** Rejection reason, from the worklog or from this client's submission. */\n reason: string | null;\n /** `true` when the accepted decision was made from this client. */\n decidedHere: boolean;\n /**\n * Whether offering Approve / Reject here can still work. `false` for a\n * channel-owned gate, and after the runtime refused this client with a 409,\n * 403 or 404 — retrying those can only fail the same way.\n */\n canAnswer: boolean;\n /** The runtime's answer to this client's last submission, if any. */\n lastResult: ToolApprovalResult | null;\n /** Message count the gate was raised after, for anchoring it in the chat. */\n afterCount: number;\n}\n\ninterface ApprovalSubmission {\n inFlight: boolean;\n approved: boolean;\n reason: string | null;\n result: ToolApprovalResult | null;\n}\n\nconst TERMINAL_REFUSALS = new Set(['already-decided', 'wrong-channel', 'not-pending', 'not-found', 'forbidden']);\n\nexport function useAlquimia(config: UseAlquimiaConfig) {\n const sdk = useMemo(() => {\n const instance = new AlquimiaSDK(config.assistantId, config.adapter, {\n enforceCharacterization: config.options?.enforceCharacterization,\n });\n\n if (config.providers?.whisper) instance.withWhisperProvider(config.providers.whisper);\n if (config.providers?.stableDiffusion) instance.withStableDiffusionProvider(config.providers.stableDiffusion);\n if (config.providers?.characterization) instance.withAnalyzeCharacterizationProvider(config.providers.characterization);\n if (config.providers?.ratings) instance.withRatingsProvider(config.providers.ratings);\n if (config.providers?.logger) instance.withLoggerProvider(config.providers.logger);\n if (config.options?.userId) instance.withUserId(config.options.userId);\n if (config.options?.extraInstructions) instance.withExtraInstructions(config.options.extraInstructions);\n\n if (config.genui && (config.genui.source ?? 'client') === 'client') {\n const cat = config.genui.catalog ?? coreCatalog;\n const allow = resolveGenuiAllow(cat, config.genui.allow);\n instance.withTools([buildRenderUiSchema(cat, allow)]);\n instance.withExtraInstructions({\n ...(config.options?.extraInstructions ?? {}),\n genui: buildGenuiClause(cat, allow),\n });\n }\n\n return instance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [config.assistantId, config.adapter]);\n\n const [input, setInput] = useState<string>('');\n const [isMessageLoading, setIsMessageLoading] = useState<boolean>(false);\n const [isStreamingLoading, setIsStreamingLoading] = useState<boolean>(false);\n const [isMessageStreaming, setIsMessageStreaming] = useState<boolean>(false);\n const [streamingMessageId, setStreamingMessageId] = useState<string | null>(null);\n const [isAudioRecording, setIsAudioRecording] = useState<boolean>(false);\n const [messages, setMessages] = useState<AlquimiaMessage[]>([]);\n const eventSourceRef = useRef<EventSource | null>(null);\n const streamUserCancelledRef = useRef(false);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [activeTool, setActiveTool] = useState<any | null>(null);\n const [lastRequest, setLastRequest] = useState<string | null>(null);\n const [hasThinkings, setHasThinkings] = useState<boolean>(false);\n const worklogEnabled = config.options?.worklog ?? false;\n const [worklog, setWorklog] = useState<WorklogState | undefined>(\n worklogEnabled ? initialWorklogState() : undefined\n );\n const [attachments, setAttachments] = useState<File[]>([]);\n const [isUploadingAttachments, setIsUploadingAttachments] = useState<boolean>(false);\n const [pendingClientTool, setPendingClientTool] = useState<PendingClientTool | null>(null);\n // Tracks control_ids already completed so a re-render never double-submits.\n const completedToolsRef = useRef<Set<string>>(new Set());\n // Human-approval gates. Always tracked, not only with `options.worklog`: a\n // gate left unanswered parks the inference forever, so it cannot be opt-in.\n const [approvalsState, setApprovalsState] = useState<ApprovalsState>(initialApprovalsState);\n const approvalsStateRef = useRef(approvalsState);\n approvalsStateRef.current = approvalsState;\n const [approvalSubmissions, setApprovalSubmissions] = useState<Record<string, ApprovalSubmission>>({});\n // One promise per control id while in flight or once accepted, so a double\n // click or a re-render resolves to the same answer instead of a second POST.\n const approvalCallsRef = useRef<Map<string, Promise<ToolApprovalResult>>>(new Map());\n const approvalAnchorsRef = useRef<Record<string, number>>({});\n // GenUI surface lifecycle state.\n const genuiCatalog = config.genui?.catalog ?? coreCatalog;\n const [genuiSurfaces, setGenuiSurfaces] = useState<GenuiSurfaceItem[]>([]);\n const messagesLenRef = useRef(0);\n messagesLenRef.current = messages.length;\n // Anchor a surface right after the last USER message — BEFORE any assistant output\n // (including the streaming placeholder). Otherwise the surface anchors after the\n // placeholder and the agent's reply (and its loader) render ABOVE the surface.\n const genuiAnchorRef = useRef(0);\n {\n let anchor = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n if ((messages[i] as { role?: string }).role === 'user') {\n anchor = i + 1;\n break;\n }\n }\n genuiAnchorRef.current = anchor;\n }\n\n const isLoading = isMessageLoading || isStreamingLoading || isUploadingAttachments;\n\n function cleanMessages() {\n setMessages([]);\n setHasThinkings(false);\n }\n\n function addAttachment(file: File) {\n setAttachments((prev) => [...prev, file]);\n }\n\n function addAttachments(files: File[]) {\n setAttachments((prev) => [...prev, ...files]);\n }\n\n function removeAttachment(index: number) {\n setAttachments((prev) => prev.filter((_, i) => i !== index));\n }\n\n function clearAttachments() {\n setAttachments([]);\n }\n\n function processMessageChunk(\n messageId: string,\n chunk: string,\n error_code?: string,\n error_detail?: string,\n taskid?: string,\n additionalInfo?: string,\n loading?: boolean,\n tooler?: ToolEvent[],\n thinkings?: any[]\n ) {\n setMessages((currentMessages) => {\n const messageIndex = currentMessages.findIndex((message) => message?.id === messageId);\n if (messageIndex !== -1) {\n const updatedMessages = [...currentMessages];\n const updatedMessage: AlquimiaMessage = {\n ...updatedMessages[messageIndex],\n content: `${updatedMessages[messageIndex]?.content || ''}${chunk}`,\n id: updatedMessages[messageIndex]?.id || '',\n role: updatedMessages[messageIndex]?.role || 'assistant',\n error_code,\n error_detail,\n taskid,\n additionalInfo,\n created_at: new Date().getTime().toString(),\n loading,\n tooler: mergeToolEvents(updatedMessages[messageIndex]?.tooler || [], tooler),\n thinkings: mergeThinkingsByControlId(\n updatedMessages[messageIndex]?.thinkings || [],\n thinkings || []\n ),\n };\n updatedMessages[messageIndex] = updatedMessage;\n return updatedMessages;\n } else {\n return [\n ...currentMessages,\n {\n content: `${chunk}`,\n role: 'assistant',\n id: messageId,\n error_code,\n error_detail,\n taskid,\n created_at: new Date().getTime().toString(),\n loading,\n tooler: mergeToolEvents([], tooler),\n thinkings,\n },\n ];\n }\n });\n }\n\n async function processAndSendMessage(\n message: string,\n options?: {\n messageType?: string;\n traceParentId?: string;\n sessionId?: string;\n additionalInfo?: string;\n }\n ) {\n addUserMessage(message, options?.messageType);\n\n const messageId = createMessageId();\n setStreamingMessageId(messageId);\n\n await sendMessage(\n message,\n (chunk: AIMessageChunk) => {\n processMessageChunk(\n messageId,\n chunk?.answer || '',\n chunk?.error_code,\n chunk?.error_detail,\n chunk?.taskid,\n options?.additionalInfo,\n chunk?.loading,\n chunk?.tooler,\n chunk?.thinkings\n );\n },\n options?.traceParentId,\n options?.sessionId\n );\n\n setInput('');\n }\n\n async function handleSubmit(\n event: React.FormEvent<HTMLFormElement>,\n traceParentId?: string,\n sessionId?: string,\n additionalInfo?: string\n ) {\n setIsMessageLoading(true);\n event.preventDefault();\n\n if (input) {\n await processAndSendMessage(input, { traceParentId, sessionId, additionalInfo });\n }\n\n setIsMessageLoading(false);\n }\n\n async function handleSystemMessage(\n message: string,\n options?: {\n traceParentId?: string;\n sessionId?: string;\n additionalInfo?: string;\n messageType?: string;\n }\n ) {\n setIsMessageLoading(true);\n\n await processAndSendMessage(message, {\n messageType: options?.messageType || 'system',\n traceParentId: options?.traceParentId,\n sessionId: options?.sessionId,\n additionalInfo: options?.additionalInfo,\n });\n\n setIsMessageLoading(false);\n }\n\n function handleInputChange(event: React.ChangeEvent<HTMLTextAreaElement>) {\n setInput(event.target.value);\n }\n\n function handleReplaceInput(input: string) {\n setInput(input);\n }\n\n function populateMessages(messages: AlquimiaMessage[]) {\n setMessages(messages);\n }\n\n function handleLoadingCancel() {\n streamUserCancelledRef.current = true;\n eventSourceRef.current?.close();\n eventSourceRef.current = null;\n setIsMessageLoading(false);\n setIsMessageStreaming(false);\n setStreamingMessageId(null);\n setIsStreamingLoading(false);\n setIsUploadingAttachments(false);\n setInput('');\n }\n\n function addUserMessage(message: string, type?: string) {\n setMessages((prevMessages: AlquimiaMessage[]) => [\n ...prevMessages,\n {\n content: message,\n role: 'user',\n type: type,\n id: createMessageId(),\n created_at: new Date().getTime().toString(),\n },\n ]);\n }\n\n function getCookie(name: string): string | null {\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const [cookieName, cookieValue] = cookie.trim().split('=');\n if (cookieName === name) {\n return decodeURIComponent(cookieValue as string);\n }\n }\n return null;\n }\n\n function cleanup(isStreaming: boolean, event: EventSource) {\n setIsMessageStreaming(isStreaming);\n setStreamingMessageId(null);\n setIsStreamingLoading(false);\n event.close();\n }\n\n async function sendMessage(\n message: string,\n callBack: (_chunk: AIMessageChunk) => void,\n traceParentId?: string,\n sessionId?: string\n ) {\n setIsStreamingLoading(true);\n callBack({ type: 'loading', loading: true });\n const conversationId = sessionId || getCookie('alquimia-session');\n setIsMessageStreaming(true);\n setActiveTool(null);\n setLastRequest(message);\n\n try {\n const hasAttachments = attachments.length > 0;\n const sdkCall = sdk.withConversationId(conversationId || '');\n\n if (hasAttachments) {\n sdkCall.withAttachments(\n attachments.map((f) => ({\n filename: f.name,\n content_type: f.type,\n content_size: f.size,\n }))\n );\n }\n\n const response = await sdkCall.sendMessage(message, traceParentId);\n\n if (hasAttachments) {\n setIsUploadingAttachments(true);\n try {\n const attachmentResponses = response.getAttachmentResponses();\n await Promise.all(\n attachments.map((file, i) => response.uploadAttachment(file, attachmentResponses[i]))\n );\n } catch (uploadError: any) {\n setIsUploadingAttachments(false);\n setIsMessageStreaming(false);\n setStreamingMessageId(null);\n setIsStreamingLoading(false);\n callBack({\n type: 'error',\n error_code: 'ATTACHMENT_UPLOAD_ERROR',\n error_detail: uploadError.message || 'Failed to upload attachment',\n });\n return;\n }\n setIsUploadingAttachments(false);\n clearAttachments();\n }\n\n const streamUrl = response.getUrlStream();\n const streamId = response.getStreamId() || '';\n streamUserCancelledRef.current = false;\n const streamState = {\n streamId,\n connectedAt: Date.now(),\n openedAt: null as number | null,\n messagesReceived: 0,\n lastMessageAt: null as number | null,\n closedByClient: false,\n };\n\n if (worklogEnabled) setWorklog(initialWorklogState());\n\n const eventSource = new EventSource(streamUrl);\n eventSourceRef.current = eventSource;\n\n eventSource.onopen = () => {\n streamState.openedAt = Date.now();\n };\n\n eventSource.onmessage = (event) => {\n streamState.messagesReceived++;\n streamState.lastMessageAt = Date.now();\n handleMessageEvent(event, callBack, eventSource, streamState);\n };\n\n eventSource.onerror = () => {\n if (streamState.closedByClient) return;\n if (streamUserCancelledRef.current) {\n streamUserCancelledRef.current = false;\n return;\n }\n\n streamState.closedByClient = true;\n\n const elapsed = Date.now() - streamState.connectedAt;\n const sinceLastMessage = streamState.lastMessageAt\n ? Date.now() - streamState.lastMessageAt\n : null;\n\n cleanup(false, eventSource);\n\n let errorDetail: string;\n if (!streamState.openedAt) {\n errorDetail =\n 'Could not open the live response. Check your connection and try again.';\n } else if (streamState.messagesReceived === 0) {\n errorDetail = 'No response was received. Try again in a moment.';\n } else {\n errorDetail = 'The response was interrupted. Try again.';\n }\n\n if (typeof console !== 'undefined' && console.debug) {\n console.debug('[Alquimia] SSE transport error', {\n streamUrl,\n taskId: streamId,\n opened: Boolean(streamState.openedAt),\n messagesReceived: streamState.messagesReceived,\n elapsedMs: elapsed,\n sinceLastMessageMs: sinceLastMessage,\n });\n }\n\n callBack({\n type: 'error',\n error_code: 'STREAM_ERROR',\n error_detail: errorDetail,\n taskid: streamId,\n });\n };\n } catch (error: any) {\n console.error('Error sending message:', error);\n const errMessage =\n error.response?.data?.detail || error.message || 'Error initiating the stream.';\n setIsUploadingAttachments(false);\n setIsMessageStreaming(false);\n setStreamingMessageId(null);\n callBack({\n type: 'error',\n error_code:\n error.response?.status != null\n ? String(error.response.status)\n : 'REQUEST_ERROR',\n error_detail: errMessage,\n });\n }\n }\n\n function handleMessageEvent(\n event: MessageEvent,\n callBack: (_chunk: AIMessageChunk) => void,\n eventSource: EventSource,\n streamState?: {\n streamId: string;\n closedByClient: boolean;\n messagesReceived: number;\n }\n ) {\n const data: AlquimiaEventData = JSON.parse(event.data);\n if (worklogEnabled) {\n setWorklog((prev) => reduceWorklog(prev ?? initialWorklogState(), frameToRecord(data)));\n }\n\n // Approval gates open and close on the stream. The close may come from\n // another operator or the originating channel, never only from our POST,\n // so this is the one place a gate settles.\n if (\n (data.event_class === 'HumanApprovalRequired' ||\n data.event_class === 'HumanApprovalRequiredResponse') &&\n data.control_id\n ) {\n if (!(data.control_id in approvalAnchorsRef.current)) {\n approvalAnchorsRef.current[data.control_id] = genuiAnchorRef.current;\n }\n const record = frameToRecord(data);\n setApprovalsState((prev) => reduceApprovals(prev, record));\n return;\n }\n\n // A client tool (e.g. render_ui) arrived on the stream. Surface it so the UI\n // can render the A2UI surface and complete it via `completeToolExecution`.\n // Inference is paused server-side until the completion POST lands.\n const pending = extractPendingClientTool(data);\n if (pending) {\n setPendingClientTool(pending);\n return;\n }\n\n const eventTaskId = data.taskid || '';\n\n if (data.errors?.length) {\n for (const error of data.errors) {\n const detail =\n error.error_detail ||\n (error.data != null\n ? `${error.data} (controlId: ${error.control_id})`\n : 'Unknown error');\n callBack({\n type: 'error',\n error_code: error.event_class || error.status || 'UNKNOWN_ERROR',\n error_detail: detail,\n taskid: eventTaskId,\n });\n }\n if (streamState) streamState.closedByClient = true;\n cleanup(false, eventSource);\n return;\n }\n\n if (data.tools_output?.length) {\n callBack({ type: 'answer', answer: '', tooler: data.tools_output });\n }\n\n if (data.thinkings?.length) {\n setHasThinkings(true);\n callBack({ type: 'answer', thinkings: data.thinkings });\n }\n\n if (data.event_class === 'AssistantInferenceResponse') {\n const final = data as AssistantInferenceResponse;\n callBack({ type: 'answer', answer: final.data });\n if (streamState) streamState.closedByClient = true;\n cleanup(false, eventSource);\n }\n }\n\n /**\n * Complete a pending client-tool execution. Interactive `render_ui` surfaces\n * pass the user's data as `result`; display-only surfaces pass `{ shown: true }`.\n * Idempotent per `control_id` (a second call for the same id is a no-op) and\n * stable across renders, so consumers can call it from an effect without\n * guarding against double-submits themselves. Clears the pending state on\n * success so inference can resume.\n */\n const completeToolExecution = useCallback(\n async (controlId: string, result: ToolExecutionResponse) => {\n if (completedToolsRef.current.has(controlId)) return;\n completedToolsRef.current.add(controlId);\n try {\n await sdk.submitToolResult({ ...result, control_id: controlId });\n setPendingClientTool((cur) => (cur?.controlId === controlId ? null : cur));\n } catch (err) {\n // Allow a retry if the submit failed.\n completedToolsRef.current.delete(controlId);\n throw err;\n }\n },\n [sdk],\n );\n\n /**\n * Answer a pending human-approval gate. `controlId` is the gate's\n * (`ToolApproval.controlId`); `message` is an optional reason, persisted in\n * the runtime's audit trail. Resolves to the runtime's classified answer and\n * never throws for a refusal. Idempotent per gate: a second call while one is\n * in flight, or after one was accepted, returns the same answer.\n *\n * The gate itself settles when its `HumanApprovalRequiredResponse` arrives on\n * the stream — `status` reflects an accepted local decision right away, but\n * `decision` stays the worklog's.\n */\n const approveTool = useCallback(\n (controlId: string, approved: boolean, message?: string): Promise<ToolApprovalResult> => {\n const existing = approvalCallsRef.current.get(controlId);\n if (existing) return existing;\n if (approvalsStateRef.current.byId[controlId]?.decision) {\n return Promise.resolve({ outcome: 'already-decided' as const });\n }\n\n const reason = message?.trim() || null;\n setApprovalSubmissions((prev) => ({\n ...prev,\n [controlId]: { inFlight: true, approved, reason, result: prev[controlId]?.result ?? null },\n }));\n\n const call = sdk\n .submitToolApproval(controlId, approved, reason ?? undefined)\n .catch((error: unknown) => ({\n outcome: 'error' as const,\n detail: error instanceof Error ? error.message : String(error),\n }))\n .then((result) => {\n // Keep the promise only if it settled the gate; anything else may be retried.\n if (result.outcome !== 'accepted') approvalCallsRef.current.delete(controlId);\n setApprovalSubmissions((prev) => ({\n ...prev,\n [controlId]: { inFlight: false, approved, reason, result },\n }));\n return result;\n });\n approvalCallsRef.current.set(controlId, call);\n return call;\n },\n [sdk],\n );\n\n const toolApprovals = useMemo<ToolApproval[]>(\n () =>\n listApprovals(approvalsState).map((gate) => {\n const sub = approvalSubmissions[gate.controlId];\n const acceptedHere = sub?.result?.outcome === 'accepted';\n const refused = !!sub?.result && TERMINAL_REFUSALS.has(sub.result.outcome);\n\n let status: ToolApproval['status'] = 'pending';\n if (gate.decision) status = gate.decision.approved ? 'approved' : 'rejected';\n else if (sub?.inFlight) status = 'submitting';\n else if (acceptedHere) status = sub.approved ? 'approved' : 'rejected';\n\n return {\n ...gate,\n status,\n reason: gate.decision?.reason ?? (acceptedHere && !sub.approved ? sub.reason : null),\n decidedHere:\n acceptedHere && (gate.decision ? gate.decision.approved === sub.approved : true),\n canAnswer: status === 'pending' && !gate.channelOwned && !refused,\n lastResult: sub?.result ?? null,\n afterCount: approvalAnchorsRef.current[gate.controlId] ?? 0,\n };\n }),\n [approvalsState, approvalSubmissions],\n );\n\n const pendingApprovals = useMemo(\n () => toolApprovals.filter((a) => a.status === 'pending' || a.status === 'submitting'),\n [toolApprovals],\n );\n\n // ---- GenUI surface lifecycle (only active when config.genui is set) ----\n useEffect(() => {\n if (!config.genui) return;\n if (!pendingClientTool || pendingClientTool.toolName !== 'render_ui') return;\n const { controlId } = pendingClientTool;\n // Stamp the active catalog id if the agent omitted it, so the client always knows\n // which catalog version to render against (Tier 2 authoritative catalogId).\n const parameters =\n pendingClientTool.parameters && typeof pendingClientTool.parameters === 'object'\n ? { catalogId: genuiCatalog.id, ...(pendingClientTool.parameters as Record<string, unknown>) }\n : pendingClientTool.parameters;\n\n const res = validateSurface(parameters, genuiCatalog);\n if (!res.ok || !res.value) {\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'error',\n message:\n 'Surface failed client validation: ' + res.errors.map((e) => `${e.path} ${e.message}`).join('; '),\n result: { errors: res.errors },\n });\n return;\n }\n\n const surface = res.value;\n setGenuiSurfaces((prev) =>\n prev.some((s) => s.controlId === controlId)\n ? prev\n : [...prev, { controlId, surface, afterCount: genuiAnchorRef.current }]\n );\n\n const interactive = surface.components.some((c) => c.action?.wantResponse === true);\n if (!interactive) {\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'success',\n result: {\n shown: true,\n instruction:\n 'The UI is rendered and visible to the user. Do NOT restate it as text/markdown/ASCII; reply with at most one short sentence.',\n },\n });\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingClientTool, completeToolExecution, config.genui]);\n\n const genuiOnAgentAction = useCallback(\n (controlId: string) => (action: UIAction) => {\n setGenuiSurfaces((prev) =>\n prev.map((s) => (s.controlId === controlId ? { ...s, submitted: true } : s)),\n );\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'success',\n // Includes componentId, so the agent can tell which element was acted on when\n // several share one action name (a grid of option cards, say).\n result: buildSurfaceResult(action),\n });\n },\n [completeToolExecution],\n );\n\n /**\n * Let the user answer an interactive surface in words instead of using it.\n */\n const genuiDismiss = useCallback(\n (userMessage?: string) => {\n if (!pendingClientTool || pendingClientTool.toolName !== 'render_ui') return;\n const { controlId } = pendingClientTool;\n const said = typeof userMessage === 'string' ? userMessage.trim() : '';\n const item = genuiSurfaces.find((s) => s.controlId === controlId);\n\n setGenuiSurfaces((prev) =>\n prev.map((s) =>\n s.controlId === controlId ? { ...s, submitted: true, dismissedWith: said || undefined } : s,\n ),\n );\n if (said) setInput('');\n void completeToolExecution(controlId, {\n control_id: controlId,\n tool_name: 'render_ui',\n status: 'success',\n result: buildDismissResult(item?.surface.surfaceId ?? '', said),\n });\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [pendingClientTool, genuiSurfaces, completeToolExecution],\n );\n\n const genuiAwaitingUser = !!(\n pendingClientTool &&\n pendingClientTool.toolName === 'render_ui' &&\n genuiSurfaces.some(\n (s) =>\n s.controlId === pendingClientTool.controlId &&\n s.surface.components.some((c) => c.action?.wantResponse === true),\n )\n );\n\n const genui = config.genui\n ? {\n surfaces: genuiSurfaces,\n onAgentAction: genuiOnAgentAction,\n awaitingUser: genuiAwaitingUser,\n dismiss: genuiDismiss,\n }\n : undefined;\n\n return {\n sdk,\n activeTool,\n pendingClientTool,\n completeToolExecution,\n toolApprovals,\n pendingApprovals,\n approveTool,\n genui,\n cleanMessages,\n createMessageId,\n handleInputChange,\n handleReplaceInput,\n handleSubmit,\n handleSystemMessage,\n handleLoadingCancel,\n input,\n isLoading,\n isMessageLoading,\n isMessageStreaming,\n isStreamingLoading,\n streamingMessageId,\n isAudioRecording,\n lastRequest,\n messages,\n populateMessages,\n processMessageChunk,\n sendMessage,\n sessionId,\n setActiveTool,\n setSessionId,\n setLastRequest,\n setIsAudioRecording,\n hasThinkings,\n worklog,\n attachments,\n addAttachment,\n addAttachments,\n removeAttachment,\n clearAttachments,\n isUploadingAttachments,\n };\n}\n","import axios, { AxiosInstance } from 'axios';\nimport {\n StableDiffusionProvider,\n WhisperProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport {\n AttachmentPayload,\n TTSResult,\n type CommonAttributes,\n type Content,\n type RuntimeBlob,\n type ToolApprovalEvent,\n type ToolApprovalOutcome,\n type ToolApprovalResult,\n} from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\n\n/** Per-turn options for {@link AlquimiaSDK.sendMessage}. */\nexport interface SendMessageOptions {\n /** W3C traceparent, so infer and stream share one trace. */\n traceParent?: string;\n /**\n * Audio input for this turn (runtime v0.5.1). Upload it with\n * {@link AlquimiaSDK.uploadAttachment} first and pass the blob it returns.\n * May be sent with or instead of `query`.\n */\n inputAudio?: RuntimeBlob;\n /**\n * Set to `false` to force a text-only reply from an audio-enabled agent.\n * The runtime defaults to `true`, so leaving this unset keeps its behaviour.\n */\n outputAudio?: boolean;\n}\n\nclass AlquimiaSDK {\n private adapter: AlquimiaAdapter;\n private assistantId: string;\n private axiosInstance: AxiosInstance;\n private conversationId: string | null = null;\n private sessionId: string | null = null;\n // Internal subscription id from infer (`taskid` on the wire).\n private streamId: string | null = null;\n // W3C traceparent for the current turn, so infer and stream share one trace.\n private traceParent: string | null = null;\n // Registry version tag resolved by the runtime for this task (v0.5.1), so\n // the tool-completion half of the turn lands on the same agentspace version.\n private versionTag: string | null = null;\n // Agentspace the runtime resolved for this task. Tool completion and\n // approval authorize a non-admin caller against it, so it is echoed back.\n private agentspaceId: string | null = null;\n private tools: any = [];\n private extraInstructions: Record<string, string> | null = null;\n private assistantConfig: any = null;\n private userId: string | null = null;\n private whisperProvider?: WhisperProvider;\n private stableDiffusionProvider?: StableDiffusionProvider;\n private analyzeCharacterizationProvider?: CharacterizationProvider;\n private ratingsProvider?: RatingsProvider;\n private loggerProvider?: LoggerProvider;\n private enforceCharacterization?: boolean;\n private attachments: AttachmentPayload[] = [];\n private attachmentResponses: string[] = [];\n\n constructor(\n assistantId: string,\n adapter: AlquimiaAdapter,\n options: AlquimiaSDKOptions = {}\n ) {\n if (!assistantId) {\n throw new Error('AlquimiaSDK: assistantId is required');\n }\n if (!adapter) {\n throw new Error(\n 'AlquimiaSDK: adapter is required. Use createNextJsAdapter() or createFetchAdapter()'\n );\n }\n\n this.assistantId = assistantId;\n this.adapter = adapter;\n this.enforceCharacterization = options.enforceCharacterization ?? true;\n\n this.axiosInstance = axios.create();\n this.axiosInstance.interceptors.response.use(\n (response) => response,\n async (error) => {\n if (error.response?.status && this.loggerProvider) {\n await this.loggerProvider.logError('Server Error', error, {\n url: error.config.url,\n method: error.config.method,\n data: error.config.data,\n status: error.response.status,\n responseData: error.response.data,\n });\n }\n return Promise.reject(error);\n }\n );\n\n this.textToSpeech = this.textToSpeech.bind(this);\n this.speechToText = this.speechToText.bind(this);\n }\n\n withConversationId(conversationId: string): AlquimiaSDK {\n this.conversationId = conversationId;\n return this;\n }\n\n withAttachments(attachments: AttachmentPayload[]): AlquimiaSDK {\n this.attachments = attachments;\n return this;\n }\n\n withWhisperProvider(provider: WhisperProvider): AlquimiaSDK {\n this.whisperProvider = provider;\n return this;\n }\n\n withStableDiffusionProvider(provider: StableDiffusionProvider): AlquimiaSDK {\n this.stableDiffusionProvider = provider;\n return this;\n }\n\n withAnalyzeCharacterizationProvider(provider: CharacterizationProvider): AlquimiaSDK {\n this.analyzeCharacterizationProvider = provider;\n return this;\n }\n\n withRatingsProvider(provider: RatingsProvider): AlquimiaSDK {\n this.ratingsProvider = provider;\n return this;\n }\n\n withLoggerProvider(provider: LoggerProvider): AlquimiaSDK {\n this.loggerProvider = provider;\n return this;\n }\n\n withTools(tools: any): AlquimiaSDK {\n this.tools = tools;\n return this;\n }\n\n withExtraInstructions(extraInstructions: Record<string, string>): AlquimiaSDK {\n this.extraInstructions = extraInstructions;\n return this;\n }\n\n withAssistantConfig(assistantConfig: any): AlquimiaSDK {\n this.assistantConfig = assistantConfig;\n return this;\n }\n\n withUserId(userId: string): AlquimiaSDK {\n this.userId = userId;\n return this;\n }\n\n /**\n * Pin inference to a cached registry version. Sent as the `version_tag`\n * query parameter, which `POST /event/infer/{assistant_id}` accepts from\n * **runtime v0.5.2** onward; older runtimes ignore it.\n *\n * Works on every version: pass a versioned assistant ref\n * (`<agentspace>/<assistant>[:<tag>]`) as the `assistantId` instead — the\n * runtime parses the tag out of the path itself.\n */\n withVersionTag(versionTag: string): AlquimiaSDK {\n this.versionTag = versionTag;\n return this;\n }\n\n getEnforceCharacterization(): boolean {\n return this.enforceCharacterization ?? true;\n }\n\n textToSpeech(text: string): Promise<TTSResult> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.textToSpeech(text);\n }\n\n speechToText(audio: string): Promise<string> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.speechToText(audio);\n }\n\n async sendMessage(\n query?: Content,\n options: string | SendMessageOptions = {}\n ): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n // Backwards-compat: the previous signature was sendMessage(query, traceParent?).\n const opts: SendMessageOptions =\n typeof options === 'string' ? { traceParent: options } : options;\n\n if (query === undefined && !opts.inputAudio) {\n throw new Error(\n 'AlquimiaSDK: sendMessage needs a query, an inputAudio blob, or both'\n );\n }\n\n const baseInferUrl = this.adapter.resolveInferUrl(this.assistantId);\n // `version_tag` is a query parameter on infer (runtime v0.5.2+), never a\n // header — the runtime reads it with `Query(...)`.\n const inferUrl = this.versionTag\n ? `${baseInferUrl}${baseInferUrl.includes('?') ? '&' : '?'}version_tag=${encodeURIComponent(this.versionTag)}`\n : baseInferUrl;\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;\n\n const initMessage: Record<string, unknown> = {\n ...(query !== undefined && { query }),\n session_id: this.conversationId,\n user_id: this.userId,\n ...(opts.inputAudio && { input_audio: opts.inputAudio }),\n // Only sent when set: the runtime defaults `output_audio` to true.\n ...(opts.outputAudio !== undefined && { output_audio: opts.outputAudio }),\n ...(this.extraInstructions && { extra_instructions: this.extraInstructions }),\n ...(this.assistantConfig && { config: this.assistantConfig }),\n ...(hasClientTools && {\n evaluation_strategy: {\n evaluation_strategy_id: 'native',\n tool_schemas: this.tools,\n },\n }),\n };\n\n const result = (\n await this.axiosInstance.post(inferUrl, initMessage, {\n headers: {\n 'Content-Type': 'application/json',\n ...(opts.traceParent && { 'x-trace-parent': opts.traceParent }),\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.traceParent = opts.traceParent ?? null;\n this.streamId = result.taskid ?? null;\n this.versionTag = result.versiontag ?? this.versionTag;\n this.agentspaceId = result.agentspaceid ?? null;\n this.attachmentResponses = result.attachments ?? [];\n this.attachments = [];\n\n return this;\n }\n\n /**\n * Complete a pending client-tool execution (the missing \"submit half\" of the\n * client-tool loop). POSTs a {@link ToolExecutionResponse} to the runtime's\n * `/event/tool-completion`. For interactive `render_ui` surfaces `result` is\n * the user's data; for display-only surfaces the SDK sends `{ shown: true }`.\n * The pending call is correlated by `control_id` in the body + the\n * `context-metadata` header (taskid + sessionid).\n */\n async submitToolResult(response: ToolExecutionResponse): Promise<void> {\n const url = this.adapter.resolveToolCompletionUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)'\n );\n }\n await this.axiosInstance.post(url, response, { headers: this.buildDecisionHeaders() });\n }\n\n /**\n * Answer a `HumanApprovalRequired` gate: POSTs a {@link ToolApprovalEvent} to\n * the runtime's `/event/tool-approval`. `controlId` is the gate's own control\n * id (the `HumanApprovalRequired` record's), not the parked tool call's.\n *\n * Never throws for a runtime refusal — each 409 means something different to\n * the UI, so the answer comes back classified as a {@link ToolApprovalResult}.\n * It does throw when the adapter has no approval route, which is a wiring bug\n * rather than a runtime answer.\n */\n async submitToolApproval(\n controlId: string,\n approved: boolean,\n message?: string\n ): Promise<ToolApprovalResult> {\n const url = this.adapter.resolveToolApprovalUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool approval (resolveToolApprovalUrl missing)'\n );\n }\n\n const event: ToolApprovalEvent = {\n event_class: 'ToolApprovalEvent',\n control_id: controlId,\n result: approved,\n ...(message && { message }),\n };\n\n try {\n await this.axiosInstance.post(url, event, { headers: this.buildDecisionHeaders() });\n return { outcome: 'accepted' };\n } catch (error) {\n return classifyApprovalError(error);\n }\n }\n\n async generateImage(query: string): Promise<string> {\n if (!this.stableDiffusionProvider) {\n throw new Error('Stable Diffusion provider not initialized');\n }\n return this.stableDiffusionProvider.generateImage(query);\n }\n\n async analyzeCharacterization(text: string): Promise<Record<string, any>> {\n if (!this.analyzeCharacterizationProvider) {\n throw new Error('Analyze characterization provider not initialized');\n }\n return this.analyzeCharacterizationProvider.analyzeCharacterization(text);\n }\n\n async rate(data: any): Promise<Record<string, any>> {\n if (!this.ratingsProvider) {\n throw new Error('Ratings provider not initialized');\n }\n return this.ratingsProvider.rate(data);\n }\n\n async logInfo(message: string, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logInfo(message, data);\n }\n\n async logError(message: string, error: Error, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logError(message, error, data);\n }\n\n /**\n * @deprecated The runtime no longer returns attachment IDs from the infer\n * response — attachments are uploaded as standalone blobs and linked to the\n * session via headers. Always returns `[]`; kept for source compatibility.\n */\n getAttachmentResponses(): string[] {\n return this.attachmentResponses;\n }\n\n /**\n * Upload a file into the session context. Returns the runtime {@link RuntimeBlob},\n * which is what `sendMessage`'s `inputAudio` expects for audio inference.\n */\n async uploadAttachment(file: File, _attachmentId?: string): Promise<RuntimeBlob> {\n void _attachmentId;\n const url = this.adapter.resolveBlobUploadUrl();\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n const formData = new FormData();\n formData.append('file', file);\n const response = await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\n return response.data as RuntimeBlob;\n }\n\n /**\n * Identity headers (kebab-case) required by `/context/blob/upload` and\n * the rest of the runtime's internal endpoints introduced in v0.2.0→next.\n */\n private buildIdentityHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'assistant-id': this.assistantId,\n };\n if (this.conversationId) headers['session-id'] = this.conversationId;\n if (this.userId) headers['user-id'] = this.userId;\n if (this.streamId) headers['task-id'] = this.streamId;\n return headers;\n }\n\n /**\n * Correlation headers for tool-completion and tool-approval: the runtime's\n * `CommonAttributes` header aliases, with no separator. Not interchangeable\n * with the kebab-case set in {@link buildIdentityHeaders}.\n */\n private buildDecisionHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n assistantid: this.assistantId,\n ...(this.streamId && { taskid: this.streamId }),\n ...(this.conversationId && { sessionid: this.conversationId }),\n ...(this.userId && { userid: this.userId }),\n ...(this.agentspaceId && { agentspaceid: this.agentspaceId }),\n ...(this.versionTag && { versiontag: this.versionTag }),\n ...(this.adapter.getHeaders?.() ?? {}),\n };\n }\n\n getUrlStream(): string {\n if (!this.streamId) {\n throw new Error('Stream ID not initialized. Call sendMessage() first');\n }\n\n const url = this.adapter.resolveStreamUrl(this.streamId);\n if (!this.traceParent) return url;\n\n // `EventSource` cannot set request headers, so the turn's traceparent rides\n // the URL. The proxy turns it back into `x-trace-parent` and does not pass\n // the param upstream; without this the stream leg — where the whole\n // inference actually happens — lands in a different trace than the infer.\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;\n }\n\n getStreamId(): string | null {\n return this.streamId;\n }\n\n /** Alias for {@link getStreamId} — same value as infer `taskid`. */\n getTaskId(): string | null {\n return this.streamId;\n }\n\n /** Registry version tag resolved by the runtime for the current task, if any. */\n getVersionTag(): string | null {\n return this.versionTag;\n }\n\n /** Agentspace the runtime resolved for the current task, if any. */\n getAgentspaceId(): string | null {\n return this.agentspaceId;\n }\n}\n\n/**\n * Map a failed `/event/tool-approval` call onto an outcome. The runtime's 409s\n * share a status and differ only in `detail` (`routers/event.py`), so matching\n * the text is the contract, not a shortcut.\n */\nfunction classifyApprovalError(error: unknown): ToolApprovalResult {\n const response = (error as { response?: { status?: number; data?: unknown } })?.response;\n const status = response?.status;\n const data = response?.data as { detail?: unknown; error?: unknown } | string | undefined;\n const rawDetail =\n typeof data === 'string' ? data : data?.detail ?? data?.error ?? (error as Error)?.message;\n const detail = typeof rawDetail === 'string' ? rawDetail : JSON.stringify(rawDetail ?? '');\n\n let outcome: ToolApprovalOutcome = 'error';\n if (status === 409) {\n if (/original channel/i.test(detail)) outcome = 'wrong-channel';\n else if (/already been recorded/i.test(detail)) outcome = 'already-decided';\n else if (/no pending approval/i.test(detail)) outcome = 'not-pending';\n } else if (status === 401 || status === 403) {\n outcome = 'forbidden';\n } else if (status === 404) {\n outcome = 'not-found';\n }\n\n return { outcome, ...(status !== undefined && { status }), detail };\n}\n\nexport default AlquimiaSDK;\n","import {\n BaseAPIConfig,\n ApiError,\n ConversationsMap,\n ThinkingsInferenceResponse,\n Tooler,\n ToolEvent,\n} from \"../types/type\";\nimport { CatalogManifest } from \"../genui\";\n\nexport function generateTranslatePrompt(text: string) {\n const prompt = `\n Arrange the following text according to the given object structure and return it as plain json, values summarized to one word, no formatting:\n {\n restrictions: {\n value: [''],\n description: 'Restrictions to certain foods'\n },\n alergies: {\n value: [''],\n description: 'Alergies to certain foods'\n },\n wine_preference: {\n value: [''],\n description: 'Preferences for the wine'\n },\n meal_preference: {\n value: [''],\n description: 'Preferences for the meal'\n }\n }\n\n Text: \"${text}\"\n\n Output:\n `;\n\n return prompt;\n}\n\nexport function getCookies(name: string) {\n if (typeof document === \"undefined\") return undefined;\n const value = `; ${document.cookie}`;\n const parts = value.split(`; ${name}=`);\n if (parts.length === 2) return parts.pop()?.split(\";\").shift();\n}\n\nexport function generateHeaders(config: BaseAPIConfig): HeadersInit {\n const headers: HeadersInit = {\n \"Content-Type\": \"application/json\",\n };\n\n if (config.token) {\n headers[\"Authorization\"] = `Bearer ${config.token}`;\n }\n\n if (config.headers) {\n Object.entries(config.headers).forEach(([key, value]) => {\n headers[key] = value;\n });\n }\n\n return headers;\n}\n\nexport function isTextContent(buffer: ArrayBuffer): boolean {\n try {\n const text = new TextDecoder().decode(buffer);\n const trimmedText = text.trim();\n\n return (\n /^[\\w#\\-*|[\\]+=\\s\\n\\r\\t!]/.test(trimmedText) ||\n trimmedText.startsWith(\"#\") ||\n trimmedText.startsWith(\"![\") ||\n trimmedText.startsWith(\"```\") ||\n trimmedText.startsWith(\"---\") ||\n /^[a-zA-Z0-9\\s\\n\\r\\t]/.test(trimmedText) ||\n /^!\\[.*\\]\\(.*\\)/.test(trimmedText)\n );\n } catch {\n return false;\n }\n}\n\nexport function getQueryParam(param: string): string | null {\n if (typeof window !== \"undefined\") {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get(param);\n }\n return null;\n}\n\nexport function defineAssistantId(defaultId: string): string {\n if (typeof window !== \"undefined\" && window.location.pathname === \"/\") {\n const queryAssistantId = getQueryParam(\"talkwith\");\n if (queryAssistantId) {\n localStorage.setItem(\"assistantId\", queryAssistantId);\n return queryAssistantId;\n }\n const storedAssistantId = localStorage.getItem(\"assistantId\");\n return storedAssistantId || defaultId;\n }\n return defaultId;\n}\n\nexport function formatTimeWithUnit(timeMs: number): string {\n if (timeMs >= 1000) {\n return `${(timeMs / 1000).toFixed(1)}s`;\n }\n return `${Math.round(timeMs)}ms`;\n}\n\nexport function serializeAxiosError(error: unknown) {\n if (error instanceof Error) {\n const customError = error as ApiError;\n return {\n message: customError?.message,\n name: customError?.name,\n stack: customError?.stack,\n code: customError?.code,\n status: customError?.status,\n };\n }\n return {\n message: String(error),\n name: \"Unknown Error\",\n };\n}\n\nexport function parseConversationsMapCookie(\n cookieValue: string\n): ConversationsMap {\n try {\n const decodedValue = decodeURIComponent(cookieValue);\n return JSON.parse(decodedValue) as ConversationsMap;\n } catch (e) {\n console.error(\"Error parsing conversations cookie:\", e);\n return {};\n }\n}\n\nexport function getTopicSessionId(topicId: string): string {\n const conversationsStr = getCookies(\"alquimia-sessions\") || \"{}\";\n if (!conversationsStr) {\n const sessionCookie = getCookies(\"alquimia-session\");\n return sessionCookie || \"\";\n }\n\n const conversationsMap = parseConversationsMapCookie(conversationsStr);\n return conversationsMap[topicId] || \"\";\n}\n\nexport function createMessageId() {\n return Math.floor(Math.random() * 1000000).toString();\n}\n\nexport function hasToolSummary(data: any) {\n return data.tool_summary && Object.keys(data.tool_summary).length > 0;\n}\n\nexport function mergeThinkingsByControlId(\n existingThinkings: ThinkingsInferenceResponse[] = [],\n newThinkings: ThinkingsInferenceResponse[] = []\n): ThinkingsInferenceResponse[] {\n const thinkingsMap = new Map(existingThinkings.map((t) => [t.control_id, t]));\n for (const t of newThinkings) {\n if (t && t.control_id) {\n thinkingsMap.set(t.control_id, t);\n }\n }\n return Array.from(thinkingsMap.values());\n}\n\n\nexport function mergeToolerByControlId(\n currentTooler: Tooler[],\n toolEvent: ToolEvent\n): Tooler[] {\n const { event_class, control_id, data, status } = toolEvent;\n const existingTool = currentTooler.find((t) => t.control_id === control_id);\n const base: Tooler = existingTool || { control_id };\n\n let updated: Tooler;\n switch (event_class) {\n case \"ServerToolExecutionCommand\":\n updated = {\n ...base,\n tool_summary: {\n name: data.name,\n parameters: data,\n },\n };\n break;\n case \"ToolExecutionResponse\":\n updated = {\n ...base,\n tool_output: {\n result: data,\n status,\n },\n };\n break;\n case \"A2AInferenceCommand\":\n updated = {\n ...base,\n tool_summary: {\n name: data.name,\n parameters: { ...data, type: \"A2A\" },\n },\n };\n break;\n default:\n return currentTooler;\n }\n\n return currentTooler.some(tool => tool.control_id === control_id)\n ? currentTooler.map(tool => (tool.control_id === control_id ? updated : tool))\n : [...currentTooler, updated];\n}\n\nexport function mergeToolEvents(\n initial: Tooler[],\n toolEvents?: ToolEvent[]\n): Tooler[] {\n return (toolEvents ?? []).reduce(\n (acc, toolEvent) => mergeToolerByControlId(acc, toolEvent),\n initial\n );\n}\n\nexport function resolveGenuiAllow(catalog: CatalogManifest, allow?: string[] | 'all'): string[] {\n return !allow || allow === 'all' ? Object.keys(catalog.components) : allow;\n}\n","/** One granular Runtime worklog record (a `bus_mode` SSE frame or a `/worklog/{task_id}/events` item). */\nexport interface WorklogRecord {\n /** Runtime v0.5.0+ tamper-evident hash chain fields (optional on SSE frames). */\n entry_hash?: string | null;\n previous_hash?: string | null;\n event_class: string;\n control_id: string | null;\n data: unknown;\n status: \"success\" | \"error\" | null;\n date_submitted: string;\n}\n\n/** Runtime v0.5.0 worklog audit summary returned by `GET /worklog/`. */\nexport interface WorklogSummary {\n task_id: string;\n parent_task_id?: string | null;\n session_id?: string | null;\n user_id?: string | null;\n assistant_id?: string | null;\n agentspace_id?: string | null;\n channel_id?: string | null;\n depth?: number;\n final_status?: string | null;\n started_at: string;\n finished_at?: string | null;\n}\n\n/** Runtime v0.5.0 full worklog detail returned by `GET /worklog/{task_id}`. */\nexport interface WorklogDetail extends WorklogSummary {\n final_result?: string | null;\n error_message?: string | null;\n}\n\n/** Runtime v0.5.0 single worklog event returned by `GET /worklog/{task_id}/events`. */\nexport interface WorklogEventDetail {\n id: number;\n task_id: string;\n previous_hash?: string | null;\n entry_hash?: string | null;\n event_class: string;\n control_id?: string | null;\n status?: string | null;\n data?: unknown;\n submitted_at: string;\n}\n\n/** Runtime v0.5.0 paginated list of worklog summaries. */\nexport interface WorklogPage {\n items: WorklogSummary[];\n total: number;\n limit: number;\n offset: number;\n}\n\n/** Runtime v0.5.0 paginated list of worklog events for a single task. */\nexport interface WorklogEventPage {\n task_id: string;\n items: WorklogEventDetail[];\n total: number;\n}\n\n/** Runtime v0.5.0 hash-chain verification result returned by `GET /worklog/{task_id}/verify`. */\nexport interface WorklogVerificationResult {\n valid: boolean;\n task_id: string;\n event_count: number;\n first_broken_event_id?: number | null;\n first_broken_index?: number | null;\n expected_hash?: string | null;\n actual_hash?: string | null;\n message: string;\n}\n\n/** Semantic bucket a node belongs to. */\nexport type NodeKind =\n | \"safeguard\"\n | \"reasoning\"\n | \"tool\"\n | \"a2a\"\n | \"memory\"\n | \"knowledge\"\n | \"speech\"\n | \"answer\"\n | \"unknown\";\n\n/** Lifecycle state of a single node. */\nexport type NodeStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"skipped\";\n\n/** Overall run status. */\nexport type RunStatus = \"idle\" | \"running\" | \"success\" | \"error\";\n\n/** A single step in the execution chain (command + its response merged by control_id). */\nexport interface WorklogNode {\n id: string;\n kind: NodeKind;\n eventClass: string;\n status: NodeStatus;\n title: string;\n startedAt?: string;\n endedAt?: string;\n depth: number;\n parentId?: string;\n children: WorklogNode[];\n command?: unknown;\n response?: unknown;\n error?: string;\n raw: WorklogRecord[];\n}\n\n/** Normalized execution model produced by the reducer. */\nexport interface WorklogState {\n taskId: string | null;\n status: RunStatus;\n answer: string | null;\n nodes: WorklogNode[];\n index: Record<string, number>;\n raw: WorklogRecord[];\n}\n\n/** How a record acts on the model. */\nexport type EventRole = \"open\" | \"close\" | \"run-open\" | \"run-close\" | \"ignore\";\n\n/** Registry descriptor for one event_class. */\nexport interface EventInterpreter {\n kind: NodeKind;\n role: EventRole;\n title: (_record: WorklogRecord) => string;\n /** If true, an opened node starts in \"pending\" (awaiting external input) rather than \"running\". */\n pending?: boolean;\n}\n\nexport function initialWorklogState(taskId: string | null = null): WorklogState {\n return { taskId, status: \"idle\", answer: null, nodes: [], index: {}, raw: [] };\n}\n","import type { EventInterpreter, WorklogRecord } from \"./types\";\n\nconst asRecord = (data: unknown): Record<string, unknown> =>\n data && typeof data === \"object\" ? (data as Record<string, unknown>) : {};\n\nconst toolTitle = (r: WorklogRecord): string => {\n const name = asRecord(r.data).name;\n return typeof name === \"string\" && name.length > 0 ? `Tool: ${name}` : \"Tool\";\n};\n\nconst agentTitle = (r: WorklogRecord): string => {\n const name = asRecord(r.data).name;\n return typeof name === \"string\" && name.length > 0 ? `Agent: ${name}` : \"Agent-to-agent\";\n};\n\nconst constTitle = (label: string) => () => label;\n\n// The approval gate wraps the parked tool execution in `parameters`.\nconst approvalTitle = (r: WorklogRecord): string => {\n const name = asRecord(asRecord(r.data).parameters).name;\n return typeof name === \"string\" && name.length > 0\n ? `Approval required: ${name}`\n : \"Human approval required\";\n};\n\nconst shieldBlockTitle = (r: WorklogRecord): string => {\n const id = asRecord(r.data).shield_id;\n return typeof id === \"string\" && id.length > 0 ? `Blocked by ${id}` : \"Blocked by safeguard\";\n};\n\nconst knowledgeTitle = (r: WorklogRecord): string => {\n const query = asRecord(r.data).query;\n return typeof query === \"string\" && query.length > 0\n ? `Knowledge: ${query}`\n : \"Knowledge retrieval\";\n};\n\nexport const EVENT_REGISTRY: Record<string, EventInterpreter> = {\n // Run envelope\n AssistantInference: { kind: \"answer\", role: \"run-open\", title: constTitle(\"Inference started\") },\n AssistantInferenceResponse: { kind: \"answer\", role: \"run-close\", title: constTitle(\"Answer\") },\n\n // Safeguard\n ShieldInference: { kind: \"safeguard\", role: \"open\", title: constTitle(\"Safeguard\") },\n ShieldInferenceResponse: { kind: \"safeguard\", role: \"close\", title: constTitle(\"Safeguard\") },\n // Emitted when a shield enforcement decision blocks the request (core 0.5.x).\n // Response-only: the reducer opens it already closed when no command matched.\n ShieldBlockedResponse: { kind: \"safeguard\", role: \"close\", title: shieldBlockTitle },\n\n // Reasoning\n ResponseInference: { kind: \"reasoning\", role: \"open\", title: constTitle(\"Reasoning\") },\n ResponseInferenceResponse: { kind: \"reasoning\", role: \"close\", title: constTitle(\"Reasoning\") },\n\n // Tools (server + subclasses) and their responses\n ServerToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle },\n BuiltinToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle },\n UnknownToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle },\n ClientToolExecution: { kind: \"tool\", role: \"open\", title: toolTitle, pending: true },\n ToolExecutionResponse: { kind: \"tool\", role: \"close\", title: toolTitle },\n BuiltinToolExecutionResponse: { kind: \"tool\", role: \"close\", title: toolTitle },\n\n // Tool schema discovery\n ToolSchema: { kind: \"tool\", role: \"open\", title: constTitle(\"Tool schema\") },\n ToolSchemaResponse: { kind: \"tool\", role: \"close\", title: constTitle(\"Tool schema\") },\n\n // Agent-to-agent\n A2AInference: { kind: \"a2a\", role: \"open\", title: agentTitle },\n AgentDiscovery: { kind: \"a2a\", role: \"open\", title: constTitle(\"Agent discovery\") },\n AgentDiscoveryResponse: { kind: \"a2a\", role: \"close\", title: constTitle(\"Agent discovery\") },\n\n // Knowledge retrieval (RAG) — core 0.5.x\n KnowledgeRetrieval: { kind: \"knowledge\", role: \"open\", title: knowledgeTitle },\n KnowledgeRetrievalResponse: { kind: \"knowledge\", role: \"close\", title: knowledgeTitle },\n\n // Speech pipeline — core 0.5.x\n SpeechTranscription: { kind: \"speech\", role: \"open\", title: constTitle(\"Speech-to-text\") },\n SpeechTranscriptionResponse: { kind: \"speech\", role: \"close\", title: constTitle(\"Speech-to-text\") },\n SpeechSynthesis: { kind: \"speech\", role: \"open\", title: constTitle(\"Text-to-speech\") },\n SpeechSynthesisResponse: { kind: \"speech\", role: \"close\", title: constTitle(\"Text-to-speech\") },\n\n // Memory / persistence\n ContextPersistence: { kind: \"memory\", role: \"open\", title: constTitle(\"Memory persistence\") },\n ContextFlush: { kind: \"memory\", role: \"open\", title: constTitle(\"Memory flush\") },\n ContextFlushResponse: { kind: \"memory\", role: \"close\", title: constTitle(\"Memory flush\") },\n\n // Human approval\n HumanApprovalRequired: {\n kind: \"tool\",\n role: \"open\",\n title: approvalTitle,\n pending: true,\n },\n HumanApprovalRequiredResponse: { kind: \"tool\", role: \"close\", title: constTitle(\"Human approval\") },\n};\n\nexport function resolveInterpreter(eventClass: string): EventInterpreter {\n if (Object.prototype.hasOwnProperty.call(EVENT_REGISTRY, eventClass)) {\n return EVENT_REGISTRY[eventClass];\n }\n return {\n kind: \"unknown\",\n role: \"open\",\n title: (r: WorklogRecord) => r.event_class,\n };\n}\n","import { resolveInterpreter } from \"./registry\";\nimport type { EventInterpreter, WorklogNode, WorklogRecord, WorklogState } from \"./types\";\nimport { initialWorklogState } from \"./types\";\n\nconst asString = (v: unknown): string =>\n typeof v === \"string\" ? v : v == null ? \"\" : JSON.stringify(v);\n\nconst nodeDepth = (record: WorklogRecord): number => {\n const d = record.data && typeof record.data === \"object\"\n ? (record.data as Record<string, unknown>).depth\n : undefined;\n return typeof d === \"number\" ? d : 0;\n};\n\nconst makeOpenNode = (record: WorklogRecord, interp: EventInterpreter, id: string): WorklogNode => ({\n id,\n kind: interp.kind,\n eventClass: record.event_class,\n status: interp.pending ? \"pending\" : \"running\",\n title: interp.title(record),\n startedAt: record.date_submitted,\n depth: nodeDepth(record),\n children: [],\n command: record.data,\n raw: [record],\n});\n\nconst makeClosedNode = (record: WorklogRecord, interp: EventInterpreter, id: string): WorklogNode => ({\n id,\n kind: interp.kind,\n eventClass: record.event_class,\n status: record.status === \"error\" ? \"failed\" : \"completed\",\n title: interp.title(record),\n startedAt: record.date_submitted,\n endedAt: record.date_submitted,\n depth: nodeDepth(record),\n children: [],\n response: record.data,\n error: record.status === \"error\" ? asString(record.data) : undefined,\n raw: [record],\n});\n\nexport function reduceWorklog(state: WorklogState, record: WorklogRecord): WorklogState {\n const interp = resolveInterpreter(record.event_class);\n const next: WorklogState = {\n ...state,\n nodes: state.nodes.slice(),\n index: { ...state.index },\n raw: [...state.raw, record],\n };\n\n if (interp.role === \"ignore\") return next;\n\n if (interp.role === \"run-open\") {\n next.status = \"running\";\n return next;\n }\n\n if (interp.role === \"run-close\") {\n next.answer = asString(record.data) || null;\n next.status = record.status === \"error\" ? \"error\" : \"success\";\n return next;\n }\n\n const key = record.control_id ?? `${record.event_class}-${next.raw.length}`;\n\n if (interp.role === \"close\") {\n const pos = Object.prototype.hasOwnProperty.call(next.index, key) ? next.index[key] : undefined;\n if (pos != null) {\n const existing = next.nodes[pos];\n next.nodes[pos] = {\n ...existing,\n status: record.status === \"error\" ? \"failed\" : \"completed\",\n endedAt: record.date_submitted,\n response: record.data,\n error: record.status === \"error\" ? asString(record.data) : existing.error,\n raw: [...existing.raw, record],\n };\n } else {\n // response arrived without a seen command — create it already closed\n next.index[key] = next.nodes.length;\n next.nodes.push(makeClosedNode(record, interp, key));\n }\n if (record.status === \"error\") next.status = \"error\";\n return next;\n }\n\n // role === \"open\"\n const pos = Object.prototype.hasOwnProperty.call(next.index, key) ? next.index[key] : undefined;\n if (pos != null) {\n const existing = next.nodes[pos];\n // The command can arrive after its response (the node was opened closed);\n // keep the status, but fill in what the command says it was.\n next.nodes[pos] = {\n ...existing,\n command: existing.command ?? record.data,\n title: existing.command === undefined ? interp.title(record) : existing.title,\n raw: [...existing.raw, record],\n };\n } else {\n next.index[key] = next.nodes.length;\n next.nodes.push(makeOpenNode(record, interp, key));\n }\n return next;\n}\n\nexport function foldWorklog(records: WorklogRecord[], taskId: string | null = null): WorklogState {\n return records.reduce(reduceWorklog, initialWorklogState(taskId));\n}\n","import { useCallback, useReducer } from \"react\";\nimport { reduceWorklog } from \"./reducer\";\nimport { initialWorklogState, type WorklogRecord, type WorklogState } from \"./types\";\n\ntype Action =\n | { type: \"ingest\"; record: WorklogRecord }\n | { type: \"ingestMany\"; records: WorklogRecord[] }\n | { type: \"reset\"; taskId: string | null };\n\nfunction hookReducer(state: WorklogState, action: Action): WorklogState {\n switch (action.type) {\n case \"ingest\":\n return reduceWorklog(state, action.record);\n case \"ingestMany\":\n return action.records.reduce(reduceWorklog, state);\n case \"reset\":\n return initialWorklogState(action.taskId);\n }\n}\n\n/** Live worklog accumulator. Feed it `bus_mode` records via `ingest`; use `foldWorklog` for history. */\nexport function useWorklog(taskId: string | null = null) {\n const [worklog, dispatch] = useReducer(hookReducer, taskId, initialWorklogState);\n\n const ingest = useCallback((record: WorklogRecord) => dispatch({ type: \"ingest\", record }), []);\n const ingestMany = useCallback(\n (records: WorklogRecord[]) => dispatch({ type: \"ingestMany\", records }),\n [],\n );\n const reset = useCallback(\n (id: string | null = null) => dispatch({ type: \"reset\", taskId: id }),\n [],\n );\n\n return { worklog, ingest, ingestMany, reset };\n}\n","import type { WorklogRecord } from \"./types\";\n\n/** Loosely-typed shape of a parsed SSE `data:` frame from the granular Runtime stream. */\nexport interface RawFrame {\n event_class?: string;\n control_id?: string | null;\n data?: unknown;\n status?: string | null;\n date_submitted?: string;\n /** Runtime v0.5.0+ tamper-evident hash chain fields. */\n entry_hash?: string | null;\n previous_hash?: string | null;\n}\n\n/** Normalize a parsed SSE frame into a WorklogRecord (defaults missing fields; never throws). */\nexport function frameToRecord(frame: RawFrame): WorklogRecord {\n const status = frame.status === \"success\" || frame.status === \"error\" ? frame.status : null;\n return {\n event_class: typeof frame.event_class === \"string\" && frame.event_class.length > 0\n ? frame.event_class\n : \"Unknown\",\n control_id: frame.control_id ?? null,\n data: frame.data,\n status,\n date_submitted: typeof frame.date_submitted === \"string\" ? frame.date_submitted : \"\",\n entry_hash: frame.entry_hash ?? null,\n previous_hash: frame.previous_hash ?? null,\n };\n}\n","import type { WorklogRecord } from \"./types\";\n\n/**\n * Human-approval gates, derived from the worklog.\n *\n * When the runtime's authz policy resolves a tool call to `REQUIRE_APPROVAL`,\n * core parks the call and records a `HumanApprovalRequired` whose `data` is the\n * command minus its conversation: `{ parameters: <the tool execution> }`. The\n * gate closes with a `HumanApprovalRequiredResponse` under the same\n * `control_id`, whichever channel the decision came through — so the stream,\n * not the local submit, is the source of truth for \"settled\".\n */\n\n/** A decision as the worklog records it. */\nexport interface ApprovalDecision {\n approved: boolean;\n /**\n * Rejection reason. Core records `result or message` as the response data,\n * so an approval never carries one and a rejection carries the reason when\n * the approver gave it.\n */\n reason: string | null;\n decidedAt: string;\n}\n\n/** One approval gate, pending or settled. */\nexport interface ApprovalRequest {\n /** The `HumanApprovalRequired` control id — the one `/event/tool-approval` expects. */\n controlId: string;\n /** Name of the parked tool call; `null` until the request record is seen. */\n toolName: string | null;\n /** Control id of the parked tool execution itself (distinct from `controlId`). */\n toolCallId: string | null;\n /** Arguments the tool would be called with. What is actually being approved. */\n arguments: unknown;\n /**\n * The gate belongs to an MCP server that runs its own approval over the\n * task's originating channel (the `mcp_approval` runtime extension). The\n * runtime refuses an HTTP decision for it with a 409, so offering buttons\n * would be a lie.\n */\n channelOwned: boolean;\n requestedAt: string | null;\n /** `null` while pending. */\n decision: ApprovalDecision | null;\n}\n\nexport interface ApprovalsState {\n /** Gates in the order they were first seen. */\n order: string[];\n byId: Record<string, ApprovalRequest>;\n}\n\nexport function initialApprovalsState(): ApprovalsState {\n return { order: [], byId: {} };\n}\n\nconst asObject = (v: unknown): Record<string, unknown> | null =>\n v && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;\n\nconst MCP_APPROVAL_EXTENSION = \"mcp_approval\";\n\nfunction describeRequest(record: WorklogRecord) {\n const execution = asObject(asObject(record.data)?.parameters) ?? {};\n const name = execution.name;\n const callId = execution.control_id;\n // Server tools keep their config in `parameters` and the LLM's arguments in\n // `tool_call_parameters`; client and builtin tools put the arguments in\n // `parameters` directly.\n const args =\n execution.tool_call_parameters !== undefined && execution.tool_call_parameters !== null\n ? execution.tool_call_parameters\n : execution.parameters;\n const extensions = asObject(execution.parameters)?.runtime_extensions;\n return {\n toolName: typeof name === \"string\" && name.length > 0 ? name : null,\n toolCallId: typeof callId === \"string\" ? callId : null,\n arguments: args ?? null,\n channelOwned: Array.isArray(extensions) && extensions.includes(MCP_APPROVAL_EXTENSION),\n };\n}\n\nfunction describeDecision(record: WorklogRecord): ApprovalDecision {\n const approved = record.data === true;\n return {\n approved,\n reason: !approved && typeof record.data === \"string\" && record.data.length > 0 ? record.data : null,\n decidedAt: record.date_submitted,\n };\n}\n\nconst blank = (controlId: string): ApprovalRequest => ({\n controlId,\n toolName: null,\n toolCallId: null,\n arguments: null,\n channelOwned: false,\n requestedAt: null,\n decision: null,\n});\n\n/** Fold one worklog record into the approvals state. Records of other classes are a no-op. */\nexport function reduceApprovals(state: ApprovalsState, record: WorklogRecord): ApprovalsState {\n const isRequest = record.event_class === \"HumanApprovalRequired\";\n const isResponse = record.event_class === \"HumanApprovalRequiredResponse\";\n if ((!isRequest && !isResponse) || !record.control_id) return state;\n\n const id = record.control_id;\n const known = state.byId[id];\n const current = known ?? blank(id);\n\n // A response can overtake its request (bus redelivery, a replayed history).\n // Either order lands on the same settled entry: the request only fills in\n // what is being approved and never reopens a decision.\n const next: ApprovalRequest = isRequest\n ? { ...current, ...describeRequest(record), requestedAt: record.date_submitted }\n : { ...current, decision: current.decision ?? describeDecision(record) };\n\n return {\n order: known ? state.order : [...state.order, id],\n byId: { ...state.byId, [id]: next },\n };\n}\n\nexport function foldApprovals(records: WorklogRecord[]): ApprovalsState {\n return records.reduce(reduceApprovals, initialApprovalsState());\n}\n\n/** All gates, in first-seen order. */\nexport function listApprovals(state: ApprovalsState): ApprovalRequest[] {\n return state.order.map((id) => state.byId[id]);\n}\n\n/** Gates with no recorded decision yet. */\nexport function pendingApprovals(state: ApprovalsState): ApprovalRequest[] {\n return listApprovals(state).filter((a) => a.decision === null);\n}\n","export interface PendingClientTool {\n controlId: string;\n toolName: string;\n parameters: unknown;\n}\n\n/** Extract a pending client-tool execution from a raw SSE frame. Returns null if not one. */\nexport function extractPendingClientTool(frame: unknown): PendingClientTool | null {\n if (!frame || typeof frame !== \"object\") return null;\n const f = frame as Record<string, any>;\n if (f.event_class !== \"ClientToolExecution\") return null;\n const name = f.data?.name;\n const parameters = f.data?.parameters;\n const controlId = f.control_id;\n if (typeof name !== \"string\" || parameters === undefined || typeof controlId !== \"string\") return null;\n return { controlId, toolName: name, parameters };\n}\n","import { z } from \"zod\";\n\n/**\n * The agent-facing \"style vocabulary\" — enum-constrained semantic props that let\n * the model style a surface via INTENT, never CSS. Shared across every catalog\n * component; the UI renderer maps these to the consumer's design tokens.\n * See docs/a2ui-approach.md §11.\n */\nexport const TONES = [\"default\", \"muted\", \"primary\", \"success\", \"warning\", \"danger\"] as const;\nexport const SIZES = [\"sm\", \"md\", \"lg\"] as const;\nexport const EMPHASES = [\"low\", \"medium\", \"high\"] as const;\nexport const ALIGNS = [\"start\", \"center\", \"end\"] as const;\nexport const DENSITIES = [\"compact\", \"comfortable\"] as const;\n\nexport type Tone = (typeof TONES)[number];\nexport type Size = (typeof SIZES)[number];\nexport type Emphasis = (typeof EMPHASES)[number];\nexport type Align = (typeof ALIGNS)[number];\nexport type Density = (typeof DENSITIES)[number];\n\nexport interface StyleProps {\n tone?: Tone;\n size?: Size;\n emphasis?: Emphasis;\n align?: Align;\n density?: Density;\n}\n\n/**\n * Raw zod shape merged into every component schema in the catalog.\n * `variant` is component-specific and added per component, not here.\n */\nexport const styleSchemaShape = {\n tone: z.enum(TONES).optional(),\n size: z.enum(SIZES).optional(),\n emphasis: z.enum(EMPHASES).optional(),\n align: z.enum(ALIGNS).optional(),\n density: z.enum(DENSITIES).optional(),\n};\n","import type { ZodType } from \"zod\";\n\nexport interface UIComponentDefinition {\n name: string;\n /** zod schema for the component's presentational props. */\n schema: ZodType;\n /** semantic action names this component may emit. */\n allowedActions?: string[];\n}\n\nexport interface CatalogManifest {\n id: string;\n components: Record<string, UIComponentDefinition>;\n}\n\n/** Marker used by the renderer when a component name is not in the catalog. */\nexport const UNKNOWN_COMPONENT = \"__unknown__\";\n\n/** Resolve a component name against the active catalog. Returns null on miss — never throws. */\nexport function resolveComponent(\n manifest: CatalogManifest,\n name: string,\n): UIComponentDefinition | null {\n if (!name || typeof name !== \"string\") return null;\n return manifest.components[name] ?? null;\n}\n","import { z } from \"zod\";\nimport type { CatalogManifest } from \"./registry\";\nimport { styleSchemaShape } from \"./style\";\n\n/** Versioned catalog id — a URI (A2UI convention). The version lives in the path. */\nexport const CORE_CATALOG_ID = \"https://alquimia.ai/catalogs/core/v1/catalog.json\";\n\n/** Merge shared style vocabulary + an optional component-specific variant enum + own props. */\nconst def = (\n name: string,\n own: z.ZodRawShape,\n opts?: { variant?: readonly [string, ...string[]]; allowedActions?: string[] },\n) => ({\n name,\n schema: z\n .object({\n ...styleSchemaShape,\n ...(opts?.variant ? { variant: z.enum(opts.variant).optional() } : {}),\n ...own,\n })\n .passthrough(),\n allowedActions: opts?.allowedActions,\n});\n\nconst option = z.object({ label: z.string(), value: z.union([z.string(), z.number()]) });\n\n/**\n * The default catalog: ~40 components across layout / content / inputs / data / actions.\n * Prop schemas describe ONLY presentational props; id/component/children/binding/action\n * are structural. Every component also accepts the shared style vocabulary.\n */\nexport const coreCatalog: CatalogManifest = {\n id: CORE_CATALOG_ID,\n components: {\n // ---- layout ----\n Stack: def(\"Stack\", {\n direction: z.enum([\"vertical\", \"horizontal\"]).optional(),\n gap: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n }),\n Grid: def(\"Grid\", {\n columns: z.number().int().min(1).max(6).optional(),\n gap: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n }),\n Row: def(\"Row\", { gap: z.enum([\"sm\", \"md\", \"lg\"]).optional(), wrap: z.boolean().optional() }),\n Column: def(\"Column\", { gap: z.enum([\"sm\", \"md\", \"lg\"]).optional() }),\n Divider: def(\"Divider\", { label: z.string().optional() }),\n Spacer: def(\"Spacer\", { size: z.enum([\"sm\", \"md\", \"lg\"]).optional() }),\n Card: def(\"Card\", { title: z.string().optional(), description: z.string().optional() }, {\n variant: [\"elevated\", \"outline\", \"ghost\"],\n }),\n Accordion: def(\"Accordion\", {\n items: z.array(z.object({ title: z.string(), value: z.string() })).optional(),\n }),\n Tabs: def(\"Tabs\", { tabs: z.array(z.object({ label: z.string(), value: z.string() })).min(1) }),\n // ---- content ----\n Text: def(\"Text\", { text: z.string() }, { variant: [\"body\", \"muted\", \"caption\", \"lead\"] }),\n Heading: def(\"Heading\", { text: z.string(), level: z.number().int().min(1).max(4).optional() }),\n Markdown: def(\"Markdown\", { text: z.string() }),\n Image: def(\"Image\", { src: z.string(), alt: z.string().optional() }),\n Icon: def(\"Icon\", { name: z.string() }),\n Badge: def(\"Badge\", { text: z.string() }, { variant: [\"solid\", \"outline\", \"subtle\"] }),\n Avatar: def(\"Avatar\", { src: z.string().optional(), fallback: z.string().optional() }),\n Alert: def(\"Alert\", { text: z.string(), title: z.string().optional() }, {\n variant: [\"info\", \"success\", \"warning\", \"danger\"],\n }),\n Stat: def(\"Stat\", { label: z.string(), value: z.union([z.string(), z.number()]), delta: z.string().optional() }),\n KeyValue: def(\"KeyValue\", {}),\n List: def(\"List\", { ordered: z.boolean().optional() }),\n Quote: def(\"Quote\", { text: z.string(), cite: z.string().optional() }),\n // ---- inputs ----\n TextField: def(\"TextField\", { label: z.string().optional(), placeholder: z.string().optional() }),\n TextArea: def(\"TextArea\", {\n label: z.string().optional(),\n placeholder: z.string().optional(),\n rows: z.number().int().optional(),\n }),\n NumberField: def(\"NumberField\", {\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n step: z.number().optional(),\n }),\n Select: def(\"Select\", {\n label: z.string().optional(),\n placeholder: z.string().optional(),\n options: z.array(option).min(1),\n }),\n MultiSelect: def(\"MultiSelect\", { label: z.string().optional(), options: z.array(option).min(1) }),\n Combobox: def(\"Combobox\", {\n label: z.string().optional(),\n placeholder: z.string().optional(),\n options: z.array(option).min(1),\n }),\n Checkbox: def(\"Checkbox\", { label: z.string().optional() }),\n CheckboxGroup: def(\"CheckboxGroup\", { label: z.string().optional(), options: z.array(option).min(1) }),\n Radio: def(\"Radio\", { label: z.string().optional(), options: z.array(option).min(1) }),\n Switch: def(\"Switch\", { label: z.string().optional() }),\n Slider: def(\"Slider\", {\n label: z.string().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n step: z.number().optional(),\n }),\n DatePicker: def(\"DatePicker\", { label: z.string().optional() }),\n DateRange: def(\"DateRange\", { label: z.string().optional() }),\n FileUpload: def(\"FileUpload\", {\n label: z.string().optional(),\n accept: z.string().optional(),\n multiple: z.boolean().optional(),\n }),\n Rating: def(\"Rating\", { label: z.string().optional(), max: z.number().int().optional() }),\n // ---- data ----\n Table: def(\"Table\", {\n columns: z.array(z.object({ key: z.string(), header: z.string().optional() })).min(1),\n sortable: z.boolean().optional(),\n }, { allowedActions: [\"sort\", \"filter\"] }),\n Chart: def(\"Chart\", {\n kind: z.enum([\"bar\", \"line\", \"area\", \"pie\"]),\n x: z.string().optional(),\n series: z.array(z.object({ key: z.string(), label: z.string().optional() })).min(1),\n title: z.string().optional(),\n }),\n Progress: def(\"Progress\", { value: z.number(), max: z.number().optional(), label: z.string().optional() }),\n Timeline: def(\"Timeline\", {\n items: z\n .array(z.object({ title: z.string(), description: z.string().optional(), timestamp: z.string().optional() }))\n .min(1),\n }),\n // ---- actions ----\n Button: def(\"Button\", { text: z.string() }, {\n variant: [\"solid\", \"outline\", \"ghost\", \"link\"],\n allowedActions: [\"submit\", \"cancel\", \"reset\", \"select\", \"confirm\"],\n }),\n ButtonGroup: def(\"ButtonGroup\", {}),\n Link: def(\"Link\", { text: z.string(), href: z.string().optional() }),\n },\n};\n","import type { SurfaceAction } from \"./types\";\n\nexport type UIActionKind = \"agent-bound\" | \"local\";\n\nexport interface UIAction {\n surfaceId: string;\n componentId: string;\n action: string;\n kind: UIActionKind;\n payload?: Record<string, unknown>;\n}\n\n/**\n * The `result` body posted to /event/tool-completion for an agent-bound action.\n * Shape is part of the agent-facing contract — the prompt clause describes it.\n */\nexport interface SurfaceResult {\n /** The action's semantic name. */\n action: string;\n /** Which surface it came from. */\n surfaceId: string;\n /**\n * The id of the component that was acted on. This is what lets the agent tell WHICH\n * element fired when several share one action name — e.g. a grid of option cards that\n * all use `selectFlight`. Without it the agent has to ask the user what they just\n * clicked, which reads as a broken assistant.\n */\n componentId: string;\n /** The surface's collected data model (empty object when the surface binds no fields). */\n data: Record<string, unknown>;\n /**\n * Present only when the user declined the surface and answered in words instead\n * (see `buildDismissResult`). Absent on a normal submit or selection.\n */\n userMessage?: string;\n}\n\n/**\n * Action name reported when the user dismisses an interactive surface rather than using it.\n * Kept distinct from any model-authored action so the agent can tell the two apart.\n */\nexport const DISMISS_ACTION = \"userDismissedSurface\";\n\n/**\n * Complete a pending interactive surface *negatively*, optionally carrying the natural-language\n * reply the user typed instead of interacting.\n *\n * Why this exists: an interactive surface parks the inference until a tool result arrives. If\n * the UI is the only way to answer, a user who doesn't want any of the offered options is stuck\n * — they cannot type, and the task never resumes. Completing with this result unparks the\n * conversation and hands the agent the user's actual words, so it can respond to them.\n */\nexport function buildDismissResult(surfaceId: string, userMessage?: string): SurfaceResult {\n const said = typeof userMessage === \"string\" ? userMessage.trim() : \"\";\n return {\n action: DISMISS_ACTION,\n surfaceId,\n componentId: \"\",\n data: {},\n ...(said ? { userMessage: said } : {}),\n };\n}\n\n/** Build the tool-completion `result` for an agent-bound action. */\nexport function buildSurfaceResult(action: UIAction): SurfaceResult {\n return {\n action: action.action,\n surfaceId: action.surfaceId,\n componentId: action.componentId,\n data: action.payload ?? {},\n };\n}\n\n/** Agent-bound actions (wantResponse) return their payload to the agent; others stay local. */\nexport function classifyAction(action: SurfaceAction): UIActionKind {\n return action.wantResponse === true ? \"agent-bound\" : \"local\";\n}\n\nconst URL_LIKE = /^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\n/** Actions are semantic names, never URLs. Reject anything scheme- or protocol-relative. */\nexport function assertSafeActionName(name: string): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(\"action.name must be a non-empty string\");\n }\n if (URL_LIKE.test(name)) {\n throw new Error(`action.name must be a semantic name, not a URL: ${name}`);\n }\n}\n","import { z } from \"zod\";\nimport type { A2uiComponent, A2uiSurface } from \"./types\";\nimport type { CatalogManifest, UIComponentDefinition } from \"./registry\";\nimport { resolveComponent } from \"./registry\";\nimport { assertSafeActionName } from \"./actions\";\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\nexport interface ValidationResult<T = unknown> {\n ok: boolean;\n value?: T;\n /** Fatal problems — the surface cannot be rendered. */\n errors: ValidationError[];\n /** Non-fatal problems — the surface still renders; these degrade gracefully. */\n warnings?: ValidationError[];\n}\n\nconst surfaceShape = z.object({\n surfaceId: z.string().min(1),\n // Tier 2 canonical id (versioned URI); `catalog` is the legacy alias. Both optional on the\n // wire — the SDK stamps `catalogId` if the agent omits it.\n catalogId: z.string().min(1).optional(),\n catalog: z.string().min(1).optional(),\n // Legacy explicit root. A2UI uses the component with id \"root\"; kept optional for back-compat.\n root: z.string().min(1).optional(),\n components: z.array(\n z\n .object({\n id: z.string().min(1),\n component: z.string().min(1),\n children: z.array(z.string()).optional(),\n child: z.string().optional(),\n binding: z.string().optional(),\n action: z.object({ name: z.string(), wantResponse: z.boolean().optional() }).optional(),\n })\n .passthrough(),\n ),\n dataModel: z.record(z.unknown()).optional(),\n});\n\n/** UAX#31 identifier rule (A2UI): XID_Start/underscore then XID_Continue. */\nconst UAX31_ID = /^[\\p{XID_Start}_][\\p{XID_Continue}]*$/u;\n\n/** Validate one node's presentational props against its catalog definition. */\nexport function validateProps(node: A2uiComponent, def: UIComponentDefinition): ValidationResult {\n const {\n id,\n component: _component,\n children: _children,\n child: _child,\n binding: _binding,\n action: _action,\n ...props\n } = node;\n const parsed = def.schema.safeParse(props);\n if (parsed.success) return { ok: true, value: parsed.data, errors: [] };\n return {\n ok: false,\n errors: parsed.error.issues.map((i) => ({ path: `${id}.${i.path.join(\".\")}`, message: i.message })),\n };\n}\n\n/** Full structural + catalog + prop + action validation of an incoming surface. */\nexport function validateSurface(input: unknown, manifest: CatalogManifest): ValidationResult<A2uiSurface> {\n const shape = surfaceShape.safeParse(input);\n if (!shape.success) {\n return { ok: false, errors: shape.error.issues.map((i) => ({ path: i.path.join(\".\"), message: i.message })) };\n }\n const surface = shape.data as A2uiSurface;\n const errors: ValidationError[] = []; // fatal — cannot render\n const warnings: ValidationError[] = []; // non-fatal — render anyway, degrade gracefully\n const ids = new Set(surface.components.map((c) => c.id));\n\n // Root = the component with id \"root\" (A2UI convention), falling back to the legacy `root` field.\n const rootId = ids.has(\"root\") ? \"root\" : surface.root;\n // Fatal: without a resolvable root node there is nothing to render.\n if (!rootId || !ids.has(rootId)) {\n errors.push({ path: \"root\", message: `no root component (expected a component with id \"root\")` });\n }\n\n // Non-fatal: catalogId should be present (the SDK stamps it if the agent omits it).\n if (!surface.catalogId && !surface.catalog) {\n warnings.push({ path: \"catalogId\", message: \"surface has no catalogId (SDK will stamp the active catalog)\" });\n }\n\n for (const node of surface.components) {\n // Non-fatal: A2UI mandates UAX#31 identifiers; a bad id still renders but is flagged.\n if (!UAX31_ID.test(node.id)) {\n warnings.push({ path: node.id, message: `id \"${node.id}\" is not a valid UAX#31 identifier` });\n }\n\n const def = resolveComponent(manifest, node.component);\n if (!def) {\n // Non-fatal: the renderer falls back to a text placeholder for unknown components.\n warnings.push({ path: node.id, message: `unknown component \"${node.component}\" (renders as text)` });\n continue;\n }\n\n // Non-fatal: invalid presentational props degrade to component defaults.\n warnings.push(...validateProps(node, def).errors);\n\n for (const childId of node.children ?? []) {\n if (!ids.has(childId)) {\n warnings.push({ path: node.id, message: `child \"${childId}\" does not exist (skipped)` });\n }\n }\n if (node.child && !ids.has(node.child)) {\n warnings.push({ path: node.id, message: `child \"${node.child}\" does not exist (skipped)` });\n }\n\n // Fatal (security invariant): an action name must be a semantic string, never a URL.\n if (node.action) {\n try {\n assertSafeActionName(node.action.name);\n } catch (e) {\n errors.push({ path: `${node.id}.action`, message: (e as Error).message });\n }\n }\n }\n\n return errors.length === 0\n ? { ok: true, value: surface, errors: [], warnings }\n : { ok: false, errors, warnings };\n}\n","import type { CatalogManifest } from \"./registry\";\nimport { TONES, SIZES, EMPHASES, ALIGNS, DENSITIES } from \"./style\";\n\n/**\n * The runtime expects each `tool_schemas` entry to be a flat JSON Schema of the\n * tool arguments: `title` is the tool name, `properties` are the arguments.\n * (Not the OpenAI `{ type:\"function\", function:{...} }` wrapper, and not a\n * `{ name, description, parameters }` envelope — both leave the runtime with an\n * empty argument schema.)\n */\nexport interface RenderUiToolSchema {\n title: \"render_ui\";\n name: \"render_ui\";\n description: string;\n type: \"object\";\n properties: Record<string, unknown>;\n required: string[];\n additionalProperties: boolean;\n}\n\nconst DESCRIPTION =\n \"Render a UI using A2UI. The arguments are a UI surface, NOT free-form. Shape: \" +\n \"{ surfaceId, root, components, dataModel? }. `components` is a FLAT array; every item is \" +\n \"{ id, component, children?, ...props } where `component` is one of the allowed names (use \" +\n \"`component`, never `type`) and `children` is an array of string ids referencing other items \" +\n \"(never nested objects). Inputs bind to the data model via `binding` (a JSON Pointer like \" +\n '\"/name\"). To collect input, include a Button with action { name, wantResponse: true } — its ' +\n \"result (the data model) is returned to you; a surface with no such button is display-only. \" +\n 'Example: { \"surfaceId\": \"signup\", \"root\": \"root\", \"components\": [ ' +\n '{ \"id\": \"root\", \"component\": \"Stack\", \"children\": [\"name\", \"desc\", \"submit\"] }, ' +\n '{ \"id\": \"name\", \"component\": \"TextField\", \"label\": \"Username\", \"binding\": \"/name\" }, ' +\n '{ \"id\": \"desc\", \"component\": \"TextField\", \"label\": \"Description\", \"binding\": \"/description\" }, ' +\n '{ \"id\": \"submit\", \"component\": \"Button\", \"text\": \"Save\", \"action\": { \"name\": \"save\", \"wantResponse\": true } } ' +\n '], \"dataModel\": { \"name\": \"\", \"description\": \"\" } }. ' +\n \"IMPORTANT: when you call render_ui, the rendered surface IS your reply — do NOT also \" +\n \"reproduce its content as text, markdown, or ASCII. Any accompanying message must be a brief \" +\n \"one-line intro at most, never a duplicate of the UI.\";\n\n/** Build the render_ui tool schema from a catalog, filtered to an allowlist of component names. */\nexport function buildRenderUiSchema(manifest: CatalogManifest, allowlist: string[]): RenderUiToolSchema {\n const allowed = allowlist.filter((name) => name in manifest.components);\n return {\n title: \"render_ui\",\n name: \"render_ui\",\n description: DESCRIPTION,\n type: \"object\",\n properties: {\n surfaceId: { type: \"string\" },\n // A2UI catalog id — a versioned URI. `const` nudges the model to echo it; the SDK\n // also stamps it if omitted, so the client always knows which catalog version to render.\n catalogId: { type: \"string\", const: manifest.id },\n catalog: { type: \"string\" }, // legacy alias (accepted, ignored)\n root: { type: \"string\" }, // legacy explicit root (accepted; A2UI uses the id:\"root\" component)\n components: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n component: { type: \"string\", enum: allowed },\n children: { type: \"array\", items: { type: \"string\" } },\n child: { type: \"string\" },\n binding: { type: \"string\" },\n action: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n wantResponse: { type: \"boolean\" },\n },\n required: [\"name\"],\n },\n tone: { type: \"string\", enum: [...TONES] },\n size: { type: \"string\", enum: [...SIZES] },\n emphasis: { type: \"string\", enum: [...EMPHASES] },\n align: { type: \"string\", enum: [...ALIGNS] },\n density: { type: \"string\", enum: [...DENSITIES] },\n variant: { type: \"string\" },\n text: { type: \"string\" },\n label: { type: \"string\" },\n placeholder: { type: \"string\" },\n title: { type: \"string\" },\n direction: { type: \"string\" },\n gap: { type: \"string\" },\n // Data props for data components. Several are legitimately polymorphic across\n // components — type them as their real unions so the runtime doesn't reject\n // valid output (adapters normalize each shape):\n // data: array (Chart/Table rows) | object (KeyValue)\n // rows: array (Table) | number (TextArea row count)\n // columns: array (Table col defs) | number (Grid column count)\n data: { type: [\"array\", \"object\"] },\n rows: { type: [\"array\", \"number\"] },\n items: { type: \"array\" },\n // Accept string OR object items — models routinely emit the terse string\n // form (e.g. series:[\"revenue\"], options:[\"A\",\"B\"]); adapters normalize.\n columns: { type: [\"array\", \"number\"], items: { type: [\"object\", \"string\"] } },\n series: { type: \"array\", items: { type: [\"object\", \"string\"] } },\n options: { type: \"array\", items: { type: [\"object\", \"string\"] } },\n kind: { type: \"string\" },\n x: { type: \"string\" },\n value: {},\n },\n required: [\"id\", \"component\"],\n },\n },\n dataModel: { type: \"object\" },\n },\n required: [\"surfaceId\", \"root\", \"components\"],\n additionalProperties: false,\n };\n}\n","import type { CatalogManifest } from \"./registry\";\nimport { TONES, SIZES } from \"./style\";\n\n/**\n * Build the compact GenUI prompt clause from the catalog, filtered to an allowlist.\n * Teaches the allowed components, the style vocabulary, the wantResponse round-trip\n * rule, and the \"don't reproduce the UI as text\" rule.\n */\nexport function buildGenuiClause(manifest: CatalogManifest, allowlist: string[]): string {\n const names = allowlist.filter((n) => n in manifest.components);\n return [\n \"You can render UI by calling render_ui with an A2UI surface (a flat components array; each item is { id, component, children?, ...props }; component is one of the allowed names; children are string ids referencing other items).\",\n `Components: ${names.join(\", \")}.`,\n `Style each component via the semantic vocabulary (never CSS, colors, or HTML): tone (${TONES.join(\"/\")}), size (${SIZES.join(\"/\")}), emphasis (low/medium/high), align (start/center/end), density (compact/comfortable), plus a component-specific variant where offered.`,\n \"Data components MUST carry their data: Chart takes `data` (an array of row objects) + `series` (keys to plot) + `x` (the category key); Table takes `rows` (array of row objects) + `columns` ([{ key, header }] matching the row keys); List takes `items` (array); Stat takes `label`+`value`; KeyValue takes `data` (an object). Put the data inline on the component (or in dataModel referenced via `binding`).\",\n \"To collect input, add a Button with an action { name, wantResponse: true }. You get back { action, surfaceId, componentId, data } — `data` is the collected data model and `componentId` is the id of the component that was acted on. A surface with no such button is display-only.\",\n \"When you render several options to choose from (a grid of cards, each with its own button), give every option component a MEANINGFUL id (e.g. flight-NH107, hotel-memmo-alfama): `componentId` tells you which one the user picked, so never ask them to repeat a choice they already made.\",\n 'The user may ignore an interactive surface and just type instead. You then receive action \"userDismissedSurface\" with their words in `userMessage` — treat it as their reply, answer it directly, and do not re-render the same surface or scold them for not using it.',\n \"IMPORTANT: the rendered surface IS your reply — do NOT reproduce its content as text, markdown, or ASCII; a one-line intro at most.\",\n \"Prefer plain text for simple replies.\",\n ].join(\" \");\n}\n","import { zodToJsonSchema } from \"zod-to-json-schema\";\nimport type { CatalogManifest } from \"./registry\";\n\n/**\n * `zodToJsonSchema`'s generic return type triggers TS2589 (excessively deep) during .d.ts\n * generation. Call it through a plain, non-generic signature — we only read properties/required.\n */\nconst toJsonSchema = zodToJsonSchema as unknown as (\n _schema: unknown,\n _opts?: unknown,\n) => { properties?: Record<string, unknown>; required?: string[] };\n\n/**\n * The A2UI-format catalog JSON — the published, versioned contract. Emitted from the\n * authoring catalog (the zod `CatalogManifest`) so the shipped artifact can never drift\n * from what the SDK validates against (guarded by emit.test.ts).\n */\nexport interface A2uiCatalogJson {\n $schema: string;\n catalogId: string;\n title: string;\n description: string;\n components: Record<string, unknown>;\n $defs: Record<string, unknown>;\n}\n\n/** Shared A2UI type defs referenced by (future, DynamicString-bound) components. */\nconst SHARED_DEFS: Record<string, unknown> = {\n DynamicString: {\n description: \"A literal string OR a data-model path reference { path }.\",\n oneOf: [\n { type: \"string\" },\n { type: \"object\", properties: { path: { type: \"string\" } }, required: [\"path\"], additionalProperties: false },\n ],\n },\n Action: {\n description: \"A semantic action (never a URL). wantResponse:true returns the data model to the agent.\",\n type: \"object\",\n properties: { name: { type: \"string\" }, wantResponse: { type: \"boolean\" } },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\n/**\n * Compile the authoring catalog to the A2UI v1.0 catalog format:\n * `{ catalogId, components: { Name: {type:object, properties:{ component:{const}, …}, required, unevaluatedProperties:false } }, $defs }`.\n */\nexport function emitA2uiCatalog(manifest: CatalogManifest, opts: { catalogId: string }): A2uiCatalogJson {\n const components: Record<string, unknown> = {};\n\n for (const [name, def] of Object.entries(manifest.components)) {\n const propsSchema = toJsonSchema(def.schema, { $refStrategy: \"none\", target: \"jsonSchema2020\" });\n const properties: Record<string, unknown> = {\n component: { const: name },\n ...(propsSchema.properties ?? {}),\n };\n const required = Array.from(new Set([\"component\", ...(propsSchema.required ?? [])]));\n components[name] = {\n type: \"object\",\n properties,\n required,\n // Presentational props are open at authoring time (zod .passthrough()); the tool\n // schema is where the model-facing prop set is fixed. Keep the catalog permissive.\n unevaluatedProperties: false,\n };\n }\n\n return {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n catalogId: opts.catalogId,\n title: \"Alquimia Core Catalog\",\n description:\n \"Alquimia's default A2UI catalog. Abstract, framework-agnostic component contract; \" +\n \"consumers map each component to their own (shadcn) renderer. Generated from the SDK authoring catalog.\",\n components,\n $defs: SHARED_DEFS,\n };\n}\n","\nimport { useState, useReducer } from \"react\";\nimport { RatingData } from \"../types/type\";\nimport { getTopicSessionId } from \"../utils/utils\";\n\ninterface RatingState {\n ratingStars: number;\n ratingThumbs: \"thumbsUp\" | \"thumbsDown\" | \"\";\n ratingComment: string;\n}\n\ntype RatingAction =\n | { type: \"SET_RATING_STARS\"; payload: number }\n | { type: \"SET_RATING_THUMBS\"; payload: \"thumbsUp\" | \"thumbsDown\" | \"\" }\n | { type: \"SET_RATING_COMMENT\"; payload: string };\n\nconst initialState: RatingState = {\n ratingStars: 0,\n ratingThumbs: \"\",\n ratingComment: \"\",\n};\n\nfunction ratingReducer(state: RatingState, action: RatingAction): RatingState {\n switch (action.type) {\n case \"SET_RATING_STARS\":\n return { ...state, ratingStars: action.payload };\n case \"SET_RATING_THUMBS\":\n return { ...state, ratingThumbs: action.payload };\n case \"SET_RATING_COMMENT\":\n return { ...state, ratingComment: action.payload };\n default:\n return state;\n }\n}\n\ninterface UseRatingsParams {\n assistantId: string;\n topicId: string;\n sendRating: (_ratingData: RatingData) => Promise<any>;\n onError?: (_componentName: string, _error: Error) => void;\n}\n\n\nexport function useRatings({ assistantId, sendRating, topicId, onError }: UseRatingsParams) {\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const [hasReviewed, setHasReviewed] = useState<boolean>(false);\n const [state, dispatch] = useReducer(ratingReducer, initialState);\n\n const setRatingStars = (rating: number) => {\n dispatch({ type: \"SET_RATING_STARS\", payload: rating });\n };\n\n const _setRatingThumbs = (rating: \"thumbsUp\" | \"thumbsDown\" | \"\") => {\n dispatch({ type: \"SET_RATING_THUMBS\", payload: rating });\n };\n\n const setRatingComment = (comment: string) => {\n dispatch({ type: \"SET_RATING_COMMENT\", payload: comment });\n };\n\n const thumbsScore = (value: string) => {\n return value === \"thumbsUp\" ? 5 : value === \"thumbsDown\" ? 0 : 0;\n }\n\n const handleRate = async (key: string, value: any | string, onHandleRateSuccess: (_success: boolean, _err?: string) => void) => {\n setIsLoading(true);\n const sessionId = getTopicSessionId(topicId);\n\n const ratingObj: RatingData = {\n topicId: parseInt(topicId),\n sessionId: sessionId || \"\",\n assistantId: assistantId,\n score: key === \"score\" ? value : thumbsScore(value),\n description: key === \"description\" ? value : state.ratingComment,\n };\n\n try {\n const response = await sendRating(ratingObj);\n if (!response.success) {\n setIsLoading(false);\n const error = new Error(response.error?.message ?? \"Failed to send rating\");\n onHandleRateSuccess(false, error.message);\n onError?.(\"useRatings\", error);\n return;\n }\n\n if (key === \"score\") {\n setRatingStars(value);\n } else if (key === \"description\") {\n setRatingComment(value);\n }\n setHasReviewed(true);\n setIsLoading(false);\n onHandleRateSuccess(true);\n } catch (err) {\n setIsLoading(false);\n const error = err instanceof Error ? err : new Error(String(err));\n onHandleRateSuccess(false, error.message);\n onError?.(\"useRatings\", error);\n }\n };\n\n return {\n handleRate,\n ratingStars: state.ratingStars,\n ratingThumbs: state.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AAa,IAAI;AACjB,UAAM,YAAY,kBAAkB,OAAO;AAE3C,UAAM,YAAwB;AAAA,MAC5B,SAAS,SAAS,OAAO;AAAA,MACzB,WAAY,aAAa;AAAA,MACzB;AAAA,MACA,OAAO,QAAQ,UAAU,QAAQ,YAAY,KAAK;AAAA,MAClD,aAAa,QAAQ,gBAAgB,QAAQ,MAAM;AAAA,IACrD;AAEA,QAAI;AACF,YAAM,WAAW,MAAM,WAAW,SAAS;AAC3C,UAAI,CAAC,SAAS,SAAS;AACrB,qBAAa,KAAK;AAClB,cAAM,QAAQ,IAAI,MAAM,SAAS,OAAO,WAAW,uBAAuB;AAC1E,4BAAoB,OAAO,MAAM,OAAO;AACxC,kBAAU,cAAc,KAAK;AAC7B;AAAA,MACF;AAEA,UAAI,QAAQ,SAAS;AACnB,uBAAe,KAAK;AAAA,MACtB,WAAW,QAAQ,eAAe;AAChC,yBAAiB,KAAK;AAAA,MACxB;AACA,qBAAe,IAAI;AACnB,mBAAa,KAAK;AAClB,0BAAoB,IAAI;AAAA,IAC1B,SAAS,KAAK;AACZ,mBAAa,KAAK;AAClB,YAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAChE,0BAAoB,OAAO,MAAM,OAAO;AACxC,gBAAU,cAAc,KAAK;AAAA,IAC/B;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,aAAa,MAAM;AAAA,IACnB,cAAc,MAAM;AAAA,IACpB,eAAe,MAAM;AAAA,IACrB;AAAA,IACA;AAAA,EACF;AACF;","names":["useCallback","pos","z","z","z","z","def","sessionId","input","messages","useCallback","pendingApprovals","useState","useReducer","useState","useReducer"]}
|