@aigentyc/chat-sdk 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
2
  export { useAigentycChat } from './chunk-3H4CX3MS.js';
3
3
  import './chunk-BKDV2H6Z.js';
4
- import { ChatInterface, PreviewEmbedPanel, LiveChatPanel, MobileLiveChatDrawer, panelMaxWidth, FloatingButton } from './chunk-BKIYPLMT.js';
5
- export { ChatError, ChatErrorBoundary, DEFAULT_PANEL_WIDTH } from './chunk-BKIYPLMT.js';
4
+ import { ChatInterface, PreviewEmbedPanel, LiveChatPanel, MobileLiveChatDrawer, panelMaxWidth, FloatingButton } from './chunk-7TMQBROA.js';
5
+ export { ChatError, ChatErrorBoundary, DEFAULT_PANEL_WIDTH } from './chunk-7TMQBROA.js';
6
6
  import { LiveChatProvider, PreviewEmbedProvider, useIsMobile, usePreviewEmbed } from './chunk-P7UR37HP.js';
7
7
  export { useAutoResize, useLiveChat } from './chunk-P7UR37HP.js';
8
8
  import { ThemeProvider } from './chunk-VQPOUMBC.js';
@@ -13,9 +13,9 @@ import './chunk-MZQKGNWF.js';
13
13
  import { I18nProvider } from './chunk-LDQVDUUJ.js';
14
14
  export { useI18n } from './chunk-LDQVDUUJ.js';
15
15
  export { getToolDisplayData, normalizeToolRows } from './chunk-XEAAB5ZM.js';
16
- import './chunk-CW6LCVNC.js';
17
- import { SlotsProvider, ChatContextProvider, useSlots, renderSlot } from './chunk-JAEXKKSE.js';
18
- export { renderSlot, useChatContext, useSlot, useSlots } from './chunk-JAEXKKSE.js';
16
+ import './chunk-ZPOCKCBF.js';
17
+ import { SlotsProvider, ChatContextProvider, useSlots, renderSlot } from './chunk-G63CLUHC.js';
18
+ export { renderSlot, useChatContext, useSlot, useSlots } from './chunk-G63CLUHC.js';
19
19
  import './chunk-CNPYBLLT.js';
20
20
  import './chunk-PS3U7T37.js';
21
21
  import './chunk-JAOD6CNW.js';
@@ -892,7 +892,7 @@ export { c as ChatAttachmentInput, d as ChatConfig, e as ChatEventCallbacks, f a
892
892
 
893
893
  export { A as AssistantMessageSlotProps, C as ChatInterfaceProps, D as DEFAULT_PANEL_WIDTH, U as UserMessageSlotProps } from './ChatInterface-D5tY6WT1.js';
894
894
 
895
- export { A as AutoResizeOptions, K as KeyboardLanguageOptions, L as LATIN, a as LiveChatReturn, S as SlotComponent, b as SlotName, U as UseAigentycChatOptions, c as UseAigentycChatReturn, d as detectLanguage, r as renderSlot, s as scriptLanguageOf, u as useAigentycChat, e as useAutoResize, f as useChatContext, g as useKeyboardLanguage, h as useLiveChat, i as useSlot, j as useSlots } from './SlotsContext-B_087V7B.js';
895
+ export { A as AutoResizeOptions, K as KeyboardLanguageOptions, L as LATIN, a as LiveChatReturn, S as SlotComponent, b as SlotName, U as UseAigentycChatOptions, c as UseAigentycChatReturn, d as detectLanguage, r as renderSlot, s as scriptLanguageOf, u as useAigentycChat, e as useAutoResize, f as useChatContext, g as useKeyboardLanguage, h as useLiveChat, i as useSlot, j as useSlots } from './SlotsContext-hUp2jze9.js';
896
896
 
897
897
  export { useTheme } from './theme.js';
898
898
 
@@ -909,7 +909,7 @@ export { Chat, ChatError, ChatErrorBoundary, type ChatErrorProps, type ChatProps
909
909
  ### `@aigentyc/chat-sdk/hooks` — Hooks — useAigentycChat, useChatContext, useTheme, useI18n, useLiveChat, useSlots
910
910
 
911
911
  ```ts
912
- export { A as AutoResizeOptions, K as KeyboardLanguageOptions, L as LATIN, a as LiveChatReturn, U as UseAigentycChatOptions, c as UseAigentycChatReturn, d as detectLanguage, s as scriptLanguageOf, u as useAigentycChat, e as useAutoResize, f as useChatContext, g as useKeyboardLanguage, h as useLiveChat, i as useSlot, j as useSlots } from './SlotsContext-B_087V7B.js';
912
+ export { A as AutoResizeOptions, K as KeyboardLanguageOptions, L as LATIN, a as LiveChatReturn, U as UseAigentycChatOptions, c as UseAigentycChatReturn, d as detectLanguage, s as scriptLanguageOf, u as useAigentycChat, e as useAutoResize, f as useChatContext, g as useKeyboardLanguage, h as useLiveChat, i as useSlot, j as useSlots } from './SlotsContext-hUp2jze9.js';
913
913
 
914
914
  export { useTheme } from './theme.js';
915
915
 
package/dist/tools.cjs CHANGED
@@ -2,8 +2,8 @@
2
2
  'use strict';
3
3
 
4
4
  var chunk7AZMWPKX_cjs = require('./chunk-7AZMWPKX.cjs');
5
- var chunkJEK2V5I3_cjs = require('./chunk-JEK2V5I3.cjs');
6
- require('./chunk-UXVOUC2A.cjs');
5
+ var chunkAQTN4QLR_cjs = require('./chunk-AQTN4QLR.cjs');
6
+ require('./chunk-JJRLHXHZ.cjs');
7
7
  require('./chunk-VYBHYFG3.cjs');
8
8
  require('./chunk-JOO6C3XT.cjs');
9
9
  var chunkH7C3AGA2_cjs = require('./chunk-H7C3AGA2.cjs');
@@ -24,15 +24,15 @@ Object.defineProperty(exports, "normalizeToolRows", {
24
24
  });
25
25
  Object.defineProperty(exports, "ComponentRenderer", {
26
26
  enumerable: true,
27
- get: function () { return chunkJEK2V5I3_cjs.ComponentRenderer; }
27
+ get: function () { return chunkAQTN4QLR_cjs.ComponentRenderer; }
28
28
  });
29
29
  Object.defineProperty(exports, "SearchKnowledgeBaseRenderer", {
30
30
  enumerable: true,
31
- get: function () { return chunkJEK2V5I3_cjs.SearchKnowledgeBaseRenderer; }
31
+ get: function () { return chunkAQTN4QLR_cjs.SearchKnowledgeBaseRenderer; }
32
32
  });
33
33
  Object.defineProperty(exports, "ToolRenderer", {
34
34
  enumerable: true,
35
- get: function () { return chunkJEK2V5I3_cjs.ToolRenderer; }
35
+ get: function () { return chunkAQTN4QLR_cjs.ToolRenderer; }
36
36
  });
37
37
  Object.defineProperty(exports, "JsonRenderResult", {
38
38
  enumerable: true,
package/dist/tools.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  export { getToolDisplayData, normalizeToolRows } from './chunk-XEAAB5ZM.js';
3
- export { ComponentRenderer, SearchKnowledgeBaseRenderer, ToolRenderer } from './chunk-CW6LCVNC.js';
4
- import './chunk-JAEXKKSE.js';
3
+ export { ComponentRenderer, SearchKnowledgeBaseRenderer, ToolRenderer } from './chunk-ZPOCKCBF.js';
4
+ import './chunk-G63CLUHC.js';
5
5
  import './chunk-CNPYBLLT.js';
6
6
  import './chunk-PS3U7T37.js';
7
7
  export { JsonRenderResult } from './chunk-ZXP7IYRC.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aigentyc/chat-sdk",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "React SDK for building AI-powered chat interfaces connected to the Aigentyc platform",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/SlotsContext.tsx","../src/providers/ChatContext.tsx"],"names":["createContext","clearMessages","jsx","useContext"],"mappings":";;;;;;AA4CA,IAAM,YAAA,GAAe,aAAA,CAAuB,EAAE,CAAA;AAcvC,SAAS,cAAc,EAAE,KAAA,GAAQ,EAAC,EAAG,UAAS,EAAuB;AAC1E,EAAA,2BACG,YAAA,CAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,OAAQ,QAAA,EAAS,CAAA;AAEnD;AAKO,SAAS,QAAA,GAAoB;AAClC,EAAA,OAAO,WAAW,YAAY,CAAA;AAChC;AAKO,SAAS,QACd,IAAA,EAC8B;AAC9B,EAAA,MAAM,KAAA,GAAQ,WAAW,YAAY,CAAA;AACrC,EAAA,OAAO,MAAM,IAAI,CAAA;AACnB;AAeO,SAAS,UAAA,CACd,IAAA,EACA,KAAA,EACA,gBAAA,EACA,KAAA,EACoB;AACpB,EAAA,MAAM,WAAA,GAAc,KAAA;AACpB,EAAA,MAAM,QAAA,GAAW,MAAM,IAAI,CAAA;AAG3B,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,uBAAO,GAAA,CAAC,QAAA,EAAA,EAAU,GAAG,WAAA,EAAa,gBA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IACZ,OAAO;AAAA,MACL,QAAA;AAAA,MACA,MAAA;AAAA,MACA,KAAA;AAAA,MACA,SAAA;AAAA,MACA,MAAA;AAAA,MACA,WAAA;AAAA,MACA,WAAA;AAAA,MACA,cAAA;AAAA,MACA,aAAA;AAAA,MACA,eAAA;AAAA,MACA,aAAA,EAAAA,cAAAA;AAAA,MACA,WAAW,YAAA,CAAa;AAAA,KAC1B,CAAA;AAAA,IACA;AAAA,MACE,QAAA;AAAA,MACA,MAAA;AAAA,MACA,KAAA;AAAA,MACA,SAAA;AAAA,MACA,MAAA;AAAA,MACA,WAAA;AAAA,MACA,WAAA;AAAA,MACA,cAAA;AAAA,MACA,aAAA;AAAA,MACA,eAAA;AAAA,MACAA;AAAA;AACF,GACF;AAEA,EAAA,uBAAOC,GAAAA,CAAC,WAAA,CAAY,QAAA,EAAZ,EAAqB,OAAe,QAAA,EAAS,CAAA;AACvD;AAKO,SAAS,cAAA,GAAmC;AACjD,EAAA,MAAM,GAAA,GAAMC,WAAW,WAAW,CAAA;AAClC,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT","file":"chunk-JAEXKKSE.js","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n type ComponentType,\n} from \"react\";\n\n/**\n * All available slot names that can be overridden.\n */\nexport type SlotName =\n | \"header\"\n | \"footer\"\n | \"input\"\n | \"welcomePage\"\n | \"userMessage\"\n | \"assistantMessage\"\n | \"systemMessage\"\n | \"loader\"\n | \"feedback\"\n | \"tools\"\n | \"toolRenderers\"\n | \"liveChatPanel\"\n | \"satisfactionRating\"\n | \"visitorIdentityForm\"\n | \"floatingButton\"\n | \"emptyState\"\n | \"error\";\n\n/**\n * A slot component receives the default component as a prop alongside its own props.\n */\nexport type SlotComponent<P = Record<string, unknown>> = ComponentType<\n P & { DefaultComponent: ComponentType<P> }\n>;\n\n/**\n * Map of slot name to override component.\n */\nexport type SlotMap = Partial<Record<SlotName, SlotComponent<any>>>;\n\nconst SlotsContext = createContext<SlotMap>({});\n\n/** Props for the SlotsProvider component. */\nexport interface SlotsProviderProps {\n /** Slot overrides map */\n slots?: SlotMap;\n children: ReactNode;\n}\n\n/**\n * Provides slot overrides to descendant components.\n * Wrap your chat tree with this provider and pass a `slots` map\n * to replace built-in UI sections.\n */\nexport function SlotsProvider({ slots = {}, children }: SlotsProviderProps) {\n return (\n <SlotsContext.Provider value={slots}>{children}</SlotsContext.Provider>\n );\n}\n\n/**\n * Returns the full SlotMap from context.\n */\nexport function useSlots(): SlotMap {\n return useContext(SlotsContext);\n}\n\n/**\n * Returns the override component for the given slot name, or undefined if none is set.\n */\nexport function useSlot<P = Record<string, unknown>>(\n name: SlotName\n): SlotComponent<P> | undefined {\n const slots = useContext(SlotsContext);\n return slots[name] as SlotComponent<P> | undefined;\n}\n\n/**\n * Renders a slot: if an override exists, renders it with `{...props, DefaultComponent}`.\n * Otherwise renders the DefaultComponent with the given props.\n *\n * The generic `P` is NOT constrained to `Record<string, unknown>` so concrete\n * component prop types (e.g. `ChatHeaderProps`) flow through at call sites\n * without `as never` casts. Internal spreads are cast through\n * `Record<string, unknown>` — safe because JSX spread accepts any record.\n *\n * @param name - The slot name\n * @param props - Props to pass to the component\n * @param DefaultComponent - The built-in fallback component\n */\nexport function renderSlot<P>(\n name: SlotName,\n props: P,\n DefaultComponent: ComponentType<P>,\n slots: SlotMap\n): React.ReactElement {\n const spreadProps = props as unknown as Record<string, unknown>;\n const Override = slots[name] as\n | ComponentType<Record<string, unknown> & { DefaultComponent: ComponentType<P> }>\n | undefined;\n if (Override) {\n return <Override {...spreadProps} DefaultComponent={DefaultComponent} />;\n }\n const Default = DefaultComponent as ComponentType<Record<string, unknown>>;\n return <Default {...spreadProps} />;\n}\n","\"use client\";\n\nimport {\n createContext,\n useContext,\n useState,\n useCallback,\n useRef,\n useEffect,\n useMemo,\n type ReactNode,\n} from \"react\";\nimport type {\n ChatConfig,\n ChatMessage,\n ChatEventCallbacks,\n ChatAttachmentInput,\n} from \"../core/types\";\nimport { useChat } from \"@ai-sdk/react\";\nimport { DefaultChatTransport } from \"ai\";\nimport {\n clearMessages as clearStoredMessages,\n loadMessages as loadStoredMessages,\n saveMessages as saveStoredMessages,\n type StoredMessage,\n} from \"../core/message-store\";\n\ntype ChatStatus = \"idle\" | \"streaming\" | \"error\";\n\ninterface ActiveTool {\n toolName: string;\n state: \"partial-call\" | \"call\" | \"output-available\";\n args: Record<string, unknown>;\n result?: unknown;\n renderMode: string;\n}\n\nconst SESSION_KEY_PREFIX = \"aigentyc-session-\";\n\n/**\n * Where this provider used to keep history, before it moved to\n * `core/message-store`.\n *\n * Worth deleting rather than leaving behind. The old writer had no size cap and\n * no expiry, so an established visitor can be carrying a large dead blob under\n * this key — and `localStorage` is a ~5 MB budget shared by the whole origin.\n * Nothing reads the key any more, but the space it holds is space the new\n * store's writes need, and those writes fail SILENTLY when the quota is gone.\n * An orphan left in place would mean persistence quietly stopping for exactly\n * the visitors who had used the chat the most.\n */\nconst LEGACY_MESSAGE_KEY_PREFIX = \"aigentyc-messages-\";\n\nfunction dropLegacyMessageStore(projectId: string): void {\n if (typeof window === \"undefined\") return;\n try {\n localStorage.removeItem(LEGACY_MESSAGE_KEY_PREFIX + projectId);\n } catch {\n // Unavailable or blocked — the old key is harmless, just wasteful.\n }\n}\n\nfunction getOrCreateSessionId(projectId: string): string {\n if (typeof window === \"undefined\") return crypto.randomUUID();\n const key = SESSION_KEY_PREFIX + projectId;\n try {\n const stored = sessionStorage.getItem(key);\n if (stored) return stored;\n const id = crypto.randomUUID();\n sessionStorage.setItem(key, id);\n return id;\n } catch {\n return crypto.randomUUID();\n }\n}\n\n/**\n * History is stored per project AND per session, by `core/message-store`.\n *\n * This used to be three local helpers keyed on `projectId` alone, with no\n * expiry and no size bound, while `message-store` — written for exactly this\n * job, and exported from the package — went unused. The difference is not\n * cosmetic:\n *\n * - **A session could not escape a poisoned history.** The server refuses a\n * turn whose replayed history is too long or too large. Because every\n * session in the project read the same key, that history came back on the\n * next page load, in the next tab and in a new session — so a conversation\n * that broke once answered nothing ever again, which is exactly how this was\n * reported from the field.\n * - **Sessions leaked into each other.** A second tab adopted the first tab's\n * conversation while reporting a different `sessionId` upstream, so the\n * transcript the server logged did not match the one on screen.\n * - **Nothing ever expired.** `message-store` drops history after 24 hours and\n * trims it when it outgrows 200 KB.\n *\n * Persistence across navigation is unchanged: the session id lives in\n * `sessionStorage`, which survives a full page load in the same tab.\n */\nfunction persistMessages(\n projectId: string,\n sessionId: string,\n messages: unknown[]\n): void {\n saveStoredMessages(projectId, sessionId, messages as StoredMessage[]);\n}\n\nfunction loadPersistedMessages(\n projectId: string,\n sessionId: string\n): ChatMessage[] {\n return loadStoredMessages(projectId, sessionId) as unknown as ChatMessage[];\n}\n\nfunction clearPersistedMessages(projectId: string, sessionId: string): void {\n clearStoredMessages(projectId, sessionId);\n}\n\nexport interface ChatContextValue {\n messages: ChatMessage[];\n status: ChatStatus;\n error: Error | undefined;\n sessionId: string;\n config: ChatConfig;\n activeTools: ActiveTool[];\n /**\n * Sends a user turn. `files` travel with it as message parts; a turn carrying\n * files may have empty text — an image on its own is a question.\n */\n sendMessage: (content: string, files?: ChatAttachmentInput[]) => void;\n stopGeneration: () => void;\n /**\n * Re-run the last turn after a failure. No-op while a turn is in flight.\n *\n * Worth offering for a transient refusal — a rate limit, a dropped stream, a\n * momentary 503. It cannot clear a refusal caused by the history itself,\n * because the same history is what gets re-sent; that needs\n * {@link ChatContextValue.newConversation}.\n */\n retryLastTurn: () => void;\n newConversation: () => void;\n clearMessages: () => void;\n callbacks?: ChatEventCallbacks;\n}\n\nexport const ChatContext = createContext<ChatContextValue | null>(null);\n\nexport interface ChatContextProviderProps {\n config: ChatConfig;\n callbacks?: ChatEventCallbacks;\n children: ReactNode;\n}\n\n/**\n * Internal provider that manages chat state via @ai-sdk/react `useChat`.\n * Handles message persistence and session management.\n */\nexport function ChatContextProvider({\n config,\n callbacks,\n children,\n}: ChatContextProviderProps) {\n const projectId = config.projectId || \"default\";\n const [sessionId, setSessionId] = useState(() => getOrCreateSessionId(projectId));\n const callbacksRef = useRef(callbacks);\n callbacksRef.current = callbacks;\n\n // Re-load persisted messages whenever the session changes (incl. after\n // newConversation()). Keying only on mount cached the original array, so\n // useChat would re-inject the OLD messages into the new sessionId — a real\n // \"new chat\" effectively kept the old conversation alive.\n const initialMessages = useMemo(\n () => loadPersistedMessages(projectId, sessionId),\n [projectId, sessionId]\n );\n\n useEffect(() => {\n dropLegacyMessageStore(projectId);\n }, [projectId]);\n\n // Page context is whatever the host page looks like *right now*, so it is read\n // through a ref at send time rather than captured when the transport is built.\n // Rebuilding the transport on every navigation would remount `useChat` and\n // drop an in-flight stream — in a single-page host that is one route change.\n const pageRef = useRef({\n pageUrl: config.pageUrl,\n pageTitle: config.pageTitle,\n pageContext: config.pageContext,\n });\n pageRef.current = {\n pageUrl: config.pageUrl,\n pageTitle: config.pageTitle,\n pageContext: config.pageContext,\n };\n\n const transport = useMemo(\n () =>\n new DefaultChatTransport({\n api: `${config.apiEndpoint || \"\"}/api/kb/chat`,\n headers: config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : undefined,\n // A function body is resolved per request by the AI SDK transport.\n body: () => {\n const { pageUrl, pageTitle, pageContext } = pageRef.current;\n return {\n projectId: config.projectId,\n sessionId,\n ...(pageUrl ? { pageUrl } : {}),\n ...(pageTitle ? { pageTitle } : {}),\n ...(pageContext !== undefined ? { pageContext } : {}),\n };\n },\n }),\n [config.apiEndpoint, config.apiKey, config.projectId, sessionId]\n );\n\n const {\n messages,\n sendMessage: sdkSendMessage,\n status: sdkStatus,\n error,\n stop,\n setMessages,\n regenerate,\n clearError,\n } = useChat({\n id: sessionId,\n messages: initialMessages as never,\n transport,\n onFinish: (message) => {\n callbacksRef.current?.onMessageReceived?.(message as unknown as ChatMessage);\n },\n onError: (err) => {\n callbacksRef.current?.onError?.(err);\n },\n });\n\n const status: ChatStatus = error\n ? \"error\"\n : sdkStatus === \"streaming\" || sdkStatus === \"submitted\"\n ? \"streaming\"\n : \"idle\";\n\n useEffect(() => {\n persistMessages(projectId, sessionId, messages);\n }, [messages, projectId, sessionId]);\n\n const activeTools = useMemo<ActiveTool[]>(() => {\n if (messages.length === 0) return [];\n const last = messages[messages.length - 1] as { role: string; parts?: unknown[] };\n if (last.role !== \"assistant\" || !Array.isArray(last.parts)) return [];\n return (last.parts as Array<Record<string, unknown>>)\n .filter((p) => typeof p.type === \"string\" && (p.type as string).startsWith(\"tool-\"))\n .map((p) => ({\n toolName: (p.toolName as string) || (p.type as string).replace(\"tool-\", \"\"),\n state: (p.state as ActiveTool[\"state\"]) || \"output-available\",\n args: (p.args as Record<string, unknown>) || {},\n result: p.result,\n renderMode: (p.renderMode as string) || \"inline\",\n }));\n }, [messages]);\n\n const sendMessage = useCallback(\n (content: string, files?: ChatAttachmentInput[]) => {\n // An attachment is a message on its own, so an empty string only blocks\n // the send when nothing else is going with it.\n if (!content.trim() && (!files || files.length === 0)) return;\n callbacksRef.current?.onMessageSent?.({\n id: crypto.randomUUID(),\n role: \"user\",\n content,\n } as ChatMessage);\n sdkSendMessage({\n text: content,\n ...(files && files.length > 0\n ? { files: files.map((f) => ({ ...f, type: \"file\" as const })) }\n : {}),\n });\n },\n [sdkSendMessage]\n );\n\n const stopGeneration = useCallback(() => stop(), [stop]);\n\n // `clearError` first: the error is what the UI is rendering, and leaving it\n // set would keep the failure card on screen next to the turn now streaming.\n //\n // The empty check is not defensive padding. `regenerate()` THROWS when there\n // is no message to re-run, and a host that calls `clearMessages()` while a\n // failure is on screen leaves exactly that state — no messages, error still\n // set, so the card is still rendered and still offering its button. Left\n // alone it would also be an unhandled rejection, since nothing awaits this.\n const retryLastTurn = useCallback(() => {\n clearError();\n if (messages.length === 0) return;\n regenerate().catch(() => {\n // Request failures already land in `error` via useChat's own handling;\n // this only stops a rejected promise escaping the click handler.\n });\n }, [clearError, regenerate, messages]);\n\n const newConversation = useCallback(() => {\n setMessages([]);\n clearPersistedMessages(projectId, sessionId);\n if (typeof window !== \"undefined\") {\n try {\n sessionStorage.removeItem(SESSION_KEY_PREFIX + projectId);\n } catch {\n // ignore\n }\n }\n setSessionId(getOrCreateSessionId(projectId));\n }, [projectId, sessionId, setMessages]);\n\n const clearMessages = useCallback(() => {\n setMessages([]);\n clearPersistedMessages(projectId, sessionId);\n }, [projectId, sessionId, setMessages]);\n\n const value = useMemo<ChatContextValue>(\n () => ({\n messages: messages as unknown as ChatMessage[],\n status,\n error: error as Error | undefined,\n sessionId,\n config,\n activeTools,\n sendMessage,\n stopGeneration,\n retryLastTurn,\n newConversation,\n clearMessages,\n callbacks: callbacksRef.current,\n }),\n [\n messages,\n status,\n error,\n sessionId,\n config,\n activeTools,\n sendMessage,\n stopGeneration,\n retryLastTurn,\n newConversation,\n clearMessages,\n ]\n );\n\n return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;\n}\n\n/**\n * Returns the chat context. Must be used within a `ChatContextProvider`.\n */\nexport function useChatContext(): ChatContextValue {\n const ctx = useContext(ChatContext);\n if (!ctx) {\n throw new Error(\n \"useChatContext must be used within a ChatProvider or ChatContextProvider\"\n );\n }\n return ctx;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/SlotsContext.tsx","../src/providers/ChatContext.tsx"],"names":["createContext","useContext","jsx","saveMessages","loadMessages","clearMessages","useState","useRef","useMemo","useEffect","DefaultChatTransport","useChat","useCallback"],"mappings":";;;;;;;;AA4CA,IAAM,YAAA,GAAeA,mBAAA,CAAuB,EAAE,CAAA;AAcvC,SAAS,cAAc,EAAE,KAAA,GAAQ,EAAC,EAAG,UAAS,EAAuB;AAC1E,EAAA,sCACG,YAAA,CAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,OAAQ,QAAA,EAAS,CAAA;AAEnD;AAKO,SAAS,QAAA,GAAoB;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UXVOUC2A.cjs","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport {\n createContext,\n useContext,\n type ReactNode,\n type ComponentType,\n} from \"react\";\n\n/**\n * All available slot names that can be overridden.\n */\nexport type SlotName =\n | \"header\"\n | \"footer\"\n | \"input\"\n | \"welcomePage\"\n | \"userMessage\"\n | \"assistantMessage\"\n | \"systemMessage\"\n | \"loader\"\n | \"feedback\"\n | \"tools\"\n | \"toolRenderers\"\n | \"liveChatPanel\"\n | \"satisfactionRating\"\n | \"visitorIdentityForm\"\n | \"floatingButton\"\n | \"emptyState\"\n | \"error\";\n\n/**\n * A slot component receives the default component as a prop alongside its own props.\n */\nexport type SlotComponent<P = Record<string, unknown>> = ComponentType<\n P & { DefaultComponent: ComponentType<P> }\n>;\n\n/**\n * Map of slot name to override component.\n */\nexport type SlotMap = Partial<Record<SlotName, SlotComponent<any>>>;\n\nconst SlotsContext = createContext<SlotMap>({});\n\n/** Props for the SlotsProvider component. */\nexport interface SlotsProviderProps {\n /** Slot overrides map */\n slots?: SlotMap;\n children: ReactNode;\n}\n\n/**\n * Provides slot overrides to descendant components.\n * Wrap your chat tree with this provider and pass a `slots` map\n * to replace built-in UI sections.\n */\nexport function SlotsProvider({ slots = {}, children }: SlotsProviderProps) {\n return (\n <SlotsContext.Provider value={slots}>{children}</SlotsContext.Provider>\n );\n}\n\n/**\n * Returns the full SlotMap from context.\n */\nexport function useSlots(): SlotMap {\n return useContext(SlotsContext);\n}\n\n/**\n * Returns the override component for the given slot name, or undefined if none is set.\n */\nexport function useSlot<P = Record<string, unknown>>(\n name: SlotName\n): SlotComponent<P> | undefined {\n const slots = useContext(SlotsContext);\n return slots[name] as SlotComponent<P> | undefined;\n}\n\n/**\n * Renders a slot: if an override exists, renders it with `{...props, DefaultComponent}`.\n * Otherwise renders the DefaultComponent with the given props.\n *\n * The generic `P` is NOT constrained to `Record<string, unknown>` so concrete\n * component prop types (e.g. `ChatHeaderProps`) flow through at call sites\n * without `as never` casts. Internal spreads are cast through\n * `Record<string, unknown>` — safe because JSX spread accepts any record.\n *\n * @param name - The slot name\n * @param props - Props to pass to the component\n * @param DefaultComponent - The built-in fallback component\n */\nexport function renderSlot<P>(\n name: SlotName,\n props: P,\n DefaultComponent: ComponentType<P>,\n slots: SlotMap\n): React.ReactElement {\n const spreadProps = props as unknown as Record<string, unknown>;\n const Override = slots[name] as\n | ComponentType<Record<string, unknown> & { DefaultComponent: ComponentType<P> }>\n | undefined;\n if (Override) {\n return <Override {...spreadProps} DefaultComponent={DefaultComponent} />;\n }\n const Default = DefaultComponent as ComponentType<Record<string, unknown>>;\n return <Default {...spreadProps} />;\n}\n","\"use client\";\n\nimport {\n createContext,\n useContext,\n useState,\n useCallback,\n useRef,\n useEffect,\n useMemo,\n type ReactNode,\n} from \"react\";\nimport type {\n ChatConfig,\n ChatMessage,\n ChatEventCallbacks,\n ChatAttachmentInput,\n} from \"../core/types\";\nimport { useChat } from \"@ai-sdk/react\";\nimport { DefaultChatTransport } from \"ai\";\nimport {\n clearMessages as clearStoredMessages,\n loadMessages as loadStoredMessages,\n saveMessages as saveStoredMessages,\n type StoredMessage,\n} from \"../core/message-store\";\n\ntype ChatStatus = \"idle\" | \"streaming\" | \"error\";\n\ninterface ActiveTool {\n toolName: string;\n state: \"partial-call\" | \"call\" | \"output-available\";\n args: Record<string, unknown>;\n result?: unknown;\n renderMode: string;\n}\n\nconst SESSION_KEY_PREFIX = \"aigentyc-session-\";\n\n/**\n * Where this provider used to keep history, before it moved to\n * `core/message-store`.\n *\n * Worth deleting rather than leaving behind. The old writer had no size cap and\n * no expiry, so an established visitor can be carrying a large dead blob under\n * this key — and `localStorage` is a ~5 MB budget shared by the whole origin.\n * Nothing reads the key any more, but the space it holds is space the new\n * store's writes need, and those writes fail SILENTLY when the quota is gone.\n * An orphan left in place would mean persistence quietly stopping for exactly\n * the visitors who had used the chat the most.\n */\nconst LEGACY_MESSAGE_KEY_PREFIX = \"aigentyc-messages-\";\n\nfunction dropLegacyMessageStore(projectId: string): void {\n if (typeof window === \"undefined\") return;\n try {\n localStorage.removeItem(LEGACY_MESSAGE_KEY_PREFIX + projectId);\n } catch {\n // Unavailable or blocked — the old key is harmless, just wasteful.\n }\n}\n\nfunction getOrCreateSessionId(projectId: string): string {\n if (typeof window === \"undefined\") return crypto.randomUUID();\n const key = SESSION_KEY_PREFIX + projectId;\n try {\n const stored = sessionStorage.getItem(key);\n if (stored) return stored;\n const id = crypto.randomUUID();\n sessionStorage.setItem(key, id);\n return id;\n } catch {\n return crypto.randomUUID();\n }\n}\n\n/**\n * History is stored per project AND per session, by `core/message-store`.\n *\n * This used to be three local helpers keyed on `projectId` alone, with no\n * expiry and no size bound, while `message-store` — written for exactly this\n * job, and exported from the package — went unused. The difference is not\n * cosmetic:\n *\n * - **A session could not escape a poisoned history.** The server refuses a\n * turn whose replayed history is too long or too large. Because every\n * session in the project read the same key, that history came back on the\n * next page load, in the next tab and in a new session — so a conversation\n * that broke once answered nothing ever again, which is exactly how this was\n * reported from the field.\n * - **Sessions leaked into each other.** A second tab adopted the first tab's\n * conversation while reporting a different `sessionId` upstream, so the\n * transcript the server logged did not match the one on screen.\n * - **Nothing ever expired.** `message-store` drops history after 24 hours and\n * trims it when it outgrows 200 KB.\n *\n * Persistence across navigation is unchanged: the session id lives in\n * `sessionStorage`, which survives a full page load in the same tab.\n */\nfunction persistMessages(\n projectId: string,\n sessionId: string,\n messages: unknown[]\n): void {\n saveStoredMessages(projectId, sessionId, messages as StoredMessage[]);\n}\n\nfunction loadPersistedMessages(\n projectId: string,\n sessionId: string\n): ChatMessage[] {\n return loadStoredMessages(projectId, sessionId) as unknown as ChatMessage[];\n}\n\nfunction clearPersistedMessages(projectId: string, sessionId: string): void {\n clearStoredMessages(projectId, sessionId);\n}\n\nexport interface ChatContextValue {\n messages: ChatMessage[];\n status: ChatStatus;\n error: Error | undefined;\n sessionId: string;\n config: ChatConfig;\n activeTools: ActiveTool[];\n /**\n * Sends a user turn. `files` travel with it as message parts; a turn carrying\n * files may have empty text — an image on its own is a question.\n */\n sendMessage: (content: string, files?: ChatAttachmentInput[]) => void;\n stopGeneration: () => void;\n /**\n * Re-run the last turn after a failure. No-op while a turn is in flight.\n *\n * Worth offering for a transient refusal — a rate limit, a dropped stream, a\n * momentary 503. It cannot clear a refusal caused by the history itself,\n * because the same history is what gets re-sent; that needs\n * {@link ChatContextValue.newConversation}.\n */\n retryLastTurn: () => void;\n newConversation: () => void;\n clearMessages: () => void;\n callbacks?: ChatEventCallbacks;\n}\n\nexport const ChatContext = createContext<ChatContextValue | null>(null);\n\nexport interface ChatContextProviderProps {\n config: ChatConfig;\n callbacks?: ChatEventCallbacks;\n children: ReactNode;\n}\n\n/**\n * Internal provider that manages chat state via @ai-sdk/react `useChat`.\n * Handles message persistence and session management.\n */\nexport function ChatContextProvider({\n config,\n callbacks,\n children,\n}: ChatContextProviderProps) {\n const projectId = config.projectId || \"default\";\n const [sessionId, setSessionId] = useState(() => getOrCreateSessionId(projectId));\n const callbacksRef = useRef(callbacks);\n callbacksRef.current = callbacks;\n\n // Re-load persisted messages whenever the session changes (incl. after\n // newConversation()). Keying only on mount cached the original array, so\n // useChat would re-inject the OLD messages into the new sessionId — a real\n // \"new chat\" effectively kept the old conversation alive.\n const initialMessages = useMemo(\n () => loadPersistedMessages(projectId, sessionId),\n [projectId, sessionId]\n );\n\n useEffect(() => {\n dropLegacyMessageStore(projectId);\n }, [projectId]);\n\n // Page context is whatever the host page looks like *right now*, so it is read\n // through a ref at send time rather than captured when the transport is built.\n // Rebuilding the transport on every navigation would remount `useChat` and\n // drop an in-flight stream — in a single-page host that is one route change.\n const pageRef = useRef({\n pageUrl: config.pageUrl,\n pageTitle: config.pageTitle,\n pageContext: config.pageContext,\n });\n pageRef.current = {\n pageUrl: config.pageUrl,\n pageTitle: config.pageTitle,\n pageContext: config.pageContext,\n };\n\n const transport = useMemo(\n () =>\n new DefaultChatTransport({\n api: `${config.apiEndpoint || \"\"}/api/kb/chat`,\n headers: config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : undefined,\n // A function body is resolved per request by the AI SDK transport.\n body: () => {\n const { pageUrl, pageTitle, pageContext } = pageRef.current;\n return {\n projectId: config.projectId,\n sessionId,\n ...(pageUrl ? { pageUrl } : {}),\n ...(pageTitle ? { pageTitle } : {}),\n ...(pageContext !== undefined ? { pageContext } : {}),\n };\n },\n }),\n [config.apiEndpoint, config.apiKey, config.projectId, sessionId]\n );\n\n const {\n messages,\n sendMessage: sdkSendMessage,\n status: sdkStatus,\n error,\n stop,\n setMessages,\n regenerate,\n clearError,\n } = useChat({\n id: sessionId,\n messages: initialMessages as never,\n transport,\n onFinish: (message) => {\n callbacksRef.current?.onMessageReceived?.(message as unknown as ChatMessage);\n },\n onError: (err) => {\n callbacksRef.current?.onError?.(err);\n },\n });\n\n const status: ChatStatus = error\n ? \"error\"\n : sdkStatus === \"streaming\" || sdkStatus === \"submitted\"\n ? \"streaming\"\n : \"idle\";\n\n useEffect(() => {\n persistMessages(projectId, sessionId, messages);\n }, [messages, projectId, sessionId]);\n\n const activeTools = useMemo<ActiveTool[]>(() => {\n if (messages.length === 0) return [];\n const last = messages[messages.length - 1] as { role: string; parts?: unknown[] };\n if (last.role !== \"assistant\" || !Array.isArray(last.parts)) return [];\n return (last.parts as Array<Record<string, unknown>>)\n .filter((p) => typeof p.type === \"string\" && (p.type as string).startsWith(\"tool-\"))\n .map((p) => ({\n toolName: (p.toolName as string) || (p.type as string).replace(\"tool-\", \"\"),\n state: (p.state as ActiveTool[\"state\"]) || \"output-available\",\n args: (p.args as Record<string, unknown>) || {},\n result: p.result,\n renderMode: (p.renderMode as string) || \"inline\",\n }));\n }, [messages]);\n\n const sendMessage = useCallback(\n (content: string, files?: ChatAttachmentInput[]) => {\n // An attachment is a message on its own, so an empty string only blocks\n // the send when nothing else is going with it.\n if (!content.trim() && (!files || files.length === 0)) return;\n callbacksRef.current?.onMessageSent?.({\n id: crypto.randomUUID(),\n role: \"user\",\n content,\n } as ChatMessage);\n sdkSendMessage({\n text: content,\n ...(files && files.length > 0\n ? { files: files.map((f) => ({ ...f, type: \"file\" as const })) }\n : {}),\n });\n },\n [sdkSendMessage]\n );\n\n const stopGeneration = useCallback(() => stop(), [stop]);\n\n // `clearError` first: the error is what the UI is rendering, and leaving it\n // set would keep the failure card on screen next to the turn now streaming.\n //\n // The empty check is not defensive padding. `regenerate()` THROWS when there\n // is no message to re-run, and a host that calls `clearMessages()` while a\n // failure is on screen leaves exactly that state — no messages, error still\n // set, so the card is still rendered and still offering its button. Left\n // alone it would also be an unhandled rejection, since nothing awaits this.\n const retryLastTurn = useCallback(() => {\n clearError();\n if (messages.length === 0) return;\n regenerate().catch(() => {\n // Request failures already land in `error` via useChat's own handling;\n // this only stops a rejected promise escaping the click handler.\n });\n }, [clearError, regenerate, messages]);\n\n const newConversation = useCallback(() => {\n setMessages([]);\n clearPersistedMessages(projectId, sessionId);\n if (typeof window !== \"undefined\") {\n try {\n sessionStorage.removeItem(SESSION_KEY_PREFIX + projectId);\n } catch {\n // ignore\n }\n }\n setSessionId(getOrCreateSessionId(projectId));\n }, [projectId, sessionId, setMessages]);\n\n const clearMessages = useCallback(() => {\n setMessages([]);\n clearPersistedMessages(projectId, sessionId);\n }, [projectId, sessionId, setMessages]);\n\n const value = useMemo<ChatContextValue>(\n () => ({\n messages: messages as unknown as ChatMessage[],\n status,\n error: error as Error | undefined,\n sessionId,\n config,\n activeTools,\n sendMessage,\n stopGeneration,\n retryLastTurn,\n newConversation,\n clearMessages,\n callbacks: callbacksRef.current,\n }),\n [\n messages,\n status,\n error,\n sessionId,\n config,\n activeTools,\n sendMessage,\n stopGeneration,\n retryLastTurn,\n newConversation,\n clearMessages,\n ]\n );\n\n return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;\n}\n\n/**\n * Returns the chat context. Must be used within a `ChatContextProvider`.\n */\nexport function useChatContext(): ChatContextValue {\n const ctx = useContext(ChatContext);\n if (!ctx) {\n throw new Error(\n \"useChatContext must be used within a ChatProvider or ChatContextProvider\"\n );\n }\n return ctx;\n}\n"]}