@assistant-ui/react 0.5.59 → 0.5.60

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/assistant-ui/assistant-ui/packages/react/dist/index.js","../src/context/providers/AssistantRuntimeProvider.tsx","../src/context/providers/AssistantProvider.tsx","../src/context/react/AssistantContext.ts","../src/context/react/utils/createContextHook.ts","../src/context/react/utils/createContextStoreHook.ts","../src/context/stores/AssistantToolUIs.ts","../src/context/providers/ThreadProvider.tsx","../src/context/react/ThreadContext.ts","../src/context/stores/ThreadComposer.ts","../src/context/stores/Thread.ts","../src/context/stores/ThreadViewport.tsx","../src/context/stores/ThreadActions.ts","../src/context/stores/ThreadMessages.ts","../src/context/stores/ThreadRuntime.tsx","../src/runtimes/core/subscribeToMainThread.ts","../src/runtimes/local/useLocalRuntime.tsx","../src/runtimes/core/BaseAssistantRuntime.tsx","../src/internal.ts","../src/runtimes/utils/ThreadRuntimeComposer.tsx","../src/utils/ProxyConfigProvider.ts","../src/utils/idUtils.tsx","../src/runtimes/edge/converters/fromCoreMessage.ts","../src/runtimes/utils/MessageRepository.tsx","../src/utils/smooth/useSmooth.tsx","../src/utils/smooth/SmoothContext.tsx","../src/context/react/ContentPartContext.ts","../src/context/ReadonlyStore.ts","../src/ui/base/tooltip-icon-button.tsx","../src/ui/base/tooltip.tsx","../src/ui/utils/withDefaults.tsx","../src/ui/base/button.tsx","../src/runtimes/edge/converters/fromLanguageModelMessages.ts","../src/runtimes/edge/converters/fromLanguageModelTools.ts","../src/runtimes/edge/streams/utils/chunkByLineStream.ts","../src/runtimes/edge/streams/utils/streamPartDecoderStream.ts","../src/runtimes/edge/streams/utils/index.ts","../src/runtimes/edge/useEdgeRuntime.ts","../src/runtimes/edge/streams/assistantDecoderStream.ts","../src/runtimes/edge/EdgeChatAdapter.ts","../src/runtimes/local/shouldContinue.tsx","../src/runtimes/local/LocalThreadRuntime.tsx","../src/runtimes/local/LocalRuntime.tsx","../src/runtimes/external-store/getExternalStoreMessage.tsx","../src/runtimes/external-store/ThreadMessageConverter.ts","../src/runtimes/external-store/auto-status.tsx","../src/runtimes/external-store/ThreadMessageLike.tsx","../src/utils/getThreadMessageText.tsx","../src/runtimes/external-store/ExternalStoreThreadRuntime.tsx","../src/runtimes/external-store/ExternalStoreRuntime.tsx","../src/runtimes/external-store/useExternalStoreRuntime.tsx","../src/runtimes/external-store/external-message-converter.tsx","../src/runtimes/dangerous-in-browser/useDangerousInBrowserRuntime.ts","../src/runtimes/dangerous-in-browser/DangerousInBrowserAdapter.ts","../src/runtimes/speech/WebSpeechSynthesisAdapter.ts","../src/runtimes/attachment/SimpleImageAttachmentAdapter.ts","../src/runtimes/attachment/SimpleTextAttachmentAdapter.ts","../src/runtimes/attachment/CompositeAttachmentAdapter.ts","../src/context/stores/AssistantActions.tsx","../src/context/stores/AssistantRuntime.tsx","../src/context/providers/TextContentPartProvider.tsx","../src/context/react/MessageContext.ts","../src/context/react/ComposerContext.ts","../src/hooks/useAppendMessage.tsx","../src/hooks/useSwitchToNewThread.tsx","../src/model-config/useAssistantTool.tsx","../src/model-config/makeAssistantTool.tsx","../src/model-config/useAssistantToolUI.tsx","../src/model-config/makeAssistantToolUI.tsx","../src/model-config/useAssistantInstructions.tsx","../src/primitive-hooks/actionBar/useActionBarCopy.tsx","../src/utils/combined/useCombinedStore.ts","../src/utils/combined/createCombinedStore.ts","../src/primitive-hooks/actionBar/useActionBarEdit.tsx","../src/primitive-hooks/actionBar/useActionBarReload.tsx","../src/primitive-hooks/actionBar/useActionBarSpeak.tsx","../src/primitive-hooks/actionBar/useActionBarStopSpeaking.tsx","../src/primitive-hooks/branchPicker/useBranchPickerCount.tsx","../src/primitive-hooks/branchPicker/useBranchPickerNext.tsx","../src/primitive-hooks/branchPicker/useBranchPickerNumber.tsx","../src/primitive-hooks/branchPicker/useBranchPickerPrevious.tsx","../src/primitive-hooks/composer/useComposerCancel.tsx","../src/primitive-hooks/composer/useComposerIf.tsx","../src/primitive-hooks/composer/useComposerSend.tsx","../src/primitive-hooks/composer/useComposerAddAttachment.tsx","../src/primitive-hooks/contentPart/useContentPartDisplay.tsx","../src/primitive-hooks/contentPart/useContentPartImage.tsx","../src/primitive-hooks/contentPart/useContentPartText.tsx","../src/primitive-hooks/message/useMessageIf.tsx","../src/primitive-hooks/thread/useThreadIf.tsx","../src/primitive-hooks/thread/useThreadEmpty.tsx","../src/primitive-hooks/thread/useThreadScrollToBottom.tsx","../src/primitive-hooks/thread/useThreadSuggestion.tsx","../src/primitives/actionBar/index.ts","../src/primitives/actionBar/ActionBarRoot.tsx","../src/primitives/actionBar/useActionBarFloatStatus.tsx","../src/utils/createActionButton.tsx","../src/primitives/actionBar/ActionBarCopy.tsx","../src/primitives/actionBar/ActionBarReload.tsx","../src/primitives/actionBar/ActionBarEdit.tsx","../src/primitives/actionBar/ActionBarSpeak.tsx","../src/primitives/actionBar/ActionBarStopSpeaking.tsx","../src/primitives/assistantModal/index.ts","../src/primitives/assistantModal/AssistantModalRoot.tsx","../src/utils/hooks/useOnComposerFocus.tsx","../src/primitives/assistantModal/scope.tsx","../src/primitives/assistantModal/AssistantModalTrigger.tsx","../src/primitives/assistantModal/AssistantModalContent.tsx","../src/primitives/assistantModal/AssistantModalAnchor.tsx","../src/primitives/branchPicker/index.ts","../src/primitives/branchPicker/BranchPickerNext.tsx","../src/primitives/branchPicker/BranchPickerPrevious.tsx","../src/primitives/branchPicker/BranchPickerCount.tsx","../src/primitives/branchPicker/BranchPickerNumber.tsx","../src/primitives/branchPicker/BranchPickerRoot.tsx","../src/primitives/message/index.ts","../src/primitives/message/MessageRoot.tsx","../src/utils/hooks/useManagedRef.ts","../src/primitives/message/MessageIf.tsx","../src/primitives/message/MessageContent.tsx","../src/context/providers/ContentPartProvider.tsx","../src/primitives/contentPart/ContentPartText.tsx","../src/primitives/contentPart/ContentPartImage.tsx","../src/primitives/contentPart/ContentPartDisplay.tsx","../src/primitives/contentPart/ContentPartInProgress.tsx","../src/primitives/message/MessageInProgress.tsx","../src/primitives/message/MessageAttachments.tsx","../src/context/react/AttachmentContext.ts","../src/context/providers/MessageAttachmentProvider.tsx","../src/primitives/composer/index.ts","../src/primitives/composer/ComposerRoot.tsx","../src/primitives/composer/ComposerInput.tsx","../src/primitives/composer/ComposerSend.tsx","../src/primitives/composer/ComposerCancel.tsx","../src/primitives/composer/ComposerAddAttachment.tsx","../src/primitives/composer/ComposerAttachments.tsx","../src/context/providers/ComposerAttachmentProvider.tsx","../src/primitives/composer/ComposerIf.tsx","../src/primitives/contentPart/index.ts","../src/primitives/thread/index.ts","../src/primitives/thread/ThreadRoot.tsx","../src/primitives/thread/ThreadEmpty.tsx","../src/primitives/thread/ThreadIf.tsx","../src/primitives/thread/ThreadViewport.tsx","../src/primitive-hooks/thread/useThreadViewportAutoScroll.tsx","../src/utils/hooks/useOnResizeContent.tsx","../src/utils/hooks/useOnScrollToBottom.tsx","../src/primitives/thread/ThreadMessages.tsx","../src/context/providers/MessageProvider.tsx","../src/context/stores/EditComposer.ts","../src/context/stores/MessageUtils.ts","../src/primitives/thread/ThreadScrollToBottom.tsx","../src/primitives/thread/ThreadSuggestion.tsx","../src/ui/thread-config.tsx","../src/ui/assistant-action-bar.tsx","../src/ui/assistant-message.tsx","../src/ui/branch-picker.tsx","../src/ui/base/avatar.tsx","../src/ui/content-part.tsx","../src/ui/assistant-modal.tsx","../src/ui/thread.tsx","../src/ui/composer.tsx","../src/ui/base/CircleStopIcon.tsx","../src/ui/composer-attachment.tsx","../src/ui/thread-welcome.tsx","../src/ui/user-message.tsx","../src/ui/user-action-bar.tsx","../src/ui/user-message-attachment.tsx","../src/ui/edit-composer.tsx"],"names":["useEffect","useInsertionEffect","useEditComposer","Primitive","COMPLETE_STATUS","useContentPartContext","useMessageAttachmentContext","useEscapeKeydown","getAttachment","useComposerAttachmentContext","getComponent","AttachmentComponent","create","useMessageContext","BranchPickerPrevious","exports","ComposerAttachment"],"mappings":"AAAA,+rCAAY;AACZ;AAC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AA;AAAA,QAAA;AACZ,MAAA;AACF,IAAA;AAEJ,EAAA;AAEH;AAED;AAEM;AACJ,EAAA;AACA,EAAA;AACD;AAED;AAEMA;AACJ,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAEO;A/J67JD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/assistant-ui/assistant-ui/packages/react/dist/index.js","sourcesContent":[null,"import type { FC, PropsWithChildren } from \"react\";\nimport { memo } from \"react\";\nimport type { AssistantRuntime } from \"../../runtimes/core/AssistantRuntime\";\nimport { AssistantProvider } from \"./AssistantProvider\";\n\ntype AssistantRuntimeProviderProps = {\n runtime: AssistantRuntime;\n};\n\nconst AssistantRuntimeProviderImpl: FC<\n PropsWithChildren<AssistantRuntimeProviderProps>\n> = ({ children, runtime }) => {\n return <AssistantProvider runtime={runtime}>{children}</AssistantProvider>;\n};\n\nexport const AssistantRuntimeProvider = memo(AssistantRuntimeProviderImpl);\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useInsertionEffect, useRef, useState } from \"react\";\nimport type { AssistantRuntime } from \"../../runtimes\";\nimport { AssistantContext } from \"../react/AssistantContext\";\nimport { makeAssistantToolUIsStore } from \"../stores/AssistantToolUIs\";\nimport { ThreadProvider } from \"./ThreadProvider\";\nimport { makeAssistantActionsStore } from \"../stores/AssistantActions\";\nimport { makeAssistantRuntimeStore } from \"../stores/AssistantRuntime\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype AssistantProviderProps = {\n runtime: AssistantRuntime;\n};\n\nexport const AssistantProvider: FC<\n PropsWithChildren<AssistantProviderProps>\n> = ({ children, runtime }) => {\n const runtimeRef = useRef(runtime);\n useInsertionEffect(() => {\n runtimeRef.current = runtime;\n });\n\n const [context] = useState(() => {\n const useAssistantRuntime = makeAssistantRuntimeStore(runtime);\n const useToolUIs = makeAssistantToolUIsStore();\n const useAssistantActions = makeAssistantActionsStore(runtimeRef);\n\n return {\n useToolUIs,\n useAssistantRuntime,\n useAssistantActions,\n };\n });\n\n useEffect(\n () => writableStore(context.useAssistantRuntime).setState(runtime, true),\n [runtime, context],\n );\n\n return (\n <AssistantContext.Provider value={context}>\n <ThreadProvider provider={runtime}>{children}</ThreadProvider>\n </AssistantContext.Provider>\n );\n};\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { AssistantToolUIsState } from \"../stores/AssistantToolUIs\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { AssistantActionsState } from \"../stores/AssistantActions\";\nimport { AssistantRuntime } from \"../../runtimes\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type AssistantContextValue = {\n useToolUIs: UseBoundStore<ReadonlyStore<AssistantToolUIsState>>;\n useAssistantRuntime: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n useAssistantActions: UseBoundStore<ReadonlyStore<AssistantActionsState>>;\n};\n\nexport const AssistantContext = createContext<AssistantContextValue | null>(\n null,\n);\n\nexport const useAssistantContext = createContextHook(\n AssistantContext,\n \"AssistantRuntimeProvider\",\n);\n\nexport const { useAssistantRuntime, useAssistantRuntimeStore } =\n createContextStoreHook(useAssistantContext, \"useAssistantRuntime\");\n\nexport const { useToolUIs, useToolUIsStore } = createContextStoreHook(\n useAssistantContext,\n \"useToolUIs\",\n);\n\nexport const { useAssistantActions, useAssistantActionsStore } =\n createContextStoreHook(useAssistantContext, \"useAssistantActions\");\n","import { useContext, Context } from \"react\";\n\n/**\n * Creates a context hook with optional support.\n * @param context - The React context to consume.\n * @param providerName - The name of the provider for error messages.\n * @returns A hook function that provides the context value.\n */\nexport function createContextHook<T>(\n context: Context<T | null>,\n providerName: string,\n) {\n function useContextHook(options?: { optional?: false | undefined }): T;\n function useContextHook(options?: {\n optional?: boolean | undefined;\n }): T | null;\n function useContextHook(options?: { optional?: boolean | undefined }) {\n const contextValue = useContext(context);\n if (!options?.optional && !contextValue) {\n throw new Error(`This component must be used within ${providerName}.`);\n }\n return contextValue;\n }\n\n return useContextHook;\n}\n","import { UseBoundStore } from \"zustand\";\nimport { ReadonlyStore } from \"../../ReadonlyStore\";\n\n/**\n * Creates hooks for accessing a store within a context.\n * @param contextHook - The hook to access the context.\n * @param contextKey - The key of the store in the context.\n * @returns An object containing the hooks: `use...` and `use...Store`.\n */\nexport function createContextStoreHook<T, K extends keyof T & string>(\n contextHook: (options?: { optional?: boolean }) => T | null,\n contextKey: K,\n) {\n type StoreType = T[K];\n type StateType = StoreType extends ReadonlyStore<infer S> ? S : never;\n\n // Define useStoreStoreHook with overloads\n function useStoreStoreHook(): ReadonlyStore<StateType>;\n function useStoreStoreHook(options: {\n optional: true;\n }): ReadonlyStore<StateType> | null;\n function useStoreStoreHook(options?: {\n optional?: boolean;\n }): ReadonlyStore<StateType> | null {\n const context = contextHook(options);\n if (!context) {\n if (!options?.optional) {\n throw new Error(`This component must be used within a ${contextKey}.`);\n }\n return null;\n }\n return context[contextKey] as ReadonlyStore<StateType>;\n }\n\n // Define useStoreHook with overloads\n function useStoreHook(): StateType;\n function useStoreHook<TSelected>(\n selector: (state: StateType) => TSelected,\n ): TSelected;\n function useStoreHook(options: { optional: true }): StateType | null;\n function useStoreHook<TSelected>(options: {\n optional: true;\n selector?: (state: StateType) => TSelected;\n }): TSelected | null;\n function useStoreHook<TSelected>(\n param?:\n | ((state: StateType) => TSelected)\n | {\n optional?: boolean;\n selector?: (state: StateType) => TSelected;\n },\n ): TSelected | StateType | null {\n let optional = false;\n let selector: ((state: StateType) => TSelected) | undefined;\n\n if (typeof param === \"function\") {\n selector = param;\n } else if (param && typeof param === \"object\") {\n optional = !!param.optional;\n selector = param.selector;\n }\n\n const store = useStoreStoreHook({\n optional,\n } as any) as UseBoundStore<ReadonlyStore<StateType>>;\n if (!store) return null;\n return selector ? store(selector) : store();\n }\n\n // Return an object with keys based on contextKey\n return {\n [contextKey]: useStoreHook,\n [`${contextKey}Store`]: useStoreStoreHook,\n } as {\n [P in K]: typeof useStoreHook;\n } & {\n [P in `${K}Store`]: typeof useStoreStoreHook;\n };\n}\n","\"use client\";\n\nimport { create } from \"zustand\";\nimport type { ToolCallContentPartComponent } from \"../../types/ContentPartComponentTypes\";\n\nexport type AssistantToolUIsState = Readonly<{\n getToolUI: (toolName: string) => ToolCallContentPartComponent | null;\n setToolUI: (\n toolName: string,\n render: ToolCallContentPartComponent,\n ) => () => void;\n}>;\n\nexport const makeAssistantToolUIsStore = () =>\n create<AssistantToolUIsState>((set) => {\n const renderers = new Map<string, ToolCallContentPartComponent[]>();\n\n return Object.freeze({\n getToolUI: (name) => {\n const arr = renderers.get(name);\n const last = arr?.at(-1);\n if (last) return last;\n return null;\n },\n setToolUI: (name, render) => {\n let arr = renderers.get(name);\n if (!arr) {\n arr = [];\n renderers.set(name, arr);\n }\n arr.push(render);\n set({}); // notify the store listeners\n\n return () => {\n const index = arr.indexOf(render);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n if (index === arr.length) {\n set({}); // notify the store listeners\n }\n };\n },\n }) satisfies AssistantToolUIsState;\n });\n","import type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useInsertionEffect, useState } from \"react\";\nimport type { ReactThreadRuntime } from \"../../runtimes/core/ReactThreadRuntime\";\nimport type { ThreadContextValue } from \"../react/ThreadContext\";\nimport { ThreadContext } from \"../react/ThreadContext\";\nimport { makeThreadComposerStore } from \"../stores/ThreadComposer\";\nimport { getThreadStateFromRuntime, makeThreadStore } from \"../stores/Thread\";\nimport { makeThreadViewportStore } from \"../stores/ThreadViewport\";\nimport { makeThreadActionStore } from \"../stores/ThreadActions\";\nimport { makeThreadMessagesStore } from \"../stores/ThreadMessages\";\nimport { ThreadRuntimeWithSubscribe } from \"../../runtimes/core/AssistantRuntime\";\nimport { makeThreadRuntimeStore } from \"../stores/ThreadRuntime\";\nimport { subscribeToMainThread } from \"../../runtimes\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype ThreadProviderProps = {\n provider: ThreadRuntimeWithSubscribe;\n};\n\nexport const ThreadProvider: FC<PropsWithChildren<ThreadProviderProps>> = ({\n children,\n provider,\n}) => {\n const [context] = useState<ThreadContextValue>(() => {\n const useThreadRuntime = makeThreadRuntimeStore(provider.thread);\n const useThread = makeThreadStore(useThreadRuntime);\n const useThreadMessages = makeThreadMessagesStore(useThreadRuntime);\n const useThreadActions = makeThreadActionStore(useThreadRuntime);\n const useViewport = makeThreadViewportStore();\n const useComposer = makeThreadComposerStore(useThreadRuntime);\n\n return {\n useThread,\n useThreadRuntime,\n useThreadMessages,\n useThreadActions,\n useComposer,\n useViewport,\n };\n });\n\n // TODO it might make sense to move this into the make* functions\n useEffect(() => {\n const onThreadUpdate = () => {\n const thread = provider.thread;\n\n const oldState = context.useThread.getState();\n const state = getThreadStateFromRuntime(thread);\n if (\n oldState.threadId !== state.threadId ||\n oldState.isDisabled !== state.isDisabled ||\n oldState.isRunning !== state.isRunning ||\n // TODO ensure capabilities is memoized\n oldState.capabilities !== state.capabilities\n ) {\n writableStore(context.useThread).setState(state, true);\n }\n\n if (thread.messages !== context.useThreadMessages.getState()) {\n writableStore(context.useThreadMessages).setState(\n thread.messages,\n true,\n );\n }\n\n const composerState = context.useComposer.getState();\n if (\n thread.composer.isEmpty !== composerState.isEmpty ||\n thread.composer.text !== composerState.text ||\n thread.composer.attachmentAccept !== composerState.attachmentAccept ||\n thread.composer.attachments !== composerState.attachments ||\n state.capabilities.cancel !== composerState.canCancel\n ) {\n writableStore(context.useComposer).setState({\n isEmpty: thread.composer.isEmpty,\n text: thread.composer.text,\n attachmentAccept: thread.composer.attachmentAccept,\n attachments: thread.composer.attachments,\n canCancel: state.capabilities.cancel,\n });\n }\n };\n\n onThreadUpdate();\n return subscribeToMainThread(provider, onThreadUpdate);\n }, [provider, context]);\n\n useInsertionEffect(\n () =>\n provider.subscribe(() => {\n writableStore(context.useThreadRuntime).setState(provider.thread, true);\n }),\n [provider, context],\n );\n\n // subscribe to thread updates\n const Synchronizer = context.useThreadRuntime(\n (t) => (t as ReactThreadRuntime).unstable_synchronizer,\n );\n\n return (\n <ThreadContext.Provider value={context}>\n {Synchronizer && <Synchronizer />}\n {children}\n </ThreadContext.Provider>\n );\n};\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { ThreadComposerState } from \"../stores/ThreadComposer\";\nimport type { ThreadState } from \"../stores/Thread\";\nimport type { ThreadViewportState } from \"../stores/ThreadViewport\";\nimport { ThreadActionsState } from \"../stores/ThreadActions\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadMessagesState } from \"../stores/ThreadMessages\";\nimport { ThreadRuntimeStore } from \"../stores/ThreadRuntime\";\nimport { UseBoundStore } from \"zustand\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\n\nexport type ThreadContextValue = {\n useThread: UseBoundStore<ReadonlyStore<ThreadState>>;\n useThreadRuntime: UseBoundStore<ReadonlyStore<ThreadRuntimeStore>>;\n useThreadMessages: UseBoundStore<ReadonlyStore<ThreadMessagesState>>;\n useThreadActions: UseBoundStore<ReadonlyStore<ThreadActionsState>>;\n useComposer: UseBoundStore<ReadonlyStore<ThreadComposerState>>;\n useViewport: UseBoundStore<ReadonlyStore<ThreadViewportState>>;\n};\n\nexport const ThreadContext = createContext<ThreadContextValue | null>(null);\n\nexport const useThreadContext = createContextHook(\n ThreadContext,\n \"AssistantRuntimeProvider\",\n);\n\nexport const { useThreadRuntime, useThreadRuntimeStore } =\n createContextStoreHook(useThreadContext, \"useThreadRuntime\");\n\nexport const { useThread, useThreadStore } = createContextStoreHook(\n useThreadContext,\n \"useThread\",\n);\n\nexport const { useThreadMessages, useThreadMessagesStore } =\n createContextStoreHook(useThreadContext, \"useThreadMessages\");\n\nexport const { useThreadActions, useThreadActionsStore } =\n createContextStoreHook(useThreadContext, \"useThreadActions\");\n\nexport const {\n useComposer: useThreadComposer,\n useComposerStore: useThreadComposerStore,\n} = createContextStoreHook(useThreadContext, \"useComposer\");\n\nexport const {\n useViewport: useThreadViewport,\n useViewportStore: useThreadViewportStore,\n} = createContextStoreHook(useThreadContext, \"useViewport\");\n","import { create, UseBoundStore } from \"zustand\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { Unsubscribe } from \"../../types/Unsubscribe\";\nimport { ThreadContextValue } from \"../react\";\nimport { ThreadComposerAttachment } from \"./Attachment\";\n\nexport type ThreadComposerState = Readonly<{\n type: \"thread\";\n\n /** @deprecated Use `text` instead. */\n value: string;\n /** @deprecated Use `setText` instead. */\n setValue: (value: string) => void;\n\n attachmentAccept: string;\n\n attachments: readonly ThreadComposerAttachment[];\n addAttachment: (file: File) => void;\n removeAttachment: (attachmentId: string) => void;\n\n text: string;\n setText: (value: string) => void;\n\n reset: () => void;\n\n canCancel: boolean;\n isEditing: true;\n isEmpty: boolean;\n\n send: () => void;\n cancel: () => void;\n focus: () => void;\n onFocus: (listener: () => void) => Unsubscribe;\n}>;\n\nexport const makeThreadComposerStore = (\n useThreadRuntime: ThreadContextValue[\"useThreadRuntime\"],\n): UseBoundStore<ReadonlyStore<ThreadComposerState>> => {\n const focusListeners = new Set<() => void>();\n return create<ThreadComposerState>()((_, get) => {\n const runtime = useThreadRuntime.getState();\n return {\n type: \"thread\",\n\n get value() {\n return get().text;\n },\n setValue(value) {\n get().setText(value);\n },\n\n attachmentAccept: runtime.composer.attachmentAccept,\n\n attachments: runtime.composer.attachments,\n addAttachment: (file) => {\n useThreadRuntime.getState().composer.addAttachment(file);\n },\n removeAttachment: (attachmentId) => {\n useThreadRuntime.getState().composer.removeAttachment(attachmentId);\n },\n reset: () => {\n useThreadRuntime.getState().composer.reset();\n },\n\n text: runtime.composer.text,\n setText: (text) => {\n useThreadRuntime.getState().composer.setText(text);\n },\n\n canCancel: runtime.capabilities.cancel,\n isEditing: true,\n isEmpty: runtime.composer.isEmpty,\n\n send: () => {\n const runtime = useThreadRuntime.getState();\n runtime.composer.send();\n },\n cancel: () => {\n useThreadRuntime.getState().cancelRun();\n },\n focus: () => {\n for (const listener of focusListeners) {\n listener();\n }\n },\n onFocus: (listener) => {\n focusListeners.add(listener);\n return () => {\n focusListeners.delete(listener);\n };\n },\n };\n });\n};\n","import { create } from \"zustand\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadRuntimeStore } from \"./ThreadRuntime\";\n\nexport type ThreadState = Readonly<{\n capabilities: Readonly<RuntimeCapabilities>;\n threadId: string;\n isRunning: boolean;\n isDisabled: boolean;\n}>;\n\nexport type RuntimeCapabilities = {\n switchToBranch: boolean;\n edit: boolean;\n reload: boolean;\n cancel: boolean;\n unstable_copy: boolean;\n speak: boolean;\n attachments: boolean;\n};\n\nexport const getThreadStateFromRuntime = (\n runtime: ThreadRuntimeStore,\n): ThreadState => {\n const lastMessage = runtime.messages.at(-1);\n return Object.freeze({\n threadId: runtime.threadId,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isRunning:\n lastMessage?.role !== \"assistant\"\n ? false\n : lastMessage.status.type === \"running\",\n });\n};\n\nexport const makeThreadStore = (\n runtimeRef: ReadonlyStore<ThreadRuntimeStore>,\n) => {\n const runtime = runtimeRef.getState();\n return create<ThreadState>(() => getThreadStateFromRuntime(runtime));\n};\n","\"use client\";\nimport { create } from \"zustand\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\n\nexport type ThreadViewportState = Readonly<{\n isAtBottom: boolean;\n scrollToBottom: () => void;\n onScrollToBottom: (callback: () => void) => Unsubscribe;\n}>;\n\nexport const makeThreadViewportStore = () => {\n const scrollToBottomListeners = new Set<() => void>();\n\n return create<ThreadViewportState>(() => ({\n isAtBottom: true,\n scrollToBottom: () => {\n for (const listener of scrollToBottomListeners) {\n listener();\n }\n },\n onScrollToBottom: (callback) => {\n scrollToBottomListeners.add(callback);\n return () => {\n scrollToBottomListeners.delete(callback);\n };\n },\n }));\n};\n","import { create } from \"zustand\";\nimport type { AppendMessage } from \"../../types/AssistantTypes\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadRuntimeStore } from \"./ThreadRuntime\";\nimport { SpeechSynthesisAdapter } from \"../../runtimes/speech/SpeechAdapterTypes\";\n\nexport type AddToolResultOptions = {\n messageId: string;\n toolName: string;\n toolCallId: string;\n result: any;\n};\n\nexport type ThreadActionsState = Readonly<{\n getBranches: (messageId: string) => readonly string[];\n switchToBranch: (branchId: string) => void;\n\n append: (message: AppendMessage) => void;\n startRun: (parentId: string | null) => void;\n cancelRun: () => void;\n\n addToolResult: (options: AddToolResultOptions) => void;\n\n speak: (messageId: string) => SpeechSynthesisAdapter.Utterance;\n}>;\n\nexport const makeThreadActionStore = (\n runtimeStore: ReadonlyStore<ThreadRuntimeStore>,\n) => {\n return create<ThreadActionsState>(() =>\n Object.freeze({\n getBranches: (messageId) =>\n runtimeStore.getState().getBranches(messageId),\n switchToBranch: (branchId) =>\n runtimeStore.getState().switchToBranch(branchId),\n\n startRun: (parentId) => runtimeStore.getState().startRun(parentId),\n append: (message) => runtimeStore.getState().append(message),\n cancelRun: () => runtimeStore.getState().cancelRun(),\n\n addToolResult: (options) =>\n runtimeStore.getState().addToolResult(options),\n\n speak: (messageId) => runtimeStore.getState().speak(messageId),\n }),\n );\n};\n","import { create } from \"zustand\";\nimport type { ThreadMessage } from \"../../types/AssistantTypes\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadRuntimeStore } from \"./ThreadRuntime\";\n\nexport type ThreadMessagesState = readonly ThreadMessage[];\n\nexport const makeThreadMessagesStore = (\n runtimeRef: ReadonlyStore<ThreadRuntimeStore>,\n) => {\n return create<ThreadMessagesState>(() => runtimeRef.getState().messages);\n};\n","import { create } from \"zustand\";\nimport { ThreadRuntime } from \"../../runtimes\";\n\nexport type ThreadRuntimeStore = ThreadRuntime;\n\nexport const makeThreadRuntimeStore = (runtime: ThreadRuntime) => {\n return create<ThreadRuntimeStore>(() => runtime);\n};\n","import { Unsubscribe } from \"../../types\";\nimport { ThreadRuntimeWithSubscribe } from \"./AssistantRuntime\";\n\nexport const subscribeToMainThread = (\n runtime: ThreadRuntimeWithSubscribe,\n callback: () => void,\n) => {\n let first = true;\n let cleanup: Unsubscribe | undefined;\n const inner = () => {\n cleanup?.();\n cleanup = runtime.thread.subscribe(callback);\n\n if (!first) {\n callback();\n }\n first = false;\n };\n\n const unsubscribe = runtime.subscribe(inner);\n inner();\n\n return () => {\n unsubscribe();\n cleanup?.();\n };\n};\n","\"use client\";\n\nimport { useInsertionEffect, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntime } from \"./LocalRuntime\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\n\nexport const useLocalRuntime = (\n adapter: ChatModelAdapter,\n options: LocalRuntimeOptions = {},\n) => {\n const [runtime] = useState(() => new LocalRuntime(adapter, options));\n\n useInsertionEffect(() => {\n runtime.adapter = adapter;\n runtime.options = options;\n });\n\n return runtime;\n};\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport type { AssistantRuntime } from \"./AssistantRuntime\";\nimport { ReactThreadRuntime } from \"./ReactThreadRuntime\";\n\nexport abstract class BaseAssistantRuntime<\n TThreadRuntime extends ReactThreadRuntime,\n> implements AssistantRuntime\n{\n constructor(private _thread: TThreadRuntime) {\n this._thread = _thread;\n }\n\n get thread() {\n return this._thread;\n }\n\n set thread(thread: TThreadRuntime) {\n this._thread = thread;\n this.subscriptionHandler();\n }\n\n public abstract switchToNewThread(): void;\n\n public abstract registerModelConfigProvider(\n provider: ModelConfigProvider,\n ): Unsubscribe;\n public abstract switchToThread(threadId: string | null): void;\n\n private _subscriptions = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private subscriptionHandler = () => {\n for (const callback of this._subscriptions) callback();\n };\n}\n","export { ThreadRuntimeComposer } from \"./runtimes/utils/ThreadRuntimeComposer\";\nexport { ProxyConfigProvider } from \"./utils/ProxyConfigProvider\";\nexport { MessageRepository } from \"./runtimes/utils/MessageRepository\";\nexport { BaseAssistantRuntime } from \"./runtimes/core/BaseAssistantRuntime\";\nexport * from \"./utils/smooth\";\nexport { TooltipIconButton } from \"./ui/base/tooltip-icon-button\";\nexport { generateId } from \"./utils/idUtils\";\n","import { ThreadComposerAttachment } from \"../../context/stores/Attachment\";\nimport { AppendMessage } from \"../../types\";\nimport { AttachmentAdapter } from \"../attachment/AttachmentAdapter\";\nimport { ThreadRuntime } from \"../core\";\n\nexport class ThreadRuntimeComposer implements ThreadRuntime.Composer {\n private _attachmentAdapter?: AttachmentAdapter | undefined;\n\n public attachmentAccept: string = \"*\";\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\n }\n\n constructor(\n private runtime: {\n messages: ThreadRuntime[\"messages\"];\n append: (message: AppendMessage) => void;\n },\n private notifySubscribers: () => void,\n ) {}\n\n public setAttachmentAdapter(adapter: AttachmentAdapter | undefined) {\n this._attachmentAdapter = adapter;\n const accept = adapter?.accept ?? \"*\";\n if (this.attachmentAccept !== accept) {\n this.attachmentAccept = accept;\n return true;\n }\n return false;\n }\n\n private _attachments: ThreadComposerAttachment[] = [];\n\n public get attachments() {\n return this._attachments;\n }\n\n async addAttachment(file: File) {\n if (!this._attachmentAdapter)\n throw new Error(\"Attachments are not supported\");\n\n const attachment = await this._attachmentAdapter.add({ file });\n\n this._attachments = [...this._attachments, attachment];\n this.notifySubscribers();\n }\n\n async removeAttachment(attachmentId: string) {\n if (!this._attachmentAdapter)\n throw new Error(\"Attachments are not supported\");\n\n const index = this._attachments.findIndex((a) => a.id === attachmentId);\n if (index === -1) throw new Error(\"Attachment not found\");\n const attachment = this._attachments[index]!;\n\n await this._attachmentAdapter.remove(attachment);\n\n this._attachments = this._attachments.toSpliced(index, 1);\n this.notifySubscribers();\n }\n\n private _text = \"\";\n\n get text() {\n return this._text;\n }\n\n setText(value: string) {\n this._text = value;\n this.notifySubscribers();\n }\n\n reset() {\n this._text = \"\";\n this._attachments = [];\n this.notifySubscribers();\n }\n\n public async send() {\n const attachments = this._attachmentAdapter\n ? await Promise.all(\n this.attachments.map(\n async (a) => await this._attachmentAdapter!.send(a),\n ),\n )\n : [];\n\n this.runtime.append({\n parentId: this.runtime.messages.at(-1)?.id ?? null,\n role: \"user\",\n content: this.text ? [{ type: \"text\", text: this.text }] : [],\n attachments,\n });\n this.reset();\n }\n}\n","\"use client\";\nimport {\n type ModelConfigProvider,\n mergeModelConfigs,\n} from \"../types/ModelConfigTypes\";\n\nexport class ProxyConfigProvider implements ModelConfigProvider {\n private _providers = new Set<ModelConfigProvider>();\n\n getModelConfig() {\n return mergeModelConfigs(this._providers);\n }\n\n registerModelConfigProvider(provider: ModelConfigProvider) {\n this._providers.add(provider);\n return () => {\n this._providers.delete(provider);\n };\n }\n}\n","import { customAlphabet } from \"nanoid/non-secure\";\n\nexport const generateId = customAlphabet(\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n 7,\n);\n\nconst optimisticPrefix = \"__optimistic__\";\nexport const generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;\nexport const isOptimisticId = (id: string) => id.startsWith(optimisticPrefix);\n","import { MessageAttachment } from \"../../../context/stores/Attachment\";\nimport { generateId } from \"../../../internal\";\nimport {\n ThreadMessage,\n CoreMessage,\n ToolCallContentPart,\n MessageStatus,\n} from \"../../../types\";\n\nexport const fromCoreMessages = (\n message: readonly CoreMessage[],\n): ThreadMessage[] => {\n return message.map((message) => fromCoreMessage(message));\n};\n\nexport const fromCoreMessage = (\n message: CoreMessage,\n {\n id = generateId(),\n status = { type: \"complete\", reason: \"unknown\" } as MessageStatus,\n attachments = [] as readonly MessageAttachment[],\n } = {},\n): ThreadMessage => {\n const commonProps = {\n id,\n createdAt: new Date(),\n };\n\n const role = message.role;\n switch (role) {\n case \"assistant\":\n return {\n ...commonProps,\n role,\n content: message.content.map((part) => {\n if (part.type === \"tool-call\") {\n return {\n ...part,\n argsText: JSON.stringify(part.args),\n } satisfies ToolCallContentPart;\n }\n return part;\n }),\n status,\n } satisfies ThreadMessage;\n\n case \"user\":\n return {\n ...commonProps,\n role,\n content: message.content,\n attachments,\n } satisfies ThreadMessage;\n\n case \"system\":\n return {\n ...commonProps,\n role,\n content: message.content,\n } satisfies ThreadMessage;\n\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n};\n","import type { CoreMessage, ThreadMessage } from \"../../types/AssistantTypes\";\nimport { generateOptimisticId } from \"../../utils/idUtils\";\nimport { fromCoreMessage } from \"../edge/converters/fromCoreMessage\";\n\ntype RepositoryParent = {\n children: string[];\n next: RepositoryMessage | null;\n};\n\ntype RepositoryMessage = RepositoryParent & {\n prev: RepositoryMessage | null;\n current: ThreadMessage;\n level: number;\n};\n\nexport interface ExportedMessageRepository {\n headId?: string | null;\n messages: Array<{\n message: ThreadMessage;\n parentId: string | null;\n }>;\n}\n\nconst findHead = (\n message: RepositoryMessage | RepositoryParent,\n): RepositoryMessage | null => {\n if (message.next) return findHead(message.next);\n if (\"current\" in message) return message;\n return null;\n};\n\nexport class MessageRepository {\n private messages = new Map<string, RepositoryMessage>(); // message_id -> item\n private head: RepositoryMessage | null = null;\n private root: RepositoryParent = {\n children: [],\n next: null,\n };\n\n private performOp(\n newParent: RepositoryMessage | null,\n child: RepositoryMessage,\n operation: \"cut\" | \"link\" | \"relink\",\n ) {\n const parentOrRoot = child.prev ?? this.root;\n const newParentOrRoot = newParent ?? this.root;\n\n if (operation === \"relink\" && parentOrRoot === newParentOrRoot) return;\n\n // cut\n if (operation !== \"link\") {\n // remove from parentOrRoot.children\n parentOrRoot.children = parentOrRoot.children.filter(\n (m) => m !== child.current.id,\n );\n\n // update parentOrRoot.next\n if (parentOrRoot.next === child) {\n const fallbackId = parentOrRoot.children.at(-1);\n const fallback = fallbackId ? this.messages.get(fallbackId) : null;\n if (fallback === undefined) {\n throw new Error(\n \"MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.\",\n );\n }\n parentOrRoot.next = fallback;\n }\n }\n\n // link\n if (operation !== \"cut\") {\n // ensure the child is not part of parent tree\n for (\n let current: RepositoryMessage | null = newParent;\n current;\n current = current.prev\n ) {\n if (current.current.id === child.current.id) {\n throw new Error(\n \"MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.\",\n );\n }\n }\n\n // add to parentOrRoot.children\n newParentOrRoot.children = [\n ...newParentOrRoot.children,\n child.current.id,\n ];\n\n // update parentOrRoot.next\n if (findHead(child) === this.head || newParentOrRoot.next === null) {\n newParentOrRoot.next = child;\n }\n\n child.prev = newParent;\n }\n }\n getMessages() {\n const messages = new Array<ThreadMessage>(this.head?.level ?? 0);\n for (let current = this.head; current; current = current.prev) {\n messages[current.level] = current.current;\n }\n return messages;\n }\n\n addOrUpdateMessage(parentId: string | null, message: ThreadMessage) {\n const existingItem = this.messages.get(message.id);\n const prev = parentId ? this.messages.get(parentId) : null;\n if (prev === undefined)\n throw new Error(\n \"MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n // update existing message\n if (existingItem) {\n existingItem.current = message;\n this.performOp(prev, existingItem, \"relink\");\n return;\n }\n\n // create a new message\n const newItem: RepositoryMessage = {\n prev,\n current: message,\n next: null,\n children: [],\n level: prev ? prev.level + 1 : 0,\n };\n\n this.messages.set(message.id, newItem);\n this.performOp(prev, newItem, \"link\");\n\n if (this.head === prev) {\n this.head = newItem;\n }\n }\n\n getMessage(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n return {\n parentId: message.prev?.current.id ?? null,\n message: message.current,\n };\n }\n\n appendOptimisticMessage(parentId: string | null, message: CoreMessage) {\n let optimisticId: string;\n do {\n optimisticId = generateOptimisticId();\n } while (this.messages.has(optimisticId));\n\n this.addOrUpdateMessage(\n parentId,\n fromCoreMessage(message, {\n id: optimisticId,\n status: { type: \"running\" },\n }),\n );\n\n return optimisticId;\n }\n\n deleteMessage(messageId: string, replacementId?: string | null | undefined) {\n const message = this.messages.get(messageId);\n\n if (!message)\n throw new Error(\n \"MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const replacement =\n replacementId === undefined\n ? message.prev // if no replacementId is provided, use the parent\n : replacementId === null\n ? null\n : this.messages.get(replacementId);\n if (replacement === undefined)\n throw new Error(\n \"MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.\",\n );\n\n for (const child of message.children) {\n const childMessage = this.messages.get(child);\n if (!childMessage)\n throw new Error(\n \"MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.\",\n );\n this.performOp(replacement, childMessage, \"relink\");\n }\n\n this.performOp(null, message, \"cut\");\n this.messages.delete(messageId);\n\n if (this.head === message) {\n this.head = findHead(replacement ?? this.root);\n }\n }\n\n getBranches(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const { children } = message.prev ?? this.root;\n return children;\n }\n\n switchToBranch(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const prevOrRoot = message.prev ?? this.root;\n prevOrRoot.next = message;\n\n this.head = findHead(message);\n }\n\n resetHead(messageId: string | null) {\n if (messageId === null) {\n this.head = null;\n return;\n }\n\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.\",\n );\n\n this.head = message;\n for (\n let current: RepositoryMessage | null = message;\n current;\n current = current.prev\n ) {\n if (current.prev) {\n current.prev.next = current;\n }\n }\n }\n\n export(): ExportedMessageRepository {\n const exportItems: ExportedMessageRepository[\"messages\"] = [];\n\n // hint: we are relying on the insertion order of the messages\n // this is important for the import function to properly link the messages\n for (const [, message] of this.messages) {\n exportItems.push({\n message: message.current,\n parentId: message.prev?.current.id ?? null,\n });\n }\n\n return {\n headId: this.head?.current.id ?? null,\n messages: exportItems,\n };\n }\n\n import({ headId, messages }: ExportedMessageRepository) {\n for (const { message, parentId } of messages) {\n this.addOrUpdateMessage(parentId, message);\n }\n\n // switch to the saved head id if it is not the most recent message\n this.resetHead(headId ?? messages.at(-1)?.message.id ?? null);\n }\n}\n","\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useMessage } from \"../../context\";\nimport { ContentPartStatus } from \"../../types/AssistantTypes\";\nimport { TextContentPartState } from \"../../context/stores/ContentPart\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useSmoothStatusStore } from \"./SmoothContext\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\n\nclass TextStreamAnimator {\n private animationFrameId: number | null = null;\n private lastUpdateTime: number = Date.now();\n\n public targetText: string = \"\";\n\n constructor(\n public currentText: string,\n private setText: (newText: string) => void,\n ) {}\n\n start() {\n if (this.animationFrameId !== null) return;\n this.lastUpdateTime = Date.now();\n this.animate();\n }\n\n stop() {\n if (this.animationFrameId !== null) {\n cancelAnimationFrame(this.animationFrameId);\n this.animationFrameId = null;\n }\n }\n\n private animate = () => {\n const currentTime = Date.now();\n const deltaTime = currentTime - this.lastUpdateTime;\n let timeToConsume = deltaTime;\n\n const remainingChars = this.targetText.length - this.currentText.length;\n const baseTimePerChar = Math.min(5, 250 / remainingChars);\n\n let charsToAdd = 0;\n while (timeToConsume >= baseTimePerChar && charsToAdd < remainingChars) {\n charsToAdd++;\n timeToConsume -= baseTimePerChar;\n }\n\n if (charsToAdd !== remainingChars) {\n this.animationFrameId = requestAnimationFrame(this.animate);\n } else {\n this.animationFrameId = null;\n }\n if (charsToAdd === 0) return;\n\n this.currentText = this.targetText.slice(\n 0,\n this.currentText.length + charsToAdd,\n );\n this.lastUpdateTime = currentTime - timeToConsume;\n this.setText(this.currentText);\n };\n}\n\nconst SMOOTH_STATUS: ContentPartStatus = Object.freeze({\n type: \"running\",\n});\n\nexport const useSmooth = (\n state: TextContentPartState,\n smooth: boolean = false,\n): TextContentPartState => {\n const {\n part: { text },\n } = state;\n const id = useMessage({\n optional: true,\n selector: (m: { message: { id: string } }) => m.message.id,\n });\n\n const idRef = useRef(id);\n const [displayedText, setDisplayedText] = useState(text);\n\n const smoothStatusStore = useSmoothStatusStore({ optional: true });\n const setText = useCallbackRef((text: string) => {\n setDisplayedText(text);\n if (smoothStatusStore) {\n writableStore(smoothStatusStore).setState(\n text !== state.part.text ? SMOOTH_STATUS : state.status,\n );\n }\n });\n\n // TODO this is hacky\n useEffect(() => {\n if (smoothStatusStore) {\n writableStore(smoothStatusStore).setState(\n text !== state.part.text ? SMOOTH_STATUS : state.status,\n );\n }\n }, [smoothStatusStore, text, displayedText, state.status, state.part.text]);\n\n const [animatorRef] = useState<TextStreamAnimator>(\n new TextStreamAnimator(text, setText),\n );\n\n useEffect(() => {\n if (!smooth) {\n animatorRef.stop();\n return;\n }\n\n if (idRef.current !== id || !text.startsWith(animatorRef.targetText)) {\n idRef.current = id;\n setText(text);\n\n animatorRef.currentText = text;\n animatorRef.targetText = text;\n animatorRef.stop();\n\n return;\n }\n\n animatorRef.targetText = text;\n animatorRef.start();\n }, [setText, animatorRef, id, smooth, text]);\n\n useEffect(() => {\n return () => {\n animatorRef.stop();\n };\n }, [animatorRef]);\n\n return useMemo(\n () =>\n smooth\n ? {\n part: { type: \"text\", text: displayedText },\n status: text === displayedText ? state.status : SMOOTH_STATUS,\n }\n : state,\n [smooth, displayedText, state, text],\n );\n};\n","import {\n createContext,\n FC,\n forwardRef,\n PropsWithChildren,\n useContext,\n useState,\n} from \"react\";\nimport { ReadonlyStore } from \"../../context/ReadonlyStore\";\nimport { create, UseBoundStore } from \"zustand\";\nimport {\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../../types/AssistantTypes\";\nimport { useContentPartStore } from \"../../context/react/ContentPartContext\";\nimport { createContextStoreHook } from \"../../context/react/utils/createContextStoreHook\";\n\ntype SmoothContextValue = {\n useSmoothStatus: UseBoundStore<\n ReadonlyStore<ContentPartStatus | ToolCallContentPartStatus>\n >;\n};\n\nconst SmoothContext = createContext<SmoothContextValue | null>(null);\n\nconst makeSmoothContext = (\n initialState: ContentPartStatus | ToolCallContentPartStatus,\n) => {\n const useSmoothStatus = create(() => initialState);\n return { useSmoothStatus };\n};\n\nexport const SmoothContextProvider: FC<PropsWithChildren> = ({ children }) => {\n const outer = useSmoothContext({ optional: true });\n const contentPartStore = useContentPartStore();\n\n const [context] = useState(() =>\n makeSmoothContext(contentPartStore.getState().status),\n );\n\n // do not wrap if there is an outer SmoothContextProvider\n if (outer) return children;\n\n return (\n <SmoothContext.Provider value={context}>{children}</SmoothContext.Provider>\n );\n};\n\nexport const withSmoothContextProvider = <C extends React.ComponentType<any>>(\n Component: C,\n): C => {\n const Wrapped = forwardRef((props, ref) => {\n return (\n <SmoothContextProvider>\n <Component {...(props as any)} ref={ref} />\n </SmoothContextProvider>\n );\n });\n Wrapped.displayName = Component.displayName;\n return Wrapped as any;\n};\n\nfunction useSmoothContext(options?: {\n optional?: false | undefined;\n}): SmoothContextValue;\nfunction useSmoothContext(options?: {\n optional?: boolean | undefined;\n}): SmoothContextValue | null;\nfunction useSmoothContext(options?: { optional?: boolean | undefined }) {\n const context = useContext(SmoothContext);\n if (!options?.optional && !context)\n throw new Error(\n \"This component must be used within a SmoothContextProvider.\",\n );\n return context;\n}\n\nexport const { useSmoothStatus, useSmoothStatusStore } = createContextStoreHook(\n useSmoothContext,\n \"useSmoothStatus\",\n);\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { ContentPartState } from \"../stores/ContentPart\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type ContentPartContextValue = {\n useContentPart: UseBoundStore<ReadonlyStore<ContentPartState>>;\n};\n\nexport const ContentPartContext = createContext<ContentPartContextValue | null>(\n null,\n);\n\nexport const useContentPartContext = createContextHook(\n ContentPartContext,\n \"a component passed to <MessagePrimitive.Content components={...}>\",\n);\n\nexport const { useContentPart, useContentPartStore } = createContextStoreHook(\n useContentPartContext,\n \"useContentPart\",\n);\n","import type { StoreApi } from \"zustand\";\n\nexport type ReadonlyStore<T> = Omit<StoreApi<T>, \"setState\" | \"destroy\">;\n\nexport const writableStore = <T>(store: ReadonlyStore<T> | undefined) => {\n return store as unknown as StoreApi<T>;\n};\n","\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"./tooltip\";\nimport { Button, ButtonProps } from \"./button\";\n\nexport type TooltipIconButtonProps = ButtonProps & {\n tooltip: string;\n side?: \"top\" | \"bottom\" | \"left\" | \"right\";\n};\n\nexport const TooltipIconButton = forwardRef<\n HTMLButtonElement,\n TooltipIconButtonProps\n>(({ children, tooltip, side = \"bottom\", ...rest }, ref) => {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button variant=\"ghost\" size=\"icon\" {...rest} ref={ref}>\n {children}\n <span className=\"aui-sr-only\">{tooltip}</span>\n </Button>\n </TooltipTrigger>\n <TooltipContent side={side}>{tooltip}</TooltipContent>\n </Tooltip>\n );\n});\n\nTooltipIconButton.displayName = \"TooltipIconButton\";\n","\"use client\";\n\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\";\nimport { withDefaults } from \"../utils/withDefaults\";\nimport { FC } from \"react\";\n\nexport const Tooltip: FC<TooltipPrimitive.TooltipProps> = (props) => {\n return (\n <TooltipPrimitive.Provider>\n <TooltipPrimitive.Root {...props} />\n </TooltipPrimitive.Provider>\n );\n};\n\nTooltip.displayName = \"Tooltip\";\n\nexport const TooltipTrigger = TooltipPrimitive.Trigger;\n\nexport const TooltipContent = withDefaults(TooltipPrimitive.Content, {\n sideOffset: 4,\n className: \"aui-tooltip-content\",\n});\n\nTooltipContent.displayName = \"TooltipContent\";\n","import {\n ComponentPropsWithoutRef,\n ElementRef,\n ElementType,\n forwardRef,\n} from \"react\";\nimport classNames from \"classnames\";\n\nexport const withDefaultProps =\n <TProps extends { className?: string }>({\n className,\n ...defaultProps\n }: Partial<TProps>) =>\n ({ className: classNameProp, ...props }: TProps) => {\n return {\n className: classNames(className, classNameProp),\n ...defaultProps,\n ...props,\n } as TProps;\n };\n\nexport const withDefaults = <TComponent extends ElementType>(\n Component: TComponent,\n defaultProps: Partial<ComponentPropsWithoutRef<TComponent>>,\n) => {\n type TComponentProps = typeof defaultProps;\n const getProps = withDefaultProps<TComponentProps>(defaultProps);\n const WithDefaults = forwardRef<ElementRef<TComponent>, TComponentProps>(\n (props, ref) => {\n const ComponentAsAny = Component as any;\n return <ComponentAsAny {...getProps(props as any)} ref={ref} />;\n },\n );\n WithDefaults.displayName =\n \"withDefaults(\" +\n (typeof Component === \"string\" ? Component : Component.displayName) +\n \")\";\n return WithDefaults;\n};\n","import { cva, type VariantProps } from \"class-variance-authority\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { ElementRef, forwardRef } from \"react\";\n\nconst buttonVariants = cva(\"aui-button\", {\n variants: {\n variant: {\n default: \"aui-button-primary\",\n outline: \"aui-button-outline\",\n ghost: \"aui-button-ghost\",\n },\n size: {\n default: \"aui-button-medium\",\n icon: \"aui-button-icon\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n});\n\ntype ButtonElement = ElementRef<typeof Primitive.button>;\n\nexport type ButtonProps = React.ComponentPropsWithoutRef<\n typeof Primitive.button\n> &\n VariantProps<typeof buttonVariants>;\n\nconst Button = forwardRef<ButtonElement, ButtonProps>(\n ({ className, variant, size, ...props }, ref) => {\n return (\n <Primitive.button\n className={buttonVariants({ variant, size, className })}\n {...props}\n ref={ref}\n />\n );\n },\n);\n\nButton.displayName = \"Button\";\n\nexport { Button, buttonVariants };\n","import { LanguageModelV1Message } from \"@ai-sdk/provider\";\nimport { CoreMessage, ToolCallContentPart } from \"../../../types\";\n\ntype fromLanguageModelMessagesOptions = {\n mergeRoundtrips: boolean;\n};\n\nexport const fromLanguageModelMessages = (\n lm: LanguageModelV1Message[],\n { mergeRoundtrips }: fromLanguageModelMessagesOptions,\n): CoreMessage[] => {\n const messages: CoreMessage[] = [];\n\n for (const lmMessage of lm) {\n const role = lmMessage.role;\n switch (role) {\n case \"system\": {\n messages.push({\n role: \"system\",\n content: [\n {\n type: \"text\",\n text: lmMessage.content,\n },\n ],\n });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: lmMessage.content.map((part) => {\n const type = part.type;\n switch (type) {\n case \"text\": {\n return {\n type: \"text\",\n text: part.text,\n };\n }\n case \"image\": {\n if (part.image instanceof URL) {\n return {\n type: \"image\",\n image: part.image.href,\n };\n }\n throw new Error(\"Only images with URL data are supported\");\n }\n default: {\n const unhandledType: never = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n }\n }),\n });\n break;\n }\n case \"assistant\": {\n const newContent = lmMessage.content.map((part) => {\n if (part.type === \"tool-call\") {\n return {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n argsText: JSON.stringify(part.args),\n args: part.args as Record<string, unknown>,\n } satisfies ToolCallContentPart;\n }\n return part;\n });\n\n if (mergeRoundtrips) {\n const previousMessage = messages[messages.length - 1];\n if (previousMessage?.role === \"assistant\") {\n previousMessage.content.push(...newContent);\n break;\n }\n }\n\n messages.push({\n role: \"assistant\",\n content: newContent,\n });\n break;\n }\n case \"tool\": {\n const previousMessage = messages[messages.length - 1];\n if (previousMessage?.role !== \"assistant\")\n throw new Error(\n \"A tool message must be preceded by an assistant message.\",\n );\n\n for (const tool of lmMessage.content) {\n const toolCall = previousMessage.content.find(\n (c): c is ToolCallContentPart =>\n c.type === \"tool-call\" && c.toolCallId === tool.toolCallId,\n );\n if (!toolCall)\n throw new Error(\"Received tool result for an unknown tool call.\");\n if (toolCall.toolName !== tool.toolName)\n throw new Error(\"Tool call name mismatch.\");\n\n toolCall.result = tool.result;\n if (tool.isError) {\n toolCall.isError = true;\n }\n }\n\n break;\n }\n\n default: {\n const unhandledRole: never = role;\n throw new Error(`Unknown message role: ${unhandledRole}`);\n }\n }\n }\n\n return messages;\n};\n","import { LanguageModelV1FunctionTool } from \"@ai-sdk/provider\";\nimport { Tool } from \"../../../types/ModelConfigTypes\";\n\nexport const fromLanguageModelTools = (\n tools: LanguageModelV1FunctionTool[],\n): Record<string, Tool<any, any>> => {\n return Object.fromEntries(\n tools.map((tool) => [\n tool.name,\n {\n description: tool.description,\n parameters: tool.parameters,\n },\n ]),\n );\n};\n","export function chunkByLineStream() {\n let buffer = \"\";\n\n return new TransformStream({\n transform(chunk, controller) {\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n\n // Process all complete lines\n for (let i = 0; i < lines.length - 1; i++) {\n controller.enqueue(lines[i]);\n }\n\n // Keep the last incomplete line in the buffer\n buffer = lines[lines.length - 1]!;\n },\n flush(controller) {\n // flush any remaining content in the buffer\n if (buffer) {\n controller.enqueue(buffer);\n }\n },\n });\n}\n","import { chunkByLineStream } from \"./chunkByLineStream\";\nimport { PipeableTransformStream } from \"./PipeableTransformStream\";\nimport { StreamPart } from \"./StreamPart\";\n\nconst decodeStreamPart = <T extends Record<string, unknown>>(\n part: string,\n): StreamPart<T> => {\n const index = part.indexOf(\":\");\n if (index === -1) throw new Error(\"Invalid stream part\");\n return {\n type: part.slice(0, index),\n value: JSON.parse(part.slice(index + 1)),\n };\n};\n\nexport function streamPartDecoderStream<T extends Record<string, unknown>>() {\n const decodeStream = new TransformStream<string, StreamPart<T>>({\n transform(chunk, controller) {\n controller.enqueue(decodeStreamPart<T>(chunk));\n },\n });\n\n return new PipeableTransformStream((readable) => {\n return readable\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(chunkByLineStream())\n .pipeThrough(decodeStream);\n });\n}\n","import { streamPartDecoderStream } from \"./streamPartDecoderStream\";\nimport { streamPartEncoderStream } from \"./streamPartEncoderStream\";\nimport { StreamPart } from \"./StreamPart\";\n\nexport declare namespace StreamUtils {\n export { StreamPart };\n}\n\nexport const streamUtils = {\n streamPartEncoderStream,\n streamPartDecoderStream,\n};\n","import { LocalRuntimeOptions, useLocalRuntime } from \"..\";\nimport { useState } from \"react\";\nimport { EdgeChatAdapterOptions, EdgeChatAdapter } from \"./EdgeChatAdapter\";\n\nexport type EdgeRuntimeOptions = EdgeChatAdapterOptions & LocalRuntimeOptions;\n\nexport const useEdgeRuntime = ({\n initialMessages,\n maxToolRoundtrips,\n adapters,\n ...options\n}: EdgeRuntimeOptions) => {\n const [adapter] = useState(() => new EdgeChatAdapter(options));\n return useLocalRuntime(adapter, {\n initialMessages,\n maxToolRoundtrips,\n adapters,\n });\n};\n","import {\n AssistantStreamChunk,\n AssistantStreamChunkType,\n} from \"./AssistantStreamChunkType\";\nimport { StreamPart } from \"./utils/StreamPart\";\nimport { ToolResultStreamPart } from \"./toolResultStream\";\n\nexport function assistantDecoderStream() {\n const toolCallNames = new Map<string, string>();\n let currentToolCall:\n | { id: string; name: string; argsText: string }\n | undefined;\n\n return new TransformStream<\n StreamPart<AssistantStreamChunk>,\n ToolResultStreamPart\n >({\n transform({ type, value }, controller) {\n if (\n currentToolCall &&\n type !== AssistantStreamChunkType.ToolCallArgsTextDelta &&\n type !== AssistantStreamChunkType.Error\n ) {\n controller.enqueue({\n type: \"tool-call\",\n toolCallType: \"function\",\n toolCallId: currentToolCall.id,\n toolName: currentToolCall.name,\n args: currentToolCall.argsText,\n });\n currentToolCall = undefined;\n }\n\n switch (type) {\n case AssistantStreamChunkType.TextDelta: {\n controller.enqueue({\n type: \"text-delta\",\n textDelta: value,\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallBegin: {\n const { id, name } = value;\n toolCallNames.set(id, name);\n currentToolCall = { id, name, argsText: \"\" };\n break;\n }\n case AssistantStreamChunkType.ToolCallArgsTextDelta: {\n const delta = value;\n currentToolCall!.argsText += delta;\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId: currentToolCall!.id,\n toolName: currentToolCall!.name,\n argsTextDelta: delta,\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallResult: {\n controller.enqueue({\n type: \"tool-result\",\n toolCallType: \"function\",\n toolCallId: value.id,\n toolName: toolCallNames.get(value.id)!,\n result: value.result,\n });\n break;\n }\n case AssistantStreamChunkType.Finish: {\n controller.enqueue({\n type: \"finish\",\n ...value,\n });\n break;\n }\n case AssistantStreamChunkType.Error: {\n controller.enqueue({\n type: \"error\",\n error: value,\n });\n break;\n }\n default: {\n const unhandledType: never = type;\n throw new Error(`Unhandled chunk type: ${unhandledType}`);\n }\n }\n },\n });\n}\n","import { ChatModelAdapter, ChatModelRunOptions } from \"../local\";\nimport { ChatModelRunResult } from \"../local/ChatModelAdapter\";\nimport { toCoreMessages } from \"./converters/toCoreMessages\";\nimport { toLanguageModelTools } from \"./converters/toLanguageModelTools\";\nimport { EdgeRuntimeRequestOptions } from \"./EdgeRuntimeRequestOptions\";\nimport { assistantDecoderStream } from \"./streams/assistantDecoderStream\";\nimport { streamPartDecoderStream } from \"./streams/utils/streamPartDecoderStream\";\nimport { runResultStream } from \"./streams/runResultStream\";\nimport { toolResultStream } from \"./streams/toolResultStream\";\n\nexport function asAsyncIterable<T>(\n source: ReadableStream<T>,\n): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]: () => {\n const reader = source.getReader();\n return {\n async next(): Promise<IteratorResult<T, undefined>> {\n const { done, value } = await reader.read();\n return done\n ? { done: true, value: undefined }\n : { done: false, value };\n },\n };\n },\n };\n}\nexport type EdgeChatAdapterOptions = {\n api: string;\n\n credentials?: RequestCredentials;\n headers?: Record<string, string> | Headers;\n body?: object;\n};\n\nexport class EdgeChatAdapter implements ChatModelAdapter {\n constructor(private options: EdgeChatAdapterOptions) {}\n\n async *run({ messages, abortSignal, config }: ChatModelRunOptions) {\n const headers = new Headers(this.options.headers);\n headers.set(\"Content-Type\", \"application/json\");\n\n const result = await fetch(this.options.api, {\n method: \"POST\",\n headers,\n credentials: this.options.credentials ?? \"same-origin\",\n body: JSON.stringify({\n system: config.system,\n messages: toCoreMessages(messages),\n tools: config.tools ? toLanguageModelTools(config.tools) : [],\n ...config.callSettings,\n ...config.config,\n\n ...this.options.body,\n } satisfies EdgeRuntimeRequestOptions),\n signal: abortSignal,\n });\n\n if (result.status !== 200) {\n throw new Error(`Status ${result.status}: ${await result.text()}`);\n }\n\n const stream = result\n .body!.pipeThrough(streamPartDecoderStream())\n .pipeThrough(assistantDecoderStream())\n .pipeThrough(toolResultStream(config.tools, abortSignal))\n .pipeThrough(runResultStream());\n\n let update: ChatModelRunResult | undefined;\n for await (update of asAsyncIterable(stream)) {\n yield update;\n }\n\n if (update === undefined)\n throw new Error(\"No data received from Edge Runtime\");\n }\n}\n","import type { ThreadAssistantMessage } from \"../../types\";\n\nexport const shouldContinue = (result: ThreadAssistantMessage) =>\n result.status?.type === \"requires-action\" &&\n result.status.reason === \"tool-calls\" &&\n result.content.every((c) => c.type !== \"tool-call\" || !!c.result);\n","import { AddToolResultOptions } from \"../../context\";\nimport { generateId } from \"../../internal\";\nimport type {\n ModelConfigProvider,\n AppendMessage,\n ThreadAssistantMessage,\n Unsubscribe,\n} from \"../../types\";\nimport { fromCoreMessage, fromCoreMessages } from \"../edge\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/MessageRepository\";\nimport type { ChatModelAdapter, ChatModelRunResult } from \"./ChatModelAdapter\";\nimport { ThreadRuntimeComposer } from \"../utils/ThreadRuntimeComposer\";\nimport { shouldContinue } from \"./shouldContinue\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { ThreadRuntime } from \"../core\";\nimport { SpeechSynthesisAdapter } from \"../speech\";\n\nexport class LocalThreadRuntime implements ThreadRuntime {\n private _subscriptions = new Set<() => void>();\n\n private abortController: AbortController | null = null;\n private readonly repository = new MessageRepository();\n\n public readonly capabilities = {\n switchToBranch: true,\n edit: true,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speak: false,\n attachments: false,\n };\n\n public readonly threadId: string;\n public readonly isDisabled = false;\n\n public get messages() {\n return this.repository.getMessages();\n }\n\n public readonly composer = new ThreadRuntimeComposer(\n this,\n this.notifySubscribers.bind(this),\n );\n\n constructor(\n private configProvider: ModelConfigProvider,\n public adapter: ChatModelAdapter,\n { initialMessages, ...options }: LocalRuntimeOptions,\n ) {\n this.threadId = generateId();\n this.options = options;\n if (initialMessages) {\n let parentId: string | null = null;\n const messages = fromCoreMessages(initialMessages);\n for (const message of messages) {\n this.repository.addOrUpdateMessage(parentId, message);\n parentId = message.id;\n }\n }\n }\n\n private _options!: LocalRuntimeOptions;\n\n public get options() {\n return this._options;\n }\n\n public set options({ initialMessages, ...options }: LocalRuntimeOptions) {\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speak !== canSpeak) {\n this.capabilities.speak = canSpeak;\n hasUpdates = true;\n }\n\n this.composer.setAttachmentAdapter(options.adapters?.attachments);\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n if (hasUpdates) this.notifySubscribers();\n }\n\n public getBranches(messageId: string): string[] {\n return this.repository.getBranches(messageId);\n }\n\n public switchToBranch(branchId: string): void {\n this.repository.switchToBranch(branchId);\n this.notifySubscribers();\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const newMessage = fromCoreMessage(message, {\n attachments: message.attachments,\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n\n if (message.role === \"user\") {\n await this.startRun(newMessage.id);\n } else {\n this.repository.resetHead(newMessage.id);\n this.notifySubscribers();\n }\n }\n\n public async startRun(parentId: string | null): Promise<void> {\n this.repository.resetHead(parentId);\n\n // add assistant message\n const id = generateId();\n let message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n createdAt: new Date(),\n };\n\n do {\n message = await this.performRoundtrip(parentId, message);\n } while (shouldContinue(message));\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n const messages = this.repository.getMessages();\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n const initialContent = message.content;\n const initialRoundtrips = message.metadata?.roundtrips;\n const initalCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n // TODO deprecated, remove in v0.6\n ...(m.metadata?.roundtrips\n ? {\n roundtrips: [\n ...(initialRoundtrips ?? []),\n ...m.metadata.roundtrips,\n ],\n }\n : undefined),\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.roundtrips\n ? {\n roundtrips: [\n ...(initialRoundtrips ?? []),\n ...m.metadata.roundtrips,\n ],\n }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: { ...(initalCustom ?? {}), ...m.metadata.custom },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this.notifySubscribers();\n };\n\n const maxToolRoundtrips = this.options.maxToolRoundtrips ?? 1;\n const toolRoundtrips = message.metadata?.roundtrips?.length ?? 0;\n if (toolRoundtrips > maxToolRoundtrips) {\n // reached max tool roundtrips\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n }\n\n try {\n const promiseOrGenerator = this.adapter.run({\n messages,\n abortSignal: this.abortController.signal,\n config: this.configProvider.getModelConfig(),\n onUpdate: updateMessage,\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n this.abortController = null;\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n this.abortController = null;\n\n // TODO this should be handled by the run result stream\n if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: { type: \"incomplete\", reason: \"error\", error: e },\n });\n\n throw e;\n }\n }\n return message;\n }\n\n cancelRun(): void {\n if (!this.abortController) return;\n\n this.abortController.abort();\n this.abortController = null;\n }\n\n private notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (!c.result) added = true;\n return {\n ...c,\n result,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n\n if (added && shouldContinue(message)) {\n this.performRoundtrip(parentId, message);\n }\n }\n\n // TODO lift utterance state to thread runtime\n private _utterance: SpeechSynthesisAdapter.Utterance | undefined;\n\n public speak(messageId: string) {\n const adapter = this.options.adapters?.speech;\n if (!adapter) throw new Error(\"Speech adapter not configured\");\n\n const { message } = this.repository.getMessage(messageId);\n\n if (this._utterance) {\n this._utterance.cancel();\n this._utterance = undefined;\n }\n\n const utterance = adapter.speak(message);\n utterance.onEnd(() => {\n if (this._utterance === utterance) {\n this._utterance = undefined;\n }\n });\n this._utterance = utterance;\n\n return this._utterance;\n }\n\n public export() {\n return this.repository.export();\n }\n\n public import(data: ExportedMessageRepository) {\n this.repository.import(data);\n this.notifySubscribers();\n }\n}\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { CoreMessage } from \"../../types/AssistantTypes\";\nimport { BaseAssistantRuntime } from \"../core/BaseAssistantRuntime\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { ProxyConfigProvider } from \"../../internal\";\nimport { LocalThreadRuntime } from \"./LocalThreadRuntime\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { fromCoreMessages } from \"../edge/converters/fromCoreMessage\";\n\nexport class LocalRuntime extends BaseAssistantRuntime<LocalThreadRuntime> {\n private readonly _proxyConfigProvider: ProxyConfigProvider;\n\n constructor(adapter: ChatModelAdapter, options: LocalRuntimeOptions) {\n const proxyConfigProvider = new ProxyConfigProvider();\n super(new LocalThreadRuntime(proxyConfigProvider, adapter, options));\n this._proxyConfigProvider = proxyConfigProvider;\n }\n\n public set adapter(adapter: ChatModelAdapter) {\n this.thread.adapter = adapter;\n }\n\n public set options(options: LocalRuntimeOptions) {\n this.thread.options = options;\n }\n\n registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n\n public switchToNewThread() {\n const { initialMessages, ...options } = this.thread.options;\n\n return (this.thread = new LocalThreadRuntime(\n this._proxyConfigProvider,\n this.thread.adapter,\n options,\n ));\n }\n\n public switchToThread(threadId: string | null) {\n if (threadId !== null) {\n throw new Error(\"LocalRuntime does not yet support switching threads\");\n }\n\n this.switchToNewThread();\n }\n\n public reset({\n initialMessages,\n }: {\n initialMessages?: readonly CoreMessage[] | undefined;\n } = {}) {\n this.switchToThread(null);\n if (!initialMessages) return;\n\n const messages = fromCoreMessages(initialMessages);\n this.thread.import({\n messages: messages.map((m, idx) => ({\n parentId: messages[idx - 1]?.id ?? null,\n message: m,\n })),\n });\n }\n}\n","import { ThreadMessage } from \"../../types\";\n\nexport const symbolInnerMessage = Symbol(\"innerMessage\");\n\nexport type ExternalStoreThreadMessage<T> = ThreadMessage & {\n [symbolInnerMessage]?: T;\n};\n\nexport const getExternalStoreMessage = <T,>(message: ThreadMessage) => {\n return (message as ExternalStoreThreadMessage<T>)[symbolInnerMessage];\n};\n","import { ThreadMessage } from \"../../types\";\n\nexport type ConverterCallback<TIn> = (\n cache: ThreadMessage | undefined,\n message: TIn,\n idx: number,\n) => ThreadMessage;\n\nexport class ThreadMessageConverter {\n private readonly cache = new WeakMap<WeakKey, ThreadMessage>();\n\n convertMessages<TIn extends WeakKey>(\n messages: TIn[],\n converter: ConverterCallback<TIn>,\n ): ThreadMessage[] {\n return messages.map((m, idx) => {\n const cached = this.cache.get(m);\n const newMessage = converter(cached, m, idx);\n this.cache.set(m, newMessage);\n return newMessage;\n });\n }\n}\n","import { MessageStatus } from \"../../types\";\n\nconst AUTO_STATUS_RUNNING = Object.freeze({ type: \"running\" });\nconst AUTO_STATUS_COMPLETE = Object.freeze({\n type: \"complete\",\n reason: \"unknown\",\n});\n\nexport const isAutoStatus = (status: MessageStatus) =>\n status === AUTO_STATUS_RUNNING || status === AUTO_STATUS_COMPLETE;\n\nexport const getAutoStatus = (isLast: boolean, isRunning: boolean) =>\n isLast && isRunning ? AUTO_STATUS_RUNNING : AUTO_STATUS_COMPLETE;\n","import { MessageAttachment } from \"../../context/stores/Attachment\";\nimport {\n MessageStatus,\n TextContentPart,\n ImageContentPart,\n ToolCallContentPart,\n UIContentPart,\n ThreadMessage,\n ThreadAssistantContentPart,\n ThreadAssistantMessage,\n ThreadUserContentPart,\n ThreadUserMessage,\n ThreadSystemMessage,\n} from \"../../types\";\nimport { CoreToolCallContentPart } from \"../../types/AssistantTypes\";\n\nexport type ThreadMessageLike = {\n role: \"assistant\" | \"user\" | \"system\";\n content:\n | string\n | (\n | TextContentPart\n | ImageContentPart\n | ToolCallContentPart<any, any>\n | CoreToolCallContentPart<any, any>\n | UIContentPart\n )[];\n id?: string | undefined;\n createdAt?: Date | undefined;\n status?: MessageStatus | undefined;\n attachments?: MessageAttachment[] | undefined;\n};\n\nexport const fromThreadMessageLike = (\n like: ThreadMessageLike,\n fallbackId: string,\n fallbackStatus: MessageStatus,\n): ThreadMessage => {\n const { role, id, createdAt, attachments, status } = like;\n const common = {\n id: id ?? fallbackId,\n createdAt: createdAt ?? new Date(),\n };\n\n const content =\n typeof like.content === \"string\"\n ? [{ type: \"text\" as const, text: like.content }]\n : like.content;\n\n if (role !== \"user\" && attachments)\n throw new Error(\"Attachments are only supported for user messages\");\n // TODO add in 0.6\n // if (role !== \"assistant\" && status)\n // throw new Error(\"Status is only supported for assistant messages\");\n\n switch (role) {\n case \"assistant\":\n return {\n ...common,\n role,\n content: content\n .map((part): ThreadAssistantContentPart | null => {\n const type = part.type;\n switch (type) {\n case \"text\":\n if (part.text.trim().length === 0) return null;\n return part;\n\n case \"ui\":\n return part;\n\n case \"tool-call\": {\n if (\"argsText\" in part) return part;\n return {\n ...part,\n argsText: JSON.stringify(part.args),\n };\n }\n\n default: {\n const unhandledType: \"image\" = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n }\n })\n .filter((c) => !!c),\n status: status ?? fallbackStatus,\n } satisfies ThreadAssistantMessage;\n\n case \"user\":\n return {\n ...common,\n role,\n content: content.map((part): ThreadUserContentPart => {\n const type = part.type;\n switch (type) {\n case \"text\":\n case \"ui\":\n case \"image\":\n return part;\n\n default: {\n const unhandledType: \"tool-call\" = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n }\n }),\n attachments: attachments ?? [],\n } satisfies ThreadUserMessage;\n\n case \"system\":\n if (content.length !== 1 || content[0]!.type !== \"text\")\n throw new Error(\n \"System messages must have exactly one text content part.\",\n );\n\n return {\n ...common,\n role,\n content: content as [TextContentPart],\n } satisfies ThreadSystemMessage;\n\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n};\n","import type { TextContentPart, ThreadMessage } from \"../types/AssistantTypes\";\n\nexport const getThreadMessageText = (message: ThreadMessage) => {\n const textParts = message.content.filter(\n (part) => part.type === \"text\",\n ) as TextContentPart[];\n\n return textParts.map((part) => part.text).join(\"\\n\\n\");\n};\n","import { ReactThreadRuntime } from \"../core\";\nimport { MessageRepository } from \"../utils/MessageRepository\";\nimport { AppendMessage, ThreadMessage, Unsubscribe } from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { AddToolResultOptions } from \"../../context\";\nimport {\n getExternalStoreMessage,\n symbolInnerMessage,\n} from \"./getExternalStoreMessage\";\nimport { ThreadMessageConverter } from \"./ThreadMessageConverter\";\nimport { getAutoStatus, isAutoStatus } from \"./auto-status\";\nimport { fromThreadMessageLike } from \"./ThreadMessageLike\";\nimport { RuntimeCapabilities } from \"../../context/stores/Thread\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { generateId } from \"../../internal\";\nimport { ThreadRuntimeComposer } from \"../utils/ThreadRuntimeComposer\";\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntime implements ReactThreadRuntime {\n private _subscriptions = new Set<() => void>();\n private repository = new MessageRepository();\n private assistantOptimisticId: string | null = null;\n\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n edit: false,\n reload: false,\n cancel: false,\n unstable_copy: false,\n speak: false,\n attachments: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n public threadId!: string;\n public messages!: ThreadMessage[];\n public isDisabled!: boolean;\n public converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n public readonly composer = new ThreadRuntimeComposer(\n this,\n this.notifySubscribers.bind(this),\n );\n\n constructor(store: ExternalStoreAdapter<any>) {\n this.store = store;\n }\n\n public get store() {\n return this._store;\n }\n\n public set store(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n this.threadId = store.threadId ?? this.threadId ?? generateId();\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n this._capabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n edit: this._store.onEdit !== undefined,\n reload: this._store.onReload !== undefined,\n cancel: this._store.onCancel !== undefined,\n speak: this._store.onSpeak !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false, // default true\n attachments: !!this.store.adapters?.attachments,\n };\n\n this.composer.setAttachmentAdapter(this._store.adapters?.attachments);\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this.converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this.notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n const messages = !store.convertMessage\n ? store.messages\n : this.converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === store.messages.length - 1;\n const autoStatus = getAutoStatus(isLast, isRunning);\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const newMessage = fromThreadMessageLike(\n store.convertMessage(m, idx),\n idx.toString(),\n autoStatus,\n );\n (newMessage as any)[symbolInnerMessage] = m;\n return newMessage;\n });\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n\n if (this.assistantOptimisticId) {\n this.repository.deleteMessage(this.assistantOptimisticId);\n this.assistantOptimisticId = null;\n }\n\n if (hasUpcomingMessage(isRunning, messages)) {\n this.assistantOptimisticId = this.repository.appendOptimisticMessage(\n messages.at(-1)?.id ?? null,\n {\n role: \"assistant\",\n content: [],\n },\n );\n }\n\n this.repository.resetHead(\n this.assistantOptimisticId ?? messages.at(-1)?.id ?? null,\n );\n\n this.messages = this.repository.getMessages();\n this.notifySubscribers();\n }\n\n private notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public getBranches(messageId: string): string[] {\n return this.repository.getBranches(messageId);\n }\n\n public switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n }\n\n public async append(message: AppendMessage): Promise<void> {\n if (message.parentId !== (this.messages.at(-1)?.id ?? null)) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async startRun(parentId: string | null): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n await this._store.onReload(parentId);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.onCancel();\n\n if (this.assistantOptimisticId) {\n this.repository.deleteMessage(this.assistantOptimisticId);\n this.assistantOptimisticId = null;\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this.notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult(options);\n }\n\n public speak(messageId: string) {\n if (!this._store.onSpeak)\n throw new Error(\"Runtime does not support speaking.\");\n\n const { message } = this.repository.getMessage(messageId);\n return this._store.onSpeak(message);\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private updateMessages = (messages: ThreadMessage[]) => {\n this._store.setMessages?.(\n messages.flatMap(getExternalStoreMessage).filter((m) => m != null),\n );\n };\n}\n","import { BaseAssistantRuntime, ProxyConfigProvider } from \"../../internal\";\nimport { ModelConfigProvider } from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { ExternalStoreThreadRuntime } from \"./ExternalStoreThreadRuntime\";\n\nexport class ExternalStoreRuntime extends BaseAssistantRuntime<ExternalStoreThreadRuntime> {\n private readonly _proxyConfigProvider = new ProxyConfigProvider();\n\n constructor(store: ExternalStoreAdapter<any>) {\n super(new ExternalStoreThreadRuntime(store));\n }\n\n public get store() {\n return this.thread.store;\n }\n\n public set store(store: ExternalStoreAdapter<any>) {\n this.thread.store = store;\n }\n\n public getModelConfig() {\n return this._proxyConfigProvider.getModelConfig();\n }\n\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n\n public async switchToNewThread() {\n if (!this.store.onSwitchToNewThread)\n throw new Error(\"Runtime does not support switching to new threads.\");\n\n this.thread = new ExternalStoreThreadRuntime({\n ...this.store,\n messages: [],\n });\n await this.store.onSwitchToNewThread();\n }\n\n public async switchToThread(threadId: string | null) {\n if (threadId !== null) {\n if (!this.store.onSwitchToThread)\n throw new Error(\"Runtime does not support switching threads.\");\n\n this.thread = new ExternalStoreThreadRuntime({\n ...this.store,\n messages: [], // ignore messages until rerender\n });\n this.store.onSwitchToThread(threadId);\n } else {\n this.switchToNewThread();\n }\n }\n}\n","import { useEffect, useState } from \"react\";\nimport { ExternalStoreRuntime } from \"./ExternalStoreRuntime\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\n\nexport const useExternalStoreRuntime = <T,>(store: ExternalStoreAdapter<T>) => {\n const [runtime] = useState(() => new ExternalStoreRuntime(store));\n\n useEffect(() => {\n runtime.store = store;\n });\n\n return runtime;\n};\n","import { useMemo } from \"react\";\nimport { ThreadMessageConverter } from \"./ThreadMessageConverter\";\nimport {\n getExternalStoreMessage,\n symbolInnerMessage,\n} from \"./getExternalStoreMessage\";\nimport { fromThreadMessageLike, ThreadMessageLike } from \"./ThreadMessageLike\";\nimport { getAutoStatus, isAutoStatus } from \"./auto-status\";\nimport { ToolCallContentPart } from \"../../types\";\n\nexport namespace useExternalMessageConverter {\n export type Message =\n | ThreadMessageLike\n | {\n role: \"tool\";\n toolCallId: string;\n toolName?: string | undefined;\n result: any;\n };\n\n export type Callback<T> = (message: T) => Message | Message[];\n}\n\ntype CallbackResult<T> = {\n input: T;\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype ChunkResult<T> = {\n inputs: T[];\n outputs: useExternalMessageConverter.Message[];\n};\n\nconst joinExternalMessages = (\n messages: useExternalMessageConverter.Message[],\n): ThreadMessageLike => {\n const assistantMessage: ThreadMessageLike & { content: any[] } = {\n role: \"assistant\",\n content: [],\n };\n for (const output of messages) {\n if (output.role === \"tool\") {\n const toolCallIdx = assistantMessage.content.findIndex(\n (c) => c.type === \"tool-call\" && c.toolCallId === output.toolCallId,\n );\n if (toolCallIdx !== -1) {\n const toolCall = assistantMessage.content[\n toolCallIdx\n ]! as ToolCallContentPart;\n if (output.toolName) {\n if (toolCall.toolName !== output.toolName)\n throw new Error(\n `Tool call name ${output.toolCallId} ${output.toolName} does not match existing tool call ${toolCall.toolName}`,\n );\n }\n assistantMessage.content[toolCallIdx] = {\n ...toolCall,\n result: output.result,\n };\n } else {\n throw new Error(\n `Tool call ${output.toolCallId} ${output.toolName} not found in assistant message`,\n );\n }\n } else {\n const content = output.content;\n const role = output.role;\n switch (role) {\n case \"system\":\n case \"user\":\n return { role, content };\n case \"assistant\":\n if (assistantMessage.content.length === 0) {\n assistantMessage.id = output.id;\n assistantMessage.createdAt ??= output.createdAt;\n assistantMessage.status ??= output.status;\n // TODO keep this in sync\n }\n assistantMessage.content.push(...content);\n break;\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n }\n }\n return assistantMessage;\n};\n\nconst chunkExternalMessages = <T,>(callbackResults: CallbackResult<T>[]) => {\n const results: ChunkResult<T>[] = [];\n let isAssistant = false;\n let inputs: T[] = [];\n let outputs: useExternalMessageConverter.Message[] = [];\n\n const flush = () => {\n if (outputs.length) {\n results.push({\n inputs,\n outputs,\n });\n }\n inputs = [];\n outputs = [];\n };\n\n for (const callbackResult of callbackResults) {\n for (const output of callbackResult.outputs) {\n if (!isAssistant || output.role === \"user\" || output.role === \"system\") {\n flush();\n }\n isAssistant = output.role === \"assistant\" || output.role === \"tool\";\n\n if (inputs.at(-1) !== callbackResult.input) {\n inputs.push(callbackResult.input);\n }\n outputs.push(output);\n }\n }\n flush();\n return results;\n};\n\nexport const useExternalMessageConverter = <T extends WeakKey>({\n callback,\n messages,\n isRunning,\n}: {\n callback: useExternalMessageConverter.Callback<T>;\n messages: T[];\n isRunning: boolean;\n}) => {\n const state = useMemo(\n () => ({\n callback,\n callbackCache: new WeakMap<T, CallbackResult<T>>(),\n chunkCache: new WeakMap<\n useExternalMessageConverter.Message,\n ChunkResult<T>\n >(),\n converterCache: new ThreadMessageConverter(),\n }),\n [callback],\n );\n\n return useMemo(() => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n let result = state.callbackCache.get(message);\n if (!result) {\n const output = state.callback(message);\n const outputs = Array.isArray(output) ? output : [output];\n result = { input: message, outputs };\n state.callbackCache.set(message, result);\n }\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults).map((m) => {\n const key = m.outputs[0];\n if (!key) return m;\n\n const cached = state.chunkCache.get(key);\n if (cached && shallowArrayEqual(cached.outputs, m.outputs)) return cached;\n state.chunkCache.set(key, m);\n return m;\n });\n\n return state.converterCache.convertMessages(\n chunks,\n (cache, message, idx) => {\n const isLast = idx === chunks.length - 1;\n const autoStatus = getAutoStatus(isLast, isRunning);\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n ) {\n const inputs = getExternalStoreMessage(cache) as T[];\n if (shallowArrayEqual(inputs, message.inputs)) {\n return cache;\n }\n }\n\n const newMessage = fromThreadMessageLike(\n joinExternalMessages(message.outputs),\n idx.toString(),\n autoStatus,\n );\n (newMessage as any)[symbolInnerMessage] = message.inputs;\n return newMessage;\n },\n );\n }, [state, messages, isRunning]);\n};\n\nconst shallowArrayEqual = (a: unknown[], b: unknown[]) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n};\n","import { LocalRuntimeOptions, useLocalRuntime } from \"..\";\nimport { useState } from \"react\";\nimport {\n DangerousInBrowserAdapter,\n DangerousInBrowserAdapterOptions,\n} from \"./DangerousInBrowserAdapter\";\n\nexport type DangerousInBrowserRuntimeOptions =\n DangerousInBrowserAdapterOptions & LocalRuntimeOptions;\n\nexport const useDangerousInBrowserRuntime = ({\n initialMessages,\n ...options\n}: DangerousInBrowserRuntimeOptions) => {\n const [adapter] = useState(() => new DangerousInBrowserAdapter(options));\n return useLocalRuntime(adapter, { initialMessages });\n};\n","import { ChatModelAdapter, ChatModelRunOptions } from \"../local\";\nimport { toCoreMessages } from \"../edge/converters/toCoreMessages\";\nimport { toLanguageModelTools } from \"../edge/converters/toLanguageModelTools\";\nimport { EdgeRuntimeRequestOptions } from \"../edge/EdgeRuntimeRequestOptions\";\nimport { runResultStream } from \"../edge/streams/runResultStream\";\nimport { toolResultStream } from \"../edge/streams/toolResultStream\";\nimport { asAsyncIterable } from \"../edge/EdgeChatAdapter\";\nimport {\n CreateEdgeRuntimeAPIOptions,\n getEdgeRuntimeStream,\n} from \"../edge/createEdgeRuntimeAPI\";\n\nexport type DangerousInBrowserAdapterOptions = CreateEdgeRuntimeAPIOptions;\n\nexport class DangerousInBrowserAdapter implements ChatModelAdapter {\n constructor(private options: DangerousInBrowserAdapterOptions) {}\n\n async *run({ messages, abortSignal, config }: ChatModelRunOptions) {\n const res = await getEdgeRuntimeStream({\n options: this.options,\n abortSignal,\n requestData: {\n system: config.system,\n messages: toCoreMessages(messages),\n tools: config.tools ? toLanguageModelTools(config.tools) : [],\n ...config.callSettings,\n ...config.config,\n } satisfies EdgeRuntimeRequestOptions,\n });\n\n const stream = res\n .pipeThrough(toolResultStream(config.tools, abortSignal))\n .pipeThrough(runResultStream());\n\n for await (const update of asAsyncIterable(stream)) {\n yield update;\n }\n }\n}\n","import { ThreadMessage } from \"../../types\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { SpeechSynthesisAdapter } from \"./SpeechAdapterTypes\";\n\nexport class WebSpeechSynthesisAdapter implements SpeechSynthesisAdapter {\n speak(message: ThreadMessage): SpeechSynthesisAdapter.Utterance {\n const text = getThreadMessageText(message);\n const utterance = new SpeechSynthesisUtterance(text);\n\n const endHandlers = new Set<() => void>();\n const handleEnd = (\n reason: \"finished\" | \"error\" | \"cancelled\",\n error?: unknown,\n ) => {\n if (res.status.type === \"ended\") return;\n\n res.status = { type: \"ended\", reason, error };\n endHandlers.forEach((handler) => handler());\n };\n\n utterance.addEventListener(\"end\", () => handleEnd(\"finished\"));\n utterance.addEventListener(\"error\", (e) => handleEnd(\"error\", e.error));\n\n window.speechSynthesis.speak(utterance);\n\n const res: SpeechSynthesisAdapter.Utterance = {\n status: { type: \"running\" },\n cancel: () => {\n window.speechSynthesis.cancel();\n handleEnd(\"cancelled\");\n },\n onEnd: (callback) => {\n if (res.status.type === \"ended\") {\n let cancelled = false;\n queueMicrotask(() => {\n if (!cancelled) callback();\n });\n return () => {\n cancelled = true;\n };\n } else {\n endHandlers.add(callback);\n return () => {\n endHandlers.delete(callback);\n };\n }\n },\n };\n return res;\n }\n}\n","import {\n ThreadComposerAttachment,\n MessageAttachment,\n} from \"../../context/stores/Attachment\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nexport class SimpleImageAttachmentAdapter implements AttachmentAdapter {\n public accept = \"image/*\";\n\n public async add(state: { file: File }): Promise<ThreadComposerAttachment> {\n return {\n id: state.file.name,\n type: \"image\",\n name: state.file.name,\n file: state.file,\n };\n }\n\n public async send(\n attachment: ThreadComposerAttachment,\n ): Promise<MessageAttachment> {\n return {\n ...attachment,\n content: [\n {\n type: \"image\",\n image: await getFileDataURL(attachment.file),\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileDataURL = (file: File) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n\n reader.readAsDataURL(file);\n });\n","import {\n ThreadComposerAttachment,\n MessageAttachment,\n} from \"../../context/stores/Attachment\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nexport class SimpleTextAttachmentAdapter implements AttachmentAdapter {\n public accept =\n \"text/plain,text/html,text/markdown,text/csv,text/xml,text/json,text/css\";\n\n public async add(state: { file: File }): Promise<ThreadComposerAttachment> {\n return {\n id: state.file.name,\n type: \"document\",\n name: state.file.name,\n file: state.file,\n };\n }\n\n public async send(\n attachment: ThreadComposerAttachment,\n ): Promise<MessageAttachment> {\n return {\n ...attachment,\n content: [\n {\n type: \"text\",\n text: `<attachment name=${attachment.name}>\\n${await getFileText(attachment.file)}\\n</attachment>`,\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileText = (file: File) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n\n reader.readAsText(file);\n });\n","import {\n ThreadComposerAttachment,\n MessageAttachment,\n} from \"../../context/stores/Attachment\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nfunction fileMatchesAccept(file: File, acceptString: string) {\n // Check if the accept string is \"*\", which allows any file\n if (acceptString === \"*\") {\n return true;\n }\n\n // Split the accept string into an array of allowed types\n const allowedTypes = acceptString\n .split(\",\")\n .map((type) => type.trim().toLowerCase());\n\n // Get the file's extension and MIME type\n const fileExtension = \".\" + file.name.split(\".\").pop()!.toLowerCase();\n const fileMimeType = file.type.toLowerCase();\n\n for (const type of allowedTypes) {\n // Check for file extension match\n if (type.startsWith(\".\") && type === fileExtension) {\n return true;\n }\n\n // Check for exact MIME type match\n if (type.includes(\"/\") && type === fileMimeType) {\n return true;\n }\n\n if (type === \"image/*\" || type === \"video/*\" || type === \"audio/*\") {\n // Check for wildcard MIME type match\n if (type.endsWith(\"/*\")) {\n const generalType = type.split(\"/\")[0]!;\n if (fileMimeType.startsWith(generalType + \"/\")) {\n return true;\n }\n }\n }\n }\n\n return false;\n}\n\nexport class CompositeAttachmentAdapter implements AttachmentAdapter {\n private _adapters: AttachmentAdapter[];\n\n public accept: string;\n\n constructor(adapters: AttachmentAdapter[]) {\n this._adapters = adapters;\n\n const wildcardIdx = adapters.findIndex((a) => a.accept === \"*\");\n if (wildcardIdx !== -1) {\n if (wildcardIdx !== adapters.length - 1)\n throw new Error(\n \"A wildcard adapter (handling all files) can only be specified as the last adapter.\",\n );\n\n this.accept = \"*\";\n } else {\n this.accept = adapters.map((a) => a.accept).join(\",\");\n }\n }\n\n public async add(state: { file: File }): Promise<ThreadComposerAttachment> {\n for (const adapter of this._adapters) {\n if (fileMatchesAccept(state.file, adapter.accept)) {\n return adapter.add(state);\n }\n }\n throw new Error(\"No matching adapter found for file\");\n }\n\n public async send(\n attachment: ThreadComposerAttachment,\n ): Promise<MessageAttachment> {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.send(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n\n public async remove(attachment: ThreadComposerAttachment): Promise<void> {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.remove(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n}\n","import { create } from \"zustand\";\nimport { AssistantRuntime } from \"../../runtimes\";\nimport { MutableRefObject } from \"react\";\nimport { ModelConfigProvider, Unsubscribe } from \"../../types\";\n\nexport type AssistantActionsState = Readonly<{\n /**\n * @deprecated Use `switchToNewThread` instead. This will be removed in 0.6.0.\n */\n switchToThread(threadId: null): void;\n switchToThread(threadId: string): void;\n\n switchToNewThread: () => void;\n registerModelConfigProvider: (provider: ModelConfigProvider) => Unsubscribe;\n}>;\n\nexport const makeAssistantActionsStore = (\n runtimeRef: MutableRefObject<AssistantRuntime>,\n) =>\n create<AssistantActionsState>(() =>\n Object.freeze({\n switchToThread: () => runtimeRef.current.switchToThread(null),\n switchToNewThread: () => runtimeRef.current.switchToNewThread(),\n registerModelConfigProvider: (provider: ModelConfigProvider) =>\n runtimeRef.current.registerModelConfigProvider(provider),\n getRuntime: () => runtimeRef.current,\n }),\n );\n","import { create } from \"zustand\";\nimport { AssistantRuntime } from \"../../runtimes\";\n\nexport type AssistantRuntimeStore = AssistantRuntime;\n\nexport const makeAssistantRuntimeStore = (runtime: AssistantRuntime) => {\n return create<AssistantRuntimeStore>(() => runtime);\n};\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useState } from \"react\";\nimport { ContentPartState } from \"../stores\";\nimport { create } from \"zustand\";\nimport {\n ContentPartContext,\n ContentPartContextValue,\n} from \"../react/ContentPartContext\";\nimport { ContentPartStatus, TextContentPart } from \"../../types/AssistantTypes\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype TextContentPartProviderProps = {\n text: string;\n isRunning?: boolean | undefined;\n};\n\nconst COMPLETE_STATUS: ContentPartStatus = {\n type: \"complete\",\n};\n\nconst RUNNING_STATUS: ContentPartStatus = {\n type: \"running\",\n};\n\nexport const TextContentPartProvider: FC<\n PropsWithChildren<TextContentPartProviderProps>\n> = ({ children, text, isRunning }) => {\n const [context] = useState<ContentPartContextValue>(() => {\n const useContentPart = create<ContentPartState>(() => ({\n status: isRunning ? RUNNING_STATUS : COMPLETE_STATUS,\n part: { type: \"text\", text },\n }));\n\n return {\n useContentPart,\n };\n });\n\n useEffect(() => {\n const state = context.useContentPart.getState();\n const textUpdated = (state.part as TextContentPart).text !== text;\n const targetTextPart = textUpdated\n ? { type: \"text\" as const, text }\n : state.part;\n const targetStatus = isRunning ? RUNNING_STATUS : COMPLETE_STATUS;\n const statusUpdated = state.status !== targetStatus;\n\n if (!textUpdated && !statusUpdated) return;\n\n writableStore(context.useContentPart).setState(\n {\n part: targetTextPart,\n status: targetStatus,\n },\n true,\n );\n }, [context, isRunning, text]);\n\n return (\n <ContentPartContext.Provider value={context}>\n {children}\n </ContentPartContext.Provider>\n );\n};\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { MessageState } from \"../stores/Message\";\nimport type { EditComposerState } from \"../stores/EditComposer\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { MessageUtilsState } from \"../stores/MessageUtils\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type MessageContextValue = {\n useMessage: UseBoundStore<ReadonlyStore<MessageState>>;\n useMessageUtils: UseBoundStore<ReadonlyStore<MessageUtilsState>>;\n useEditComposer: UseBoundStore<ReadonlyStore<EditComposerState>>;\n};\n\nexport const MessageContext = createContext<MessageContextValue | null>(null);\n\nexport const useMessageContext = createContextHook(\n MessageContext,\n \"a component passed to <ThreadPrimitive.Messages components={...} />\",\n);\n\n// TODO make this only return the message itself?\nexport const { useMessage, useMessageStore } = createContextStoreHook(\n useMessageContext,\n \"useMessage\",\n);\n\nexport const { useMessageUtils, useMessageUtilsStore } = createContextStoreHook(\n useMessageContext,\n \"useMessageUtils\",\n);\n\nexport const { useEditComposer, useEditComposerStore } = createContextStoreHook(\n useMessageContext,\n \"useEditComposer\",\n);\n","import { useMemo } from \"react\";\nimport { useMessageContext } from \"./MessageContext\";\nimport { useThreadContext } from \"./ThreadContext\";\nimport type { ThreadComposerState } from \"../stores/ThreadComposer\";\nimport type { EditComposerState } from \"../stores/EditComposer\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\n\nexport type ComposerContextValue = {\n useComposer: ReadonlyStore<EditComposerState | ThreadComposerState>;\n type: \"edit\" | \"new\";\n};\n\nexport const useComposerContext = (): ComposerContextValue => {\n const { useComposer } = useThreadContext();\n const { useEditComposer } = useMessageContext({ optional: true }) ?? {};\n return useMemo(\n () => ({\n useComposer: (useEditComposer ?? useComposer) as ReadonlyStore<\n EditComposerState | ThreadComposerState\n >,\n type: useEditComposer ? (\"edit\" as const) : (\"new\" as const),\n }),\n [useEditComposer, useComposer],\n );\n};\n\nexport const { useComposer, useComposerStore } = createContextStoreHook(\n useComposerContext,\n \"useComposer\",\n);\n","import { useCallback } from \"react\";\nimport {\n ThreadMessagesState,\n useThreadActionsStore,\n useThreadMessagesStore,\n useThreadViewportStore,\n} from \"../context\";\nimport { AppendMessage } from \"../types\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\nimport { ReadonlyStore } from \"../context/ReadonlyStore\";\n\ntype CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n };\n\nconst toAppendMessage = (\n useThreadMessages: ReadonlyStore<ThreadMessagesState>,\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n parentId: useThreadMessages.getState().at(-1)?.id ?? null,\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n };\n }\n\n return {\n parentId:\n message.parentId ?? useThreadMessages.getState().at(-1)?.id ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n } as AppendMessage;\n};\n\nexport const useAppendMessage = () => {\n const threadMessagesStore = useThreadMessagesStore();\n const threadActionsStore = useThreadActionsStore();\n const threadViewportStore = useThreadViewportStore();\n const threadComposerStore = useThreadComposerStore();\n\n const append = useCallback(\n (message: CreateAppendMessage) => {\n const appendMessage = toAppendMessage(threadMessagesStore, message);\n threadActionsStore.getState().append(appendMessage);\n\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n },\n [\n threadMessagesStore,\n threadActionsStore,\n threadViewportStore,\n threadComposerStore,\n ],\n );\n\n return append;\n};\n","import { useCallback } from \"react\";\nimport { useAssistantActionsStore } from \"../context\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\n\n/**\n * @deprecated Use `useRuntimeActions().switchToNewThread()` instead. This will be removed in 0.6.0.\n */\nexport const useSwitchToNewThread = () => {\n const assistantActionsStore = useAssistantActionsStore();\n const threadComposerStore = useThreadComposerStore();\n const switchToNewThread = useCallback(() => {\n assistantActionsStore.getState().switchToNewThread();\n threadComposerStore.getState().focus();\n }, [assistantActionsStore, threadComposerStore]);\n\n return switchToNewThread;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport {\n useAssistantActionsStore,\n useToolUIsStore,\n} from \"../context/react/AssistantContext\";\nimport type { ToolCallContentPartComponent } from \"../types/ContentPartComponentTypes\";\nimport type { Tool } from \"../types/ModelConfigTypes\";\n\nexport type AssistantToolProps<\n TArgs extends Record<string, unknown>,\n TResult,\n> = Tool<TArgs, TResult> & {\n toolName: string;\n render?: ToolCallContentPartComponent<TArgs, TResult> | undefined;\n};\n\nexport const useAssistantTool = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n tool: AssistantToolProps<TArgs, TResult>,\n) => {\n const assistantActionsStore = useAssistantActionsStore();\n const toolUIsStore = useToolUIsStore();\n useEffect(() => {\n const { toolName, render, ...rest } = tool;\n const config = {\n tools: {\n [tool.toolName]: rest,\n },\n };\n const unsub1 = assistantActionsStore\n .getState()\n .registerModelConfigProvider({\n getModelConfig: () => config,\n });\n const unsub2 = render\n ? toolUIsStore.getState().setToolUI(toolName, render)\n : undefined;\n return () => {\n unsub1();\n unsub2?.();\n };\n }, [assistantActionsStore, toolUIsStore, tool]);\n};\n","\"use client\";\nimport { FC } from \"react\";\nimport { type AssistantToolProps, useAssistantTool } from \"./useAssistantTool\";\n\nexport type AssistantTool = FC & {\n unstable_tool: AssistantToolProps<any, any>;\n};\n\nexport const makeAssistantTool = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n tool: AssistantToolProps<TArgs, TResult>,\n) => {\n const Tool: AssistantTool = () => {\n useAssistantTool(tool);\n return null;\n };\n Tool.unstable_tool = tool;\n return Tool;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useToolUIsStore } from \"../context/react/AssistantContext\";\nimport type { ToolCallContentPartComponent } from \"../types/ContentPartComponentTypes\";\n\nexport type AssistantToolUIProps<\n TArgs extends Record<string, unknown>,\n TResult,\n> = {\n toolName: string;\n render: ToolCallContentPartComponent<TArgs, TResult>;\n};\n\nexport const useAssistantToolUI = (\n tool: AssistantToolUIProps<any, any> | null,\n) => {\n const toolUIsStore = useToolUIsStore();\n useEffect(() => {\n if (!tool) return;\n const { toolName, render } = tool;\n return toolUIsStore.getState().setToolUI(toolName, render);\n }, [toolUIsStore, tool]);\n};\n","\"use client\";\nimport { FC } from \"react\";\nimport {\n type AssistantToolUIProps,\n useAssistantToolUI,\n} from \"./useAssistantToolUI\";\n\nexport type AssistantToolUI = FC & {\n unstable_tool: AssistantToolUIProps<any, any>;\n};\n\nexport const makeAssistantToolUI = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n tool: AssistantToolUIProps<TArgs, TResult>,\n) => {\n const ToolUI: AssistantToolUI = () => {\n useAssistantToolUI(tool);\n return null;\n };\n ToolUI.unstable_tool = tool;\n return ToolUI;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useAssistantActionsStore } from \"../context\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const actionsStore = useAssistantActionsStore();\n useEffect(() => {\n const config = {\n system: instruction,\n };\n return actionsStore\n .getState()\n .registerModelConfigProvider({ getModelConfig: () => config });\n }, [actionsStore, instruction]);\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposerStore,\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\n\nexport type UseActionBarCopyProps = {\n copiedDuration?: number | undefined;\n};\n\nexport const useActionBarCopy = ({\n copiedDuration = 3000,\n}: UseActionBarCopyProps = {}) => {\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n const editComposerStore = useEditComposerStore();\n const hasCopyableContent = useCombinedStore(\n [messageStore, editComposerStore],\n ({ message }, c) => {\n return (\n !c.isEditing &&\n (message.role !== \"assistant\" || message.status.type !== \"running\") &&\n message.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n },\n );\n\n const callback = useCallback(() => {\n const { message } = messageStore.getState();\n const { setIsCopied } = messageUtilsStore.getState();\n const { isEditing, text: composerValue } = editComposerStore.getState();\n\n const valueToCopy = isEditing\n ? composerValue\n : getThreadMessageText(message);\n\n navigator.clipboard.writeText(valueToCopy).then(() => {\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), copiedDuration);\n });\n }, [messageStore, messageUtilsStore, editComposerStore, copiedDuration]);\n\n if (!hasCopyableContent) return null;\n return callback;\n};\n","import { useMemo } from \"react\";\nimport {\n type CombinedSelector,\n createCombinedStore,\n} from \"./createCombinedStore\";\nimport { ReadonlyStore } from \"../../context/ReadonlyStore\";\n\nexport const useCombinedStore = <T extends Array<unknown>, R>(\n stores: { [K in keyof T]: ReadonlyStore<T[K]> },\n selector: CombinedSelector<T, R>,\n): R => {\n // eslint-disable-next-line react-hooks/exhaustive-deps -- shallow-compare the store array\n const useCombined = useMemo(() => createCombinedStore<T, R>(stores), stores);\n return useCombined(selector);\n};\n","\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport { ReadonlyStore } from \"../../context/ReadonlyStore\";\n\nexport type CombinedSelector<T extends Array<unknown>, R> = (...args: T) => R;\n\nexport const createCombinedStore = <T extends Array<unknown>, R>(stores: {\n [K in keyof T]: ReadonlyStore<T[K]>;\n}) => {\n const subscribe = (callback: () => void): Unsubscribe => {\n const unsubscribes = stores.map((store) => store.subscribe(callback));\n return () => {\n for (const unsub of unsubscribes) {\n unsub();\n }\n };\n };\n\n return (selector: CombinedSelector<T, R>): R => {\n const getSnapshot = (): R =>\n selector(...(stores.map((store) => store.getState()) as T));\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n };\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposer,\n useEditComposerStore,\n} from \"../../context/react/MessageContext\";\n\nexport const useActionBarEdit = () => {\n const editComposerStore = useEditComposerStore();\n const disabled = useEditComposer((c) => c.isEditing);\n\n const callback = useCallback(() => {\n const { edit } = editComposerStore.getState();\n edit();\n }, [editComposerStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageStore } from \"../../context/react/MessageContext\";\nimport {\n useThreadActionsStore,\n useThreadComposerStore,\n useThreadStore,\n useThreadViewportStore,\n} from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useActionBarReload = () => {\n const messageStore = useMessageStore();\n const threadStore = useThreadStore();\n const threadActionsStore = useThreadActionsStore();\n const threadComposerStore = useThreadComposerStore();\n const threadViewportStore = useThreadViewportStore();\n\n const disabled = useCombinedStore(\n [threadStore, messageStore],\n (t, m) => t.isRunning || t.isDisabled || m.message.role !== \"assistant\",\n );\n\n const callback = useCallback(() => {\n const { parentId } = messageStore.getState();\n threadActionsStore.getState().startRun(parentId);\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [\n threadActionsStore,\n threadComposerStore,\n threadViewportStore,\n messageStore,\n ]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\n\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport {\n useEditComposerStore,\n useMessageStore,\n useMessageUtilsStore,\n useThreadActionsStore,\n} from \"../../context\";\n\nexport const useActionBarSpeak = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const threadActionsStore = useThreadActionsStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n const hasSpeakableContent = useCombinedStore(\n [messageStore, editComposerStore],\n ({ message }, c) => {\n return (\n !c.isEditing &&\n (message.role !== \"assistant\" || message.status.type !== \"running\") &&\n message.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n },\n );\n\n const callback = useCallback(async () => {\n const { message } = messageStore.getState();\n const utt = threadActionsStore.getState().speak(message.id);\n messageUtilsStore.getState().addUtterance(utt);\n }, [threadActionsStore, messageStore, messageUtilsStore]);\n\n if (!hasSpeakableContent) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport {\n useMessageUtils,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\n\nexport const useActionBarStopSpeaking = () => {\n const messageUtilsStore = useMessageUtilsStore();\n const isSpeaking = useMessageUtils((u) => u.isSpeaking);\n\n const callback = useCallback(async () => {\n messageUtilsStore.getState().stopSpeaking();\n }, [messageUtilsStore]);\n\n if (!isSpeaking) return null;\n\n return callback;\n};\n","\"use client\";\nimport { useMessage } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerCount = () => {\n const branchCount = useMessage((s) => s.branches.length);\n return branchCount;\n};\n","import { useCallback } from \"react\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport {\n useEditComposerStore,\n useMessageStore,\n useThreadActionsStore,\n} from \"../../context\";\n\nexport const useBranchPickerNext = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const threadActionsStore = useThreadActionsStore();\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) =>\n c.isEditing || m.branches.indexOf(m.message.id) + 1 >= m.branches.length,\n );\n\n const callback = useCallback(() => {\n const { message, branches } = messageStore.getState();\n threadActionsStore\n .getState()\n .switchToBranch(branches[branches.indexOf(message.id) + 1]!);\n }, [threadActionsStore, messageStore]);\n\n if (disabled) return null;\n return callback;\n};\n","\"use client\";\n\nimport { useMessage } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerNumber = () => {\n const branchIdx = useMessage((s) => s.branches.indexOf(s.message.id));\n return branchIdx + 1;\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposerStore,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport { useThreadActionsStore } from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useBranchPickerPrevious = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const threadActionsStore = useThreadActionsStore();\n\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) => c.isEditing || m.branches.indexOf(m.message.id) <= 0,\n );\n\n const callback = useCallback(() => {\n const { message, branches } = messageStore.getState();\n threadActionsStore\n .getState()\n .switchToBranch(branches[branches.indexOf(message.id) - 1]!);\n }, [threadActionsStore, messageStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useComposer, useComposerStore } from \"../../context\";\n\nexport const useComposerCancel = () => {\n const composerStore = useComposerStore();\n const disabled = useComposer((c) => !c.canCancel);\n\n const callback = useCallback(() => {\n const { cancel } = composerStore.getState();\n cancel();\n }, [composerStore]);\n\n if (disabled) return null;\n return callback;\n};\n","\"use client\";\n\nimport { useComposer } from \"../../context/react/ComposerContext\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\n\ntype ComposerIfFilters = {\n editing: boolean | undefined;\n};\n\nexport type UseComposerIfProps = RequireAtLeastOne<ComposerIfFilters>;\n\nexport const useComposerIf = (props: UseComposerIfProps) => {\n return useComposer((composer) => {\n if (props.editing === true && !composer.isEditing) return false;\n if (props.editing === false && composer.isEditing) return false;\n\n return true;\n });\n};\n","import { useCallback } from \"react\";\nimport { useComposerStore } from \"../../context\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport {\n useThreadComposerStore,\n useThreadStore,\n useThreadViewportStore,\n} from \"../../context/react/ThreadContext\";\n\nexport const useComposerSend = () => {\n const threadStore = useThreadStore();\n const threadViewportStore = useThreadViewportStore();\n const composerStore = useComposerStore();\n const threadComposerStore = useThreadComposerStore();\n\n const disabled = useCombinedStore(\n [threadStore, composerStore],\n (t, c) => t.isRunning || !c.isEditing || c.isEmpty,\n );\n\n const callback = useCallback(() => {\n const composerState = composerStore.getState();\n if (!composerState.isEditing) return;\n\n composerState.send();\n\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [threadComposerStore, composerStore, threadViewportStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useComposer } from \"../../context\";\nimport { useThreadComposerStore } from \"../../context/react/ThreadContext\";\n\nexport const useComposerAddAttachment = () => {\n const disabled = useComposer((c) => !c.isEditing);\n\n const threadComposerStore = useThreadComposerStore();\n const threadRuntimeStore = useThreadComposerStore();\n const callback = useCallback(() => {\n const { addAttachment } = threadComposerStore.getState();\n const { attachmentAccept } = threadRuntimeStore.getState();\n\n const input = document.createElement(\"input\");\n input.type = \"file\";\n if (attachmentAccept !== \"*\") {\n input.accept = attachmentAccept;\n }\n\n input.onchange = (e) => {\n const file = (e.target as HTMLInputElement).files?.[0];\n if (!file) return;\n addAttachment(file);\n };\n\n input.click();\n }, [threadComposerStore, threadRuntimeStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { UIContentPartState } from \"../../context/stores/ContentPart\";\n\nexport const useContentPartDisplay = () => {\n const display = useContentPart((c) => {\n if (c.part.type !== \"ui\")\n throw new Error(\n \"This component can only be used inside ui content parts.\",\n );\n\n return c as UIContentPartState;\n });\n\n return display;\n};\n","import { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { ImageContentPartState } from \"../../context/stores/ContentPart\";\n\nexport const useContentPartImage = () => {\n const image = useContentPart((c) => {\n if (c.part.type !== \"image\")\n throw new Error(\n \"ContentPartImage can only be used inside image content parts.\",\n );\n\n return c as ImageContentPartState;\n });\n\n return image;\n};\n","import { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { TextContentPartState } from \"../../context/stores/ContentPart\";\n\nexport const useContentPartText = () => {\n const text = useContentPart((c) => {\n if (c.part.type !== \"text\")\n throw new Error(\n \"ContentPartText can only be used inside text content parts.\",\n );\n\n return c as TextContentPartState;\n });\n\n return text;\n};\n","\"use client\";\nimport {\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\ntype MessageIfFilters = {\n user: boolean | undefined;\n assistant: boolean | undefined;\n system: boolean | undefined;\n hasBranches: boolean | undefined;\n copied: boolean | undefined;\n lastOrHover: boolean | undefined;\n speaking: boolean | undefined;\n hasAttachments: boolean | undefined;\n};\nexport type UseMessageIfProps = RequireAtLeastOne<MessageIfFilters>;\n\nexport const useMessageIf = (props: UseMessageIfProps) => {\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [messageStore, messageUtilsStore],\n ({ message, branches, isLast }, { isCopied, isHovering, isSpeaking }) => {\n if (props.hasBranches === true && branches.length < 2) return false;\n\n if (props.user && message.role !== \"user\") return false;\n if (props.assistant && message.role !== \"assistant\") return false;\n if (props.system && message.role !== \"system\") return false;\n\n if (props.lastOrHover === true && !isHovering && !isLast) return false;\n\n if (props.copied === true && !isCopied) return false;\n if (props.copied === false && isCopied) return false;\n\n if (props.speaking === true && !isSpeaking) return false;\n if (props.speaking === false && isSpeaking) return false;\n\n if (\n props.hasAttachments === true &&\n (message.role !== \"user\" || !message.attachments.length)\n )\n return false;\n if (\n props.hasAttachments === false &&\n message.role === \"user\" &&\n !!message.attachments.length\n )\n return false;\n\n return true;\n },\n );\n};\n","\"use client\";\n\nimport { useThreadMessagesStore, useThreadStore } from \"../../context\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\ntype ThreadIfFilters = {\n empty: boolean | undefined;\n running: boolean | undefined;\n disabled: boolean | undefined;\n};\n\nexport type UseThreadIfProps = RequireAtLeastOne<ThreadIfFilters>;\n\nexport const useThreadIf = (props: UseThreadIfProps) => {\n const threadStore = useThreadStore();\n const threadMessagesStore = useThreadMessagesStore();\n return useCombinedStore(\n [threadStore, threadMessagesStore],\n (thread, messages) => {\n if (props.empty === true && messages.length !== 0) return false;\n if (props.empty === false && messages.length === 0) return false;\n if (props.running === true && !thread.isRunning) return false;\n if (props.running === false && thread.isRunning) return false;\n if (props.disabled === true && thread.isDisabled) return false;\n if (props.disabled === false && thread.isDisabled) return false;\n\n return true;\n },\n );\n};\n","import { useThreadIf } from \"./useThreadIf\";\n\nexport const useThreadEmpty = () => {\n return useThreadIf({ empty: true });\n};\n","import { useCallback } from \"react\";\nimport { useThreadViewport } from \"../../context\";\nimport {\n useThreadComposerStore,\n useThreadViewportStore,\n} from \"../../context/react/ThreadContext\";\n\nexport const useThreadScrollToBottom = () => {\n const isAtBottom = useThreadViewport((s) => s.isAtBottom);\n\n const threadViewportStore = useThreadViewportStore();\n const threadComposerStore = useThreadComposerStore();\n\n const handleScrollToBottom = useCallback(() => {\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [threadViewportStore, threadComposerStore]);\n\n if (isAtBottom) return null;\n return handleScrollToBottom;\n};\n","import { useCallback } from \"react\";\nimport { useThread, useThreadStore } from \"../../context\";\nimport { useAppendMessage } from \"../../hooks\";\nimport { useThreadComposerStore } from \"../../context/react/ThreadContext\";\n\nexport type UseApplyThreadSuggestionProps = {\n prompt: string;\n method: \"replace\";\n autoSend?: boolean | undefined;\n};\n\nexport const useThreadSuggestion = ({\n prompt,\n autoSend,\n}: UseApplyThreadSuggestionProps) => {\n const threadStore = useThreadStore();\n const composerStore = useThreadComposerStore();\n\n const append = useAppendMessage();\n const disabled = useThread((t) => t.isDisabled);\n const callback = useCallback(() => {\n const thread = threadStore.getState();\n const composer = composerStore.getState();\n if (autoSend && !thread.isRunning) {\n append(prompt);\n composer.setText(\"\");\n } else {\n composer.setText(prompt);\n }\n }, [threadStore, composerStore, autoSend, append, prompt]);\n\n if (disabled) return null;\n return callback;\n};\n","export { ActionBarPrimitiveRoot as Root } from \"./ActionBarRoot\";\nexport { ActionBarPrimitiveCopy as Copy } from \"./ActionBarCopy\";\nexport { ActionBarPrimitiveReload as Reload } from \"./ActionBarReload\";\nexport { ActionBarPrimitiveEdit as Edit } from \"./ActionBarEdit\";\nexport { ActionBarPrimitiveSpeak as Speak } from \"./ActionBarSpeak\";\nexport { ActionBarPrimitiveStopSpeaking as StopSpeaking } from \"./ActionBarStopSpeaking\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport {\n useActionBarFloatStatus,\n HideAndFloatStatus,\n UseActionBarFloatStatusProps,\n} from \"./useActionBarFloatStatus\";\n\ntype ActionBarPrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type ActionBarPrimitiveRootProps = PrimitiveDivProps &\n UseActionBarFloatStatusProps;\n\nexport const ActionBarPrimitiveRoot = forwardRef<\n ActionBarPrimitiveRootElement,\n ActionBarPrimitiveRootProps\n>(({ hideWhenRunning, autohide, autohideFloat, ...rest }, ref) => {\n const hideAndfloatStatus = useActionBarFloatStatus({\n hideWhenRunning,\n autohide,\n autohideFloat,\n });\n\n if (hideAndfloatStatus === HideAndFloatStatus.Hidden) return null;\n\n return (\n <Primitive.div\n {...(hideAndfloatStatus === HideAndFloatStatus.Floating\n ? { \"data-floating\": \"true\" }\n : null)}\n {...rest}\n ref={ref}\n />\n );\n});\n\nActionBarPrimitiveRoot.displayName = \"ActionBarPrimitive.Root\";\n","\"use client\";\nimport {\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport { useThreadStore } from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport enum HideAndFloatStatus {\n Hidden = \"hidden\",\n Floating = \"floating\",\n Normal = \"normal\",\n}\n\nexport type UseActionBarFloatStatusProps = {\n hideWhenRunning?: boolean | undefined;\n autohide?: \"always\" | \"not-last\" | \"never\" | undefined;\n autohideFloat?: \"always\" | \"single-branch\" | \"never\" | undefined;\n};\n\nexport const useActionBarFloatStatus = ({\n hideWhenRunning,\n autohide,\n autohideFloat,\n}: UseActionBarFloatStatusProps) => {\n const threadStore = useThreadStore();\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [threadStore, messageStore, messageUtilsStore],\n (t, m, mu) => {\n if (hideWhenRunning && t.isRunning) return HideAndFloatStatus.Hidden;\n\n const autohideEnabled =\n autohide === \"always\" || (autohide === \"not-last\" && !m.isLast);\n\n // normal status\n if (!autohideEnabled) return HideAndFloatStatus.Normal;\n\n // hidden status\n if (!mu.isHovering) return HideAndFloatStatus.Hidden;\n\n // floating status\n if (\n autohideFloat === \"always\" ||\n (autohideFloat === \"single-branch\" && m.branches.length <= 1)\n )\n return HideAndFloatStatus.Floating;\n\n return HideAndFloatStatus.Normal;\n },\n );\n};\n","\"use client\";\n\nimport { ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\n\ntype ActionButtonCallback<TProps> = (props: TProps) => null | (() => void);\n\ntype PrimitiveButtonElement = ElementRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = ComponentPropsWithoutRef<typeof Primitive.button>;\n\nexport type ActionButtonProps<THook> = PrimitiveButtonProps &\n (THook extends (props: infer TProps) => unknown ? TProps : never);\n\nexport const createActionButton = <TProps,>(\n displayName: string,\n useActionButton: ActionButtonCallback<TProps>,\n forwardProps: (keyof NonNullable<TProps>)[] = [],\n) => {\n const ActionButton = forwardRef<\n PrimitiveButtonElement,\n PrimitiveButtonProps & TProps\n >((props, forwardedRef) => {\n const forwardedProps = {} as TProps;\n const primitiveProps = {} as PrimitiveButtonProps;\n\n (Object.keys(props) as Array<keyof typeof props>).forEach((key) => {\n if (forwardProps.includes(key as keyof TProps)) {\n (forwardedProps as any)[key] = props[key];\n } else {\n (primitiveProps as any)[key] = props[key];\n }\n });\n\n const callback = useActionButton(forwardedProps as TProps);\n return (\n <Primitive.button\n type=\"button\"\n {...primitiveProps}\n ref={forwardedRef}\n disabled={primitiveProps.disabled || !callback}\n onClick={composeEventHandlers(primitiveProps.onClick, () => {\n callback?.();\n })}\n />\n );\n });\n\n ActionButton.displayName = displayName;\n\n return ActionButton;\n};\n","\"use client\";\n\nimport { useActionBarCopy } from \"../../primitive-hooks/actionBar/useActionBarCopy\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type ActionBarPrimitiveCopyProps = ActionButtonProps<\n typeof useActionBarCopy\n>;\n\nexport const ActionBarPrimitiveCopy = createActionButton(\n \"ActionBarPrimitive.Copy\",\n useActionBarCopy,\n [\"copiedDuration\"],\n);\n","\"use client\";\n\nimport { useActionBarReload } from \"../../primitive-hooks/actionBar/useActionBarReload\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type ActionBarPrimitiveReloadProps = ActionButtonProps<\n typeof useActionBarReload\n>;\n\nexport const ActionBarPrimitiveReload = createActionButton(\n \"ActionBarPrimitive.Reload\",\n useActionBarReload,\n);\n","\"use client\";\n\nimport { useActionBarEdit } from \"../../primitive-hooks/actionBar/useActionBarEdit\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type ActionBarPrimitiveEditProps = ActionButtonProps<\n typeof useActionBarEdit\n>;\n\nexport const ActionBarPrimitiveEdit = createActionButton(\n \"ActionBarPrimitive.Edit\",\n useActionBarEdit,\n);\n","\"use client\";\n\nimport { useActionBarSpeak } from \"../../primitive-hooks/actionBar/useActionBarSpeak\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type ActionBarPrimitiveSpeakProps = ActionButtonProps<\n typeof useActionBarSpeak\n>;\n\nexport const ActionBarPrimitiveSpeak = createActionButton(\n \"ActionBarPrimitive.Speak\",\n useActionBarSpeak,\n);\n","\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { useActionBarStopSpeaking } from \"../../primitive-hooks/actionBar/useActionBarStopSpeaking\";\nimport { ActionButtonProps } from \"../../utils/createActionButton\";\nimport { useEscapeKeydown } from \"@radix-ui/react-use-escape-keydown\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\n\nexport type ActionBarPrimitiveStopSpeakingProps = ActionButtonProps<\n typeof useActionBarStopSpeaking\n>;\n\nexport const ActionBarPrimitiveStopSpeaking = forwardRef<\n HTMLButtonElement,\n Partial<ActionBarPrimitiveStopSpeakingProps>\n>((props, ref) => {\n const callback = useActionBarStopSpeaking();\n\n // TODO this stops working if the user is not hovering over an older message\n useEscapeKeydown((e) => {\n if (callback) {\n e.preventDefault();\n callback();\n }\n });\n\n return (\n <Primitive.button\n type=\"button\"\n disabled={!callback}\n {...props}\n ref={ref}\n onClick={composeEventHandlers(props.onClick, () => {\n callback?.();\n })}\n />\n );\n});\n\nActionBarPrimitiveStopSpeaking.displayName = \"ActionBarPrimitive.StopSpeaking\";\n","export { AssistantModalPrimitiveRoot as Root } from \"./AssistantModalRoot\";\nexport { AssistantModalPrimitiveTrigger as Trigger } from \"./AssistantModalTrigger\";\nexport { AssistantModalPrimitiveContent as Content } from \"./AssistantModalContent\";\nexport { AssistantModalPrimitiveAnchor as Anchor } from \"./AssistantModalAnchor\";\n","\"use client\";\n\nimport { FC, useState } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useOnComposerFocus } from \"../../utils/hooks/useOnComposerFocus\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\n\nexport type AssistantModalPrimitiveRootProps = PopoverPrimitive.PopoverProps;\n\nconst useAssistantModalOpenState = (defaultOpen = false) => {\n const state = useState(defaultOpen);\n\n const [, setOpen] = state;\n useOnComposerFocus(() => {\n setOpen(true);\n });\n\n return state;\n};\n\nexport const AssistantModalPrimitiveRoot: FC<\n AssistantModalPrimitiveRootProps\n> = ({\n __scopeAssistantModal,\n defaultOpen,\n open,\n onOpenChange,\n ...rest\n}: ScopedProps<AssistantModalPrimitiveRootProps>) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n const [modalOpen, setOpen] = useAssistantModalOpenState(defaultOpen);\n\n return (\n <PopoverPrimitive.Root\n {...scope}\n open={open === undefined ? modalOpen : open}\n onOpenChange={composeEventHandlers(onOpenChange, setOpen)}\n {...rest}\n />\n );\n};\n\nAssistantModalPrimitiveRoot.displayName = \"AssistantModalPrimitive.Root\";\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useEffect } from \"react\";\nimport { useThreadComposerStore } from \"../../context/react/ThreadContext\";\n\nexport const useOnComposerFocus = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n\n const threadComposerStore = useThreadComposerStore();\n useEffect(() => {\n return threadComposerStore.getState().onFocus(() => {\n callbackRef();\n });\n }, [threadComposerStore, callbackRef]);\n};\n","import * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport type { Scope } from \"@radix-ui/react-context\";\n\nexport type ScopedProps<P> = P & { __scopeAssistantModal?: Scope };\nexport const usePopoverScope = PopoverPrimitive.createPopoverScope();\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\n\ntype AssistantModalPrimitiveTriggerElement = ElementRef<\n typeof PopoverPrimitive.Trigger\n>;\nexport type AssistantModalPrimitiveTriggerProps = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Trigger\n>;\n\nexport const AssistantModalPrimitiveTrigger = forwardRef<\n AssistantModalPrimitiveTriggerElement,\n AssistantModalPrimitiveTriggerProps\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveTriggerProps>,\n ref,\n ) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n return <PopoverPrimitive.Trigger {...scope} {...rest} ref={ref} />;\n },\n);\n\nAssistantModalPrimitiveTrigger.displayName = \"AssistantModalPrimitive.Trigger\";\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\n\ntype AssistantModalPrimitiveContentElement = ElementRef<\n typeof PopoverPrimitive.Content\n>;\nexport type AssistantModalPrimitiveContentProps = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Content\n> & {\n dissmissOnInteractOutside?: boolean | undefined;\n};\n\nexport const AssistantModalPrimitiveContent = forwardRef<\n AssistantModalPrimitiveContentElement,\n AssistantModalPrimitiveContentProps\n>(\n (\n {\n __scopeAssistantModal,\n side,\n align,\n onInteractOutside,\n dissmissOnInteractOutside = false,\n ...props\n }: ScopedProps<AssistantModalPrimitiveContentProps>,\n forwardedRef,\n ) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n return (\n <PopoverPrimitive.Portal {...scope}>\n <PopoverPrimitive.Content\n {...scope}\n {...props}\n ref={forwardedRef}\n side={side ?? \"top\"}\n align={align ?? \"end\"}\n onInteractOutside={composeEventHandlers(\n onInteractOutside,\n dissmissOnInteractOutside ? undefined : (e) => e.preventDefault(),\n )}\n />\n </PopoverPrimitive.Portal>\n );\n },\n);\n\nAssistantModalPrimitiveContent.displayName = \"AssistantModalPrimitive.Content\";\n","\"use client\";\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\n\ntype AssistantModalPrimitiveAnchorElement = ElementRef<\n typeof PopoverPrimitive.Anchor\n>;\ntype AssistantModalPrimitiveAnchorProps = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Anchor\n>;\n\nexport const AssistantModalPrimitiveAnchor = forwardRef<\n AssistantModalPrimitiveAnchorElement,\n AssistantModalPrimitiveAnchorProps\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveAnchorProps>,\n ref,\n ) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n return <PopoverPrimitive.Anchor {...scope} {...rest} ref={ref} />;\n },\n);\nAssistantModalPrimitiveAnchor.displayName = \"AssistantModalPrimitive.Anchor\";\n","export { BranchPickerPrimitiveNext as Next } from \"./BranchPickerNext\";\nexport { BranchPickerPrevious as Previous } from \"./BranchPickerPrevious\";\nexport { BranchPickerPrimitiveCount as Count } from \"./BranchPickerCount\";\nexport { BranchPickerPrimitiveNumber as Number } from \"./BranchPickerNumber\";\nexport { BranchPickerPrimitiveRoot as Root } from \"./BranchPickerRoot\";\n","\"use client\";\n\nimport { useBranchPickerNext } from \"../../primitive-hooks/branchPicker/useBranchPickerNext\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type BranchPickerPrimitiveNextProps = ActionButtonProps<\n typeof useBranchPickerNext\n>;\n\nexport const BranchPickerPrimitiveNext = createActionButton(\n \"BranchPickerPrimitive.Next\",\n useBranchPickerNext,\n);\n","\"use client\";\n\nimport { useBranchPickerPrevious } from \"../../primitive-hooks/branchPicker/useBranchPickerPrevious\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type BranchPickerPrimitivePreviousProps = ActionButtonProps<\n typeof useBranchPickerPrevious\n>;\n\nexport const BranchPickerPrevious = createActionButton(\n \"BranchPickerPrimitive.Previous\",\n useBranchPickerPrevious,\n);\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport { useBranchPickerCount } from \"../../primitive-hooks/branchPicker/useBranchPickerCount\";\n\nexport type BranchPickerPrimitiveCountProps = Record<string, never>;\n\nexport const BranchPickerPrimitiveCount: FC<\n BranchPickerPrimitiveCountProps\n> = () => {\n const branchCount = useBranchPickerCount();\n return <>{branchCount}</>;\n};\n\nBranchPickerPrimitiveCount.displayName = \"BranchPickerPrimitive.Count\";\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport { useBranchPickerNumber } from \"../../primitive-hooks/branchPicker/useBranchPickerNumber\";\n\nexport type BranchPickerPrimitiveNumberProps = Record<string, never>;\n\nexport const BranchPickerPrimitiveNumber: FC<\n BranchPickerPrimitiveNumberProps\n> = () => {\n const branchNumber = useBranchPickerNumber();\n return <>{branchNumber}</>;\n};\n\nBranchPickerPrimitiveNumber.displayName = \"BranchPickerPrimitive.Number\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport { If } from \"../message\";\n\ntype BranchPickerPrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type BranchPickerPrimitiveRootProps = PrimitiveDivProps & {\n hideWhenSingleBranch?: boolean | undefined;\n};\n\nexport const BranchPickerPrimitiveRoot = forwardRef<\n BranchPickerPrimitiveRootElement,\n BranchPickerPrimitiveRootProps\n>(({ hideWhenSingleBranch, ...rest }, ref) => {\n return (\n <If hasBranches={hideWhenSingleBranch ? true : undefined}>\n <Primitive.div {...rest} ref={ref} />\n </If>\n );\n});\n\nBranchPickerPrimitiveRoot.displayName = \"BranchPickerPrimitive.Root\";\n","export { MessagePrimitiveRoot as Root } from \"./MessageRoot\";\nexport { MessagePrimitiveIf as If } from \"./MessageIf\";\nexport { MessagePrimitiveContent as Content } from \"./MessageContent\";\nexport { MessagePrimitiveInProgress as InProgress } from \"./MessageInProgress\";\nexport { MessagePrimitiveAttachments as Attachments } from \"./MessageAttachments\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport {\n type ElementRef,\n forwardRef,\n ComponentPropsWithoutRef,\n useCallback,\n} from \"react\";\nimport { useMessageUtilsStore } from \"../../context/react/MessageContext\";\nimport { useManagedRef } from \"../../utils/hooks/useManagedRef\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\n\ntype MessagePrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nconst useIsHoveringRef = () => {\n const messageUtilsStore = useMessageUtilsStore();\n const callbackRef = useCallback(\n (el: HTMLElement) => {\n const setIsHovering = messageUtilsStore.getState().setIsHovering;\n\n const handleMouseEnter = () => {\n setIsHovering(true);\n };\n const handleMouseLeave = () => {\n setIsHovering(false);\n };\n\n el.addEventListener(\"mouseenter\", handleMouseEnter);\n el.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n el.removeEventListener(\"mouseenter\", handleMouseEnter);\n el.removeEventListener(\"mouseleave\", handleMouseLeave);\n setIsHovering(false);\n };\n },\n [messageUtilsStore],\n );\n\n return useManagedRef(callbackRef);\n};\n\nexport type MessagePrimitiveRootProps = PrimitiveDivProps;\n\nexport const MessagePrimitiveRoot = forwardRef<\n MessagePrimitiveRootElement,\n MessagePrimitiveRootProps\n>((props, forwardRef) => {\n const isHoveringRef = useIsHoveringRef();\n const ref = useComposedRefs<HTMLDivElement>(forwardRef, isHoveringRef);\n\n return <Primitive.div {...props} ref={ref} />;\n});\n\nMessagePrimitiveRoot.displayName = \"MessagePrimitive.Root\";\n","import { useCallback, useRef } from \"react\";\n\nexport const useManagedRef = <TNode>(\n callback: (node: TNode) => (() => void) | void,\n) => {\n const cleanupRef = useRef<(() => void) | void>();\n\n const ref = useCallback(\n (el: TNode | null) => {\n // Call the previous cleanup function\n if (cleanupRef.current) {\n cleanupRef.current();\n }\n\n // Call the new callback and store its cleanup function\n if (el) {\n cleanupRef.current = callback(el);\n }\n },\n [callback],\n );\n\n return ref;\n};\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport {\n UseMessageIfProps,\n useMessageIf,\n} from \"../../primitive-hooks/message/useMessageIf\";\n\nexport type MessagePrimitiveIfProps = PropsWithChildren<UseMessageIfProps>;\n\nexport const MessagePrimitiveIf: FC<MessagePrimitiveIfProps> = ({\n children,\n ...query\n}) => {\n const result = useMessageIf(query);\n return result ? children : null;\n};\n\nMessagePrimitiveIf.displayName = \"MessagePrimitive.If\";\n","\"use client\";\n\nimport { type ComponentType, type FC, memo } from \"react\";\nimport {\n useContentPart,\n useThreadActionsStore,\n useToolUIs,\n} from \"../../context\";\nimport {\n useMessage,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport {\n ContentPartProvider,\n EMPTY_CONTENT,\n} from \"../../context/providers/ContentPartProvider\";\nimport { ContentPartPrimitiveText } from \"../contentPart/ContentPartText\";\nimport { ContentPartPrimitiveImage } from \"../contentPart/ContentPartImage\";\nimport { ContentPartPrimitiveDisplay } from \"../contentPart/ContentPartDisplay\";\nimport type {\n EmptyContentPartComponent,\n ImageContentPartComponent,\n TextContentPartComponent,\n ToolCallContentPartComponent,\n ToolCallContentPartProps,\n UIContentPartComponent,\n} from \"../../types/ContentPartComponentTypes\";\nimport { ContentPartPrimitiveInProgress } from \"../contentPart/ContentPartInProgress\";\n\nexport type MessagePrimitiveContentProps = {\n components?:\n | {\n Empty?: EmptyContentPartComponent | undefined;\n Text?: TextContentPartComponent | undefined;\n Image?: ImageContentPartComponent | undefined;\n UI?: UIContentPartComponent | undefined;\n tools?:\n | {\n by_name?:\n | Record<string, ToolCallContentPartComponent | undefined>\n | undefined;\n Fallback?: ComponentType<ToolCallContentPartProps> | undefined;\n }\n | undefined;\n }\n | undefined;\n};\n\nconst ToolUIDisplay = ({\n UI,\n ...props\n}: {\n UI: ToolCallContentPartComponent | undefined;\n} & ToolCallContentPartProps) => {\n const Render = useToolUIs((s) => s.getToolUI(props.part.toolName)) ?? UI;\n if (!Render) return null;\n return <Render {...props} />;\n};\n\nconst defaultComponents = {\n Text: () => (\n <p style={{ whiteSpace: \"pre-line\" }}>\n <ContentPartPrimitiveText />\n <ContentPartPrimitiveInProgress>\n <span style={{ fontFamily: \"revert\" }}>{\" \\u25CF\"}</span>\n </ContentPartPrimitiveInProgress>\n </p>\n ),\n Image: () => <ContentPartPrimitiveImage />,\n UI: () => <ContentPartPrimitiveDisplay />,\n} satisfies MessagePrimitiveContentProps[\"components\"];\n\ntype MessageContentPartComponentProps = {\n components: MessagePrimitiveContentProps[\"components\"];\n};\n\nconst MessageContentPartComponent: FC<MessageContentPartComponentProps> = ({\n components: {\n Text = defaultComponents.Text,\n Empty,\n Image = defaultComponents.Image,\n UI = defaultComponents.UI,\n tools: { by_name = {}, Fallback = undefined } = {},\n } = {},\n}) => {\n const messageStore = useMessageStore();\n const threadActionsStore = useThreadActionsStore();\n\n const { part, status } = useContentPart();\n\n const type = part.type;\n switch (type) {\n case \"text\":\n if (status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n if (part === EMPTY_CONTENT && !!Empty) {\n return <Empty status={status} />;\n }\n\n return <Text part={part} status={status} />;\n\n case \"image\":\n if (status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n // eslint-disable-next-line jsx-a11y/alt-text\n return <Image part={part} status={status} />;\n\n case \"ui\":\n if (status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n return <UI part={part} status={status} />;\n\n case \"tool-call\": {\n const Tool = by_name[part.toolName] || Fallback;\n const addResult = (result: any) =>\n threadActionsStore.getState().addToolResult({\n messageId: messageStore.getState().message.id,\n toolName: part.toolName,\n toolCallId: part.toolCallId,\n result,\n });\n return (\n <ToolUIDisplay\n UI={Tool}\n part={part}\n status={status}\n addResult={addResult}\n />\n );\n }\n default:\n const unhandledType: never = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n};\n\ntype MessageContentPartProps = {\n partIndex: number;\n components: MessagePrimitiveContentProps[\"components\"];\n};\n\nconst MessageContentPartImpl: FC<MessageContentPartProps> = ({\n partIndex,\n components,\n}) => {\n return (\n <ContentPartProvider partIndex={partIndex}>\n <MessageContentPartComponent components={components} />\n </ContentPartProvider>\n );\n};\n\nconst MessageContentPart = memo(\n MessageContentPartImpl,\n (prev, next) =>\n prev.partIndex === next.partIndex &&\n prev.components?.Text === next.components?.Text &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.UI === next.components?.UI &&\n prev.components?.tools === next.components?.tools,\n);\n\nexport const MessagePrimitiveContent: FC<MessagePrimitiveContentProps> = ({\n components,\n}) => {\n const contentLength = useMessage((s) => s.message.content.length) || 1;\n\n return Array.from({ length: contentLength }, (_, index) => (\n <MessageContentPart key={index} partIndex={index} components={components} />\n ));\n};\n\nMessagePrimitiveContent.displayName = \"MessagePrimitive.Content\";\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport { ContentPartContext } from \"../react/ContentPartContext\";\nimport type { ContentPartContextValue } from \"../react/ContentPartContext\";\nimport { useMessageStore } from \"../react/MessageContext\";\nimport type { MessageState } from \"../stores\";\nimport type { ContentPartState } from \"../stores/ContentPart\";\nimport {\n ContentPartStatus,\n ThreadAssistantContentPart,\n ThreadMessage,\n ThreadUserContentPart,\n ToolCallContentPartStatus,\n} from \"../../types/AssistantTypes\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype ContentPartProviderProps = PropsWithChildren<{\n partIndex: number;\n}>;\n\nconst COMPLETE_STATUS: ContentPartStatus = {\n type: \"complete\",\n};\n\nconst toContentPartStatus = (\n message: ThreadMessage,\n partIndex: number,\n part: ThreadUserContentPart | ThreadAssistantContentPart,\n): ToolCallContentPartStatus => {\n if (message.role !== \"assistant\") return COMPLETE_STATUS;\n\n const isLastPart = partIndex === Math.max(0, message.content.length - 1);\n if (part.type !== \"tool-call\") {\n if (\n \"reason\" in message.status &&\n message.status.reason === \"tool-calls\" &&\n isLastPart\n )\n throw new Error(\n \"Encountered unexpected requires-action status. This is likely an internal bug in assistant-ui.\",\n );\n\n return isLastPart ? (message.status as ContentPartStatus) : COMPLETE_STATUS;\n }\n\n if (!!part.result) {\n return COMPLETE_STATUS;\n }\n\n return message.status as ToolCallContentPartStatus;\n};\n\nexport const EMPTY_CONTENT = Object.freeze({ type: \"text\", text: \"\" });\n\nconst getContentPartState = (\n { message }: MessageState,\n useContentPart: ContentPartContextValue[\"useContentPart\"] | undefined,\n partIndex: number,\n) => {\n let part = message.content[partIndex];\n if (!part) {\n // for empty messages, show an empty text content part\n if (message.content.length === 0 && partIndex === 0) {\n part = EMPTY_CONTENT;\n } else {\n return null;\n }\n } else if (\n message.content.length === 1 &&\n part.type === \"text\" &&\n part.text.length === 0\n ) {\n // ensure reference equality for equivalent empty text parts\n part = EMPTY_CONTENT;\n }\n\n // if the content part is the same, don't update\n const status = toContentPartStatus(message, partIndex, part);\n const currentState = useContentPart?.getState();\n if (\n currentState &&\n currentState.part === part &&\n currentState.status === status\n )\n return null;\n\n return Object.freeze({ part, status });\n};\n\nconst useContentPartContext = (partIndex: number) => {\n const messageStore = useMessageStore();\n const [context] = useState<ContentPartContextValue>(() => {\n const useContentPart = create<ContentPartState>(\n () => getContentPartState(messageStore.getState(), undefined, partIndex)!,\n );\n\n return { useContentPart };\n });\n\n useEffect(() => {\n const syncContentPart = (message: MessageState) => {\n const newState = getContentPartState(\n message,\n context.useContentPart,\n partIndex,\n );\n if (!newState) return;\n writableStore(context.useContentPart).setState(newState, true);\n };\n\n syncContentPart(messageStore.getState());\n return messageStore.subscribe(syncContentPart);\n }, [context, messageStore, partIndex]);\n\n return context;\n};\n\nexport const ContentPartProvider: FC<ContentPartProviderProps> = ({\n partIndex,\n children,\n}) => {\n const context = useContentPartContext(partIndex);\n\n return (\n <ContentPartContext.Provider value={context}>\n {children}\n </ContentPartContext.Provider>\n );\n};\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport {\n type ElementRef,\n forwardRef,\n ComponentPropsWithoutRef,\n ElementType,\n} from \"react\";\nimport { useContentPartText } from \"../../primitive-hooks/contentPart/useContentPartText\";\nimport { useSmooth } from \"../../utils/smooth/useSmooth\";\n\ntype ContentPartPrimitiveTextElement = ElementRef<typeof Primitive.span>;\ntype PrimitiveSpanProps = ComponentPropsWithoutRef<typeof Primitive.span>;\n\nexport type ContentPartPrimitiveTextProps = Omit<\n PrimitiveSpanProps,\n \"children\" | \"asChild\"\n> & {\n smooth?: boolean;\n component?: ElementType;\n};\n\nexport const ContentPartPrimitiveText = forwardRef<\n ContentPartPrimitiveTextElement,\n ContentPartPrimitiveTextProps\n>(({ smooth = true, component: Component = \"span\", ...rest }, forwardedRef) => {\n const {\n part: { text },\n status,\n } = useSmooth(useContentPartText(), smooth);\n\n return (\n <Component data-status={status.type} {...rest} ref={forwardedRef}>\n {text}\n </Component>\n );\n});\n\nContentPartPrimitiveText.displayName = \"ContentPartPrimitive.Text\";\n","import { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport { useContentPartImage } from \"../../primitive-hooks/contentPart/useContentPartImage\";\n\ntype ContentPartPrimitiveImageElement = ElementRef<typeof Primitive.img>;\ntype PrimitiveImageProps = ComponentPropsWithoutRef<typeof Primitive.img>;\n\nexport type ContentPartPrimitiveImageProps = PrimitiveImageProps;\n\nexport const ContentPartPrimitiveImage = forwardRef<\n ContentPartPrimitiveImageElement,\n ContentPartPrimitiveImageProps\n>((props, forwardedRef) => {\n const {\n part: { image },\n } = useContentPartImage();\n return <Primitive.img src={image} {...props} ref={forwardedRef} />;\n});\n\nContentPartPrimitiveImage.displayName = \"ContentPartPrimitive.Image\";\n","import type { FC } from \"react\";\nimport { useContentPartDisplay } from \"../../primitive-hooks/contentPart/useContentPartDisplay\";\n\nexport type ContentPartPrimitiveDisplayProps = Record<string, never>;\n\nexport const ContentPartPrimitiveDisplay: FC = () => {\n const {\n part: { display },\n } = useContentPartDisplay();\n return display ?? null;\n};\n\nContentPartPrimitiveDisplay.displayName = \"ContentPartPrimitive.Display\";\n","import { FC, PropsWithChildren } from \"react\";\nimport { useContentPart } from \"../../context\";\n\nexport type ContentPartPrimitiveInProgressProps = PropsWithChildren;\n\n// TODO should this be renamed to IsRunning?\nexport const ContentPartPrimitiveInProgress: FC<\n ContentPartPrimitiveInProgressProps\n> = ({ children }) => {\n const isInProgress = useContentPart((c) => c.status.type === \"running\");\n\n return isInProgress ? children : null;\n};\n\nContentPartPrimitiveInProgress.displayName = \"ContentPartPrimitive.InProgress\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { ComponentPropsWithoutRef, FC } from \"react\";\n\ntype PrimitiveSpanProps = ComponentPropsWithoutRef<typeof Primitive.span>;\n\nexport type MessagePrimitiveInProgressProps = PrimitiveSpanProps;\n\n/**\n * @deprecated Define a custom Text renderer via ContentPartPrimitiveInProgress instead. This will be removed in 0.6.\n */\nexport const MessagePrimitiveInProgress: FC<\n MessagePrimitiveInProgressProps\n> = () => {\n return null;\n};\n\nMessagePrimitiveInProgress.displayName = \"MessagePrimitive.InProgress\";\n","\"use client\";\n\nimport { ComponentType, type FC, memo } from \"react\";\nimport { useMessage } from \"../../context\";\nimport { useMessageAttachment } from \"../../context/react/AttachmentContext\";\nimport { MessageAttachmentProvider } from \"../../context/providers/MessageAttachmentProvider\";\nimport type { MessageAttachment } from \"../../context/stores/Attachment\";\n\nexport type MessagePrimitiveAttachmentsProps = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n};\n\nconst getComponent = (\n components: MessagePrimitiveAttachmentsProps[\"components\"],\n attachment: MessageAttachment,\n) => {\n const type = attachment.type;\n switch (type) {\n case \"image\":\n return components?.Image ?? components?.Attachment;\n case \"document\":\n return components?.Document ?? components?.Attachment;\n case \"file\":\n return components?.File ?? components?.Attachment;\n default:\n const _exhaustiveCheck: never = type;\n throw new Error(`Unknown attachment type: ${_exhaustiveCheck}`);\n }\n};\n\nconst AttachmentComponent: FC<{\n components: MessagePrimitiveAttachmentsProps[\"components\"];\n}> = ({ components }) => {\n const Component = useMessageAttachment((a) =>\n getComponent(components, a.attachment),\n );\n\n if (!Component) return null;\n return <Component />;\n};\n\nconst MessageAttachmentImpl: FC<\n MessagePrimitiveAttachmentsProps & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n return (\n <MessageAttachmentProvider attachmentIndex={attachmentIndex}>\n <AttachmentComponent components={components} />\n </MessageAttachmentProvider>\n );\n};\n\nconst MessageAttachment = memo(\n MessageAttachmentImpl,\n (prev, next) =>\n prev.attachmentIndex === next.attachmentIndex &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.Document === next.components?.Document &&\n prev.components?.File === next.components?.File &&\n prev.components?.Attachment === next.components?.Attachment,\n);\n\nexport const MessagePrimitiveAttachments: FC<\n MessagePrimitiveAttachmentsProps\n> = ({ components }) => {\n const attachmentsCount = useMessage(({ message }) => {\n if (message.role !== \"user\") return 0;\n return message.attachments.length;\n });\n\n return Array.from({ length: attachmentsCount }, (_, index) => (\n <MessageAttachment\n key={index}\n attachmentIndex={index}\n components={components}\n />\n ));\n};\n\nMessagePrimitiveAttachments.displayName = \"MessagePrimitive.Attachments\";\n","\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport {\n ComposerAttachmentState,\n MessageAttachmentState,\n} from \"../stores/Attachment\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\n\nexport type AttachmentContextValue = {\n type: \"composer\" | \"message\";\n useAttachment: ReadonlyStore<\n ComposerAttachmentState | MessageAttachmentState\n >;\n};\n\ntype ComposerAttachmentContextValue = {\n type: \"composer\";\n useAttachment: ReadonlyStore<ComposerAttachmentState>;\n};\n\ntype MessageAttachmentContextValue = {\n type: \"message\";\n useAttachment: ReadonlyStore<MessageAttachmentState>;\n};\n\nexport const AttachmentContext = createContext<AttachmentContextValue | null>(\n null,\n);\n\nexport function useAttachmentContext(options?: {\n optional?: false | undefined;\n}): AttachmentContextValue;\nexport function useAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): AttachmentContextValue | null;\nexport function useAttachmentContext(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useContext(AttachmentContext);\n if (!options?.optional && !context)\n throw new Error(\n \"This component must be used within a ComposerPrimitive.Attachments or MessagePrimitive.Attachments component.\",\n );\n\n return context;\n}\n\nfunction useComposerAttachmentContext(): ComposerAttachmentContextValue;\nfunction useComposerAttachmentContext(options: {\n optional: true;\n}): ComposerAttachmentContextValue | null;\nfunction useComposerAttachmentContext(options?: { optional?: true }) {\n const context = useAttachmentContext(options);\n if (!context) return null;\n if (context.type !== \"composer\")\n throw new Error(\n \"This component must be used within a ComposerPrimitive.Attachments component.\",\n );\n return context;\n}\n\nfunction useMessageAttachmentContext(): MessageAttachmentContextValue;\nfunction useMessageAttachmentContext(options: {\n optional: true;\n}): MessageAttachmentContextValue | null;\nfunction useMessageAttachmentContext(options?: { optional?: true }) {\n const context = useAttachmentContext(options);\n if (!context) return null;\n if (context.type !== \"message\")\n throw new Error(\n \"This component must be used within a MessagePrimitive.Attachments component.\",\n );\n return context;\n}\n\nexport const { useAttachment, useAttachmentStore } = createContextStoreHook(\n useAttachmentContext,\n \"useAttachment\",\n);\n\nexport const {\n useAttachment: useComposerAttachment,\n useAttachmentStore: useComposerAttachmentStore,\n} = createContextStoreHook(useComposerAttachmentContext, \"useAttachment\");\n\nexport const {\n useAttachment: useMessageAttachment,\n useAttachmentStore: useMessageAttachmentStore,\n} = createContextStoreHook(useMessageAttachmentContext, \"useAttachment\");\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport type { MessageState } from \"../stores\";\nimport { useMessageStore } from \"../react\";\nimport { MessageAttachmentState } from \"../stores/Attachment\";\nimport {\n AttachmentContext,\n AttachmentContextValue,\n} from \"../react/AttachmentContext\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype MessageAttachmentProviderProps = PropsWithChildren<{\n attachmentIndex: number;\n}>;\n\nconst getAttachment = (\n { message }: MessageState,\n useAttachment: AttachmentContextValue[\"useAttachment\"] | undefined,\n partIndex: number,\n) => {\n if (message.role !== \"user\") return null;\n\n const attachments = message.attachments;\n const attachment = attachments[partIndex];\n if (!attachment) return null;\n\n // if the attachment is the same, don't update\n const currentState = useAttachment?.getState();\n if (currentState && currentState.attachment === attachment) return null;\n\n return Object.freeze({ attachment });\n};\n\nconst useMessageAttachmentContext = (partIndex: number) => {\n const messageStore = useMessageStore();\n const [context] = useState<AttachmentContextValue & { type: \"message\" }>(\n () => {\n const useAttachment = create<MessageAttachmentState>(\n () => getAttachment(messageStore.getState(), undefined, partIndex)!,\n );\n\n return { type: \"message\", useAttachment };\n },\n );\n\n useEffect(() => {\n const syncAttachment = (messageState: MessageState) => {\n const newState = getAttachment(\n messageState,\n context.useAttachment,\n partIndex,\n );\n if (!newState) return;\n writableStore(context.useAttachment).setState(newState, true);\n };\n\n syncAttachment(messageStore.getState());\n return messageStore.subscribe(syncAttachment);\n }, [context, messageStore, partIndex]);\n\n return context;\n};\n\nexport const MessageAttachmentProvider: FC<MessageAttachmentProviderProps> = ({\n attachmentIndex: partIndex,\n children,\n}) => {\n const context = useMessageAttachmentContext(partIndex);\n\n return (\n <AttachmentContext.Provider value={context}>\n {children}\n </AttachmentContext.Provider>\n );\n};\n","export { ComposerPrimitiveRoot as Root } from \"./ComposerRoot\";\nexport { ComposerPrimitiveInput as Input } from \"./ComposerInput\";\nexport { ComposerPrimitiveSend as Send } from \"./ComposerSend\";\nexport { ComposerPrimitiveCancel as Cancel } from \"./ComposerCancel\";\nexport { ComposerPrimitiveAddAttachment as AddAttachment } from \"./ComposerAddAttachment\";\nexport { ComposerPrimitiveAttachments as Attachments } from \"./ComposerAttachments\";\nexport { ComposerPrimitiveIf as If } from \"./ComposerIf\";\n","\"use client\";\n\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport {\n type ElementRef,\n type FormEvent,\n forwardRef,\n ComponentPropsWithoutRef,\n} from \"react\";\nimport { useComposerSend } from \"../../primitive-hooks\";\n\ntype ComposerPrimitiveRootElement = ElementRef<typeof Primitive.form>;\ntype PrimitiveFormProps = ComponentPropsWithoutRef<typeof Primitive.form>;\n\nexport type ComposerPrimitiveRootProps = PrimitiveFormProps;\n\nexport const ComposerPrimitiveRoot = forwardRef<\n ComposerPrimitiveRootElement,\n ComposerPrimitiveRootProps\n>(({ onSubmit, ...rest }, forwardedRef) => {\n const send = useComposerSend();\n\n const handleSubmit = (e: FormEvent) => {\n e.preventDefault();\n\n if (!send) return;\n send();\n };\n\n return (\n <Primitive.form\n {...rest}\n ref={forwardedRef}\n onSubmit={composeEventHandlers(onSubmit, handleSubmit)}\n />\n );\n});\n\nComposerPrimitiveRoot.displayName = \"ComposerPrimitive.Root\";\n","\"use client\";\n\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { Slot } from \"@radix-ui/react-slot\";\nimport {\n type KeyboardEvent,\n forwardRef,\n useCallback,\n useEffect,\n useRef,\n} from \"react\";\nimport TextareaAutosize, {\n type TextareaAutosizeProps,\n} from \"react-textarea-autosize\";\nimport {\n useComposer,\n useComposerStore,\n} from \"../../context/react/ComposerContext\";\nimport { useThread, useThreadStore } from \"../../context/react/ThreadContext\";\nimport { useEscapeKeydown } from \"@radix-ui/react-use-escape-keydown\";\nimport { useOnComposerFocus } from \"../../utils/hooks/useOnComposerFocus\";\n\nexport type ComposerPrimitiveInputProps = TextareaAutosizeProps & {\n asChild?: boolean | undefined;\n};\n\nexport const ComposerPrimitiveInput = forwardRef<\n HTMLTextAreaElement,\n ComposerPrimitiveInputProps\n>(\n (\n {\n autoFocus = false,\n asChild,\n disabled: disabledProp,\n onChange,\n onKeyDown,\n ...rest\n },\n forwardedRef,\n ) => {\n const threadStore = useThreadStore();\n const composerStore = useComposerStore();\n\n const value = useComposer((c) => {\n if (!c.isEditing) return \"\";\n return c.text;\n });\n\n const Component = asChild ? Slot : TextareaAutosize;\n\n const isDisabled = useThread((t) => t.isDisabled) ?? disabledProp ?? false;\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const ref = useComposedRefs(forwardedRef, textareaRef);\n\n useEscapeKeydown((e) => {\n const composer = composerStore.getState();\n if (composer.canCancel) {\n composer.cancel();\n e.preventDefault();\n }\n });\n\n const handleKeyPress = (e: KeyboardEvent) => {\n if (isDisabled) return;\n\n // ignore IME composition events\n if (e.nativeEvent.isComposing) return;\n\n if (e.key === \"Enter\" && e.shiftKey === false) {\n const { isRunning } = threadStore.getState();\n\n if (!isRunning) {\n e.preventDefault();\n\n textareaRef.current?.closest(\"form\")?.requestSubmit();\n }\n }\n };\n\n const autoFocusEnabled = autoFocus && !isDisabled;\n const focus = useCallback(() => {\n const textarea = textareaRef.current;\n if (!textarea || !autoFocusEnabled) return;\n\n textarea.focus({ preventScroll: true });\n textarea.setSelectionRange(\n textareaRef.current.value.length,\n textareaRef.current.value.length,\n );\n }, [autoFocusEnabled]);\n\n useEffect(() => focus(), [focus]);\n\n useOnComposerFocus(() => {\n if (composerStore.getState().type === \"thread\") {\n focus();\n }\n });\n\n return (\n <Component\n name=\"input\"\n value={value}\n {...rest}\n ref={ref}\n disabled={isDisabled}\n onChange={composeEventHandlers(onChange, (e) => {\n const composerState = composerStore.getState();\n if (!composerState.isEditing) return;\n return composerState.setText(e.target.value);\n })}\n onKeyDown={composeEventHandlers(onKeyDown, handleKeyPress)}\n />\n );\n },\n);\n\nComposerPrimitiveInput.displayName = \"ComposerPrimitive.Input\";\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerSend } from \"../../primitive-hooks\";\n\nexport type ComposerPrimitiveSendProps = ActionButtonProps<\n typeof useComposerSend\n>;\n\nexport const ComposerPrimitiveSend = createActionButton(\n \"ComposerPrimitive.Send\",\n useComposerSend,\n);\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerCancel } from \"../../primitive-hooks/composer/useComposerCancel\";\n\nexport type ComposerPrimitiveCancelProps = ActionButtonProps<\n typeof useComposerCancel\n>;\n\nexport const ComposerPrimitiveCancel = createActionButton(\n \"ComposerPrimitive.Cancel\",\n useComposerCancel,\n);\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerAddAttachment } from \"../../primitive-hooks/composer\";\n\nexport type ComposerPrimitiveAddAttachmentProps = ActionButtonProps<\n typeof useComposerAddAttachment\n>;\n\nexport const ComposerPrimitiveAddAttachment = createActionButton(\n \"ComposerPrimitive.AddAttachment\",\n useComposerAddAttachment,\n);\n","\"use client\";\n\nimport { ComponentType, type FC, memo } from \"react\";\nimport { useComposerAttachment } from \"../../context/react/AttachmentContext\";\nimport { ComposerAttachmentProvider } from \"../../context/providers/ComposerAttachmentProvider\";\nimport type { ThreadComposerAttachment } from \"../../context/stores/Attachment\";\nimport { useThreadComposer } from \"../../context/react/ThreadContext\";\n\nexport type ComposerPrimitiveAttachmentsProps = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n};\n\nconst getComponent = (\n components: ComposerPrimitiveAttachmentsProps[\"components\"],\n attachment: ThreadComposerAttachment,\n) => {\n const type = attachment.type;\n switch (type) {\n case \"image\":\n return components?.Image ?? components?.Attachment;\n case \"document\":\n return components?.Document ?? components?.Attachment;\n case \"file\":\n return components?.File ?? components?.Attachment;\n default:\n const _exhaustiveCheck: never = type;\n throw new Error(`Unknown attachment type: ${_exhaustiveCheck}`);\n }\n};\n\nconst AttachmentComponent: FC<{\n components: ComposerPrimitiveAttachmentsProps[\"components\"];\n}> = ({ components }) => {\n const Component = useComposerAttachment((a) =>\n getComponent(components, a.attachment),\n );\n\n if (!Component) return null;\n return <Component />;\n};\n\nconst ComposerAttachmentImpl: FC<\n ComposerPrimitiveAttachmentsProps & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n return (\n <ComposerAttachmentProvider attachmentIndex={attachmentIndex}>\n <AttachmentComponent components={components} />\n </ComposerAttachmentProvider>\n );\n};\n\nconst ComposerAttachment = memo(\n ComposerAttachmentImpl,\n (prev, next) =>\n prev.attachmentIndex === next.attachmentIndex &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.Document === next.components?.Document &&\n prev.components?.File === next.components?.File &&\n prev.components?.Attachment === next.components?.Attachment,\n);\n\nexport const ComposerPrimitiveAttachments: FC<\n ComposerPrimitiveAttachmentsProps\n> = ({ components }) => {\n const attachmentsCount = useThreadComposer((s) => s.attachments.length);\n\n return Array.from({ length: attachmentsCount }, (_, index) => (\n <ComposerAttachment\n key={index}\n attachmentIndex={index}\n components={components}\n />\n ));\n};\n\nComposerPrimitiveAttachments.displayName = \"ComposerPrimitive.Attachments\";\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport type { ThreadComposerState } from \"../stores\";\nimport { ComposerAttachmentState } from \"../stores/Attachment\";\nimport {\n AttachmentContext,\n AttachmentContextValue,\n} from \"../react/AttachmentContext\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport { useThreadComposerStore } from \"../react/ThreadContext\";\n\ntype ComposerAttachmentProviderProps = PropsWithChildren<{\n attachmentIndex: number;\n}>;\n\nconst getAttachment = (\n { attachments }: ThreadComposerState,\n useAttachment: AttachmentContextValue[\"useAttachment\"] | undefined,\n partIndex: number,\n) => {\n const attachment = attachments[partIndex];\n if (!attachment) return null;\n\n // if the attachment is the same, don't update\n const currentState = useAttachment?.getState();\n if (currentState && currentState.attachment === attachment) return null;\n\n return Object.freeze({ attachment });\n};\n\nconst useComposerAttachmentContext = (partIndex: number) => {\n const threadComposerStore = useThreadComposerStore();\n const [context] = useState<AttachmentContextValue & { type: \"composer\" }>(\n () => {\n const useAttachment = create<ComposerAttachmentState>(\n () =>\n getAttachment(threadComposerStore.getState(), undefined, partIndex)!,\n );\n\n return { type: \"composer\", useAttachment };\n },\n );\n\n useEffect(() => {\n const syncAttachment = (composer: ThreadComposerState) => {\n const newState = getAttachment(\n composer,\n context.useAttachment,\n partIndex,\n );\n if (!newState) return;\n writableStore(context.useAttachment).setState(newState, true);\n };\n\n syncAttachment(threadComposerStore.getState());\n return threadComposerStore.subscribe(syncAttachment);\n }, [context, threadComposerStore, partIndex]);\n\n return context;\n};\n\nexport const ComposerAttachmentProvider: FC<\n ComposerAttachmentProviderProps\n> = ({ attachmentIndex: partIndex, children }) => {\n const context = useComposerAttachmentContext(partIndex);\n\n return (\n <AttachmentContext.Provider value={context}>\n {children}\n </AttachmentContext.Provider>\n );\n};\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport {\n UseComposerIfProps,\n useComposerIf,\n} from \"../../primitive-hooks/composer/useComposerIf\";\n\nexport type ComposerPrimitiveIfProps = PropsWithChildren<UseComposerIfProps>;\n\nexport const ComposerPrimitiveIf: FC<ComposerPrimitiveIfProps> = ({\n children,\n ...query\n}) => {\n const result = useComposerIf(query);\n return result ? children : null;\n};\n\nComposerPrimitiveIf.displayName = \"ComposerPrimitive.If\";\n","export { ContentPartPrimitiveText as Text } from \"./ContentPartText\";\nexport { ContentPartPrimitiveImage as Image } from \"./ContentPartImage\";\nexport { ContentPartPrimitiveDisplay as Display } from \"./ContentPartDisplay\";\nexport { ContentPartPrimitiveInProgress as InProgress } from \"./ContentPartInProgress\";\n","export { ThreadPrimitiveRoot as Root } from \"./ThreadRoot\";\nexport { ThreadPrimitiveEmpty as Empty } from \"./ThreadEmpty\";\nexport { ThreadPrimitiveIf as If } from \"./ThreadIf\";\nexport { ThreadPrimitiveViewport as Viewport } from \"./ThreadViewport\";\nexport { ThreadPrimitiveMessages as Messages } from \"./ThreadMessages\";\nexport { ThreadPrimitiveScrollToBottom as ScrollToBottom } from \"./ThreadScrollToBottom\";\nexport { ThreadPrimitiveSuggestion as Suggestion } from \"./ThreadSuggestion\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\n\ntype ThreadPrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type ThreadPrimitiveRootProps = PrimitiveDivProps;\n\nexport const ThreadPrimitiveRoot = forwardRef<\n ThreadPrimitiveRootElement,\n ThreadPrimitiveRootProps\n>((props, ref) => {\n return <Primitive.div {...props} ref={ref} />;\n});\n\nThreadPrimitiveRoot.displayName = \"ThreadPrimitive.Root\";\n","\"use client\";\n\nimport type { FC, ReactNode } from \"react\";\nimport { useThreadEmpty } from \"../../primitive-hooks\";\n\nexport type ThreadPrimitiveEmptyProps = {\n children: ReactNode;\n};\n\nexport const ThreadPrimitiveEmpty: FC<ThreadPrimitiveEmptyProps> = ({\n children,\n}) => {\n const empty = useThreadEmpty();\n return empty ? children : null;\n};\n\nThreadPrimitiveEmpty.displayName = \"ThreadPrimitive.Empty\";\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport {\n UseThreadIfProps,\n useThreadIf,\n} from \"../../primitive-hooks/thread/useThreadIf\";\n\nexport type ThreadPrimitiveIfProps = PropsWithChildren<UseThreadIfProps>;\n\nexport const ThreadPrimitiveIf: FC<ThreadPrimitiveIfProps> = ({\n children,\n ...query\n}) => {\n const result = useThreadIf(query);\n return result ? children : null;\n};\n\nThreadPrimitiveIf.displayName = \"ThreadPrimitive.If\";\n","\"use client\";\n\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport {\n UseThreadViewportAutoScrollProps,\n useThreadViewportAutoScroll,\n} from \"../../primitive-hooks/thread/useThreadViewportAutoScroll\";\n\ntype ThreadPrimitiveViewportElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type ThreadPrimitiveViewportProps = PrimitiveDivProps &\n UseThreadViewportAutoScrollProps;\n\nexport const ThreadPrimitiveViewport = forwardRef<\n ThreadPrimitiveViewportElement,\n ThreadPrimitiveViewportProps\n>(({ autoScroll, children, ...rest }, forwardedRef) => {\n const autoScrollRef = useThreadViewportAutoScroll<HTMLDivElement>({\n autoScroll,\n });\n\n const ref = useComposedRefs(forwardedRef, autoScrollRef);\n\n return (\n <Primitive.div {...rest} ref={ref}>\n {children}\n </Primitive.div>\n );\n});\n\nThreadPrimitiveViewport.displayName = \"ThreadPrimitive.Viewport\";\n","\"use client\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { useRef } from \"react\";\nimport { useThreadViewportStore } from \"../../context/react/ThreadContext\";\nimport { useOnResizeContent } from \"../../utils/hooks/useOnResizeContent\";\nimport { useOnScrollToBottom } from \"../../utils/hooks/useOnScrollToBottom\";\nimport { useManagedRef } from \"../../utils/hooks/useManagedRef\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\n\nexport type UseThreadViewportAutoScrollProps = {\n autoScroll?: boolean | undefined;\n};\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll = true,\n}: UseThreadViewportAutoScrollProps) => {\n const divRef = useRef<TElement>(null);\n\n const threadViewportStore = useThreadViewportStore();\n\n const lastScrollTop = useRef<number>(0);\n\n // bug: when ScrollToBottom's button changes its disabled state, the scroll stops\n // fix: delay the state change until the scroll is done\n const isScrollingToBottomRef = useRef(false);\n\n const scrollToBottom = (behavior: ScrollBehavior) => {\n const div = divRef.current;\n if (!div || !autoScroll) return;\n\n isScrollingToBottomRef.current = true;\n div.scrollTo({ top: div.scrollHeight, behavior });\n };\n\n const handleScroll = () => {\n const div = divRef.current;\n if (!div) return;\n\n const isAtBottom = threadViewportStore.getState().isAtBottom;\n const newIsAtBottom =\n div.scrollHeight - div.scrollTop <= div.clientHeight + 1; // TODO figure out why +1 is needed\n\n if (!newIsAtBottom && lastScrollTop.current < div.scrollTop) {\n // ignore scroll down\n } else {\n if (newIsAtBottom) {\n isScrollingToBottomRef.current = false;\n }\n\n if (newIsAtBottom !== isAtBottom) {\n writableStore(threadViewportStore).setState({\n isAtBottom: newIsAtBottom,\n });\n }\n }\n\n lastScrollTop.current = div.scrollTop;\n };\n\n const resizeRef = useOnResizeContent(() => {\n if (\n isScrollingToBottomRef.current ||\n threadViewportStore.getState().isAtBottom\n ) {\n scrollToBottom(\"instant\");\n }\n\n handleScroll();\n });\n\n const scrollRef = useManagedRef<HTMLElement>((el) => {\n el.addEventListener(\"scroll\", handleScroll);\n return () => {\n el.removeEventListener(\"scroll\", handleScroll);\n };\n });\n\n const autoScrollRef = useComposedRefs<TElement>(resizeRef, scrollRef, divRef);\n\n useOnScrollToBottom(() => {\n scrollToBottom(\"auto\");\n });\n\n return autoScrollRef;\n};\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useCallback } from \"react\";\nimport { useManagedRef } from \"./useManagedRef\";\n\nexport const useOnResizeContent = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n\n const refCallback = useCallback(\n (el: HTMLElement) => {\n const resizeObserver = new ResizeObserver(() => {\n callbackRef();\n });\n\n const mutationObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n resizeObserver.observe(node);\n }\n }\n\n for (const node of mutation.removedNodes) {\n if (node instanceof Element) {\n resizeObserver.unobserve(node);\n }\n }\n }\n\n callbackRef();\n });\n\n resizeObserver.observe(el);\n mutationObserver.observe(el, { childList: true });\n\n // Observe existing children\n for (const child of el.children) {\n resizeObserver.observe(child);\n }\n\n return () => {\n resizeObserver.disconnect();\n mutationObserver.disconnect();\n };\n },\n [callbackRef],\n );\n\n return useManagedRef(refCallback);\n};\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useEffect } from \"react\";\nimport { useThreadViewportStore } from \"../../context/react/ThreadContext\";\n\nexport const useOnScrollToBottom = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n const threadViewportStore = useThreadViewportStore();\n\n useEffect(() => {\n return threadViewportStore.getState().onScrollToBottom(() => {\n callbackRef();\n });\n }, [threadViewportStore, callbackRef]);\n};\n","\"use client\";\n\nimport { type ComponentType, type FC, memo } from \"react\";\nimport { useThreadMessages } from \"../../context/react/ThreadContext\";\nimport { MessageProvider } from \"../../context/providers/MessageProvider\";\nimport { useEditComposer, useMessage } from \"../../context\";\nimport { ThreadMessage as ThreadMessageType } from \"../../types\";\n\nexport type ThreadPrimitiveMessagesProps = {\n components:\n | {\n Message: ComponentType;\n EditComposer?: ComponentType | undefined;\n UserEditComposer?: ComponentType | undefined;\n AssistantEditComposer?: ComponentType | undefined;\n SystemEditComposer?: ComponentType | undefined;\n UserMessage?: ComponentType | undefined;\n AssistantMessage?: ComponentType | undefined;\n SystemMessage?: ComponentType | undefined;\n }\n | {\n Message?: ComponentType | undefined;\n EditComposer?: ComponentType | undefined;\n UserEditComposer?: ComponentType | undefined;\n AssistantEditComposer?: ComponentType | undefined;\n SystemEditComposer?: ComponentType | undefined;\n UserMessage: ComponentType;\n AssistantMessage: ComponentType;\n SystemMessage?: ComponentType | undefined;\n };\n};\n\nconst isComponentsSame = (\n prev: ThreadPrimitiveMessagesProps[\"components\"],\n next: ThreadPrimitiveMessagesProps[\"components\"],\n) => {\n return (\n prev.Message === next.Message &&\n prev.EditComposer === next.EditComposer &&\n prev.UserEditComposer === next.UserEditComposer &&\n prev.AssistantEditComposer === next.AssistantEditComposer &&\n prev.SystemEditComposer === next.SystemEditComposer &&\n prev.UserMessage === next.UserMessage &&\n prev.AssistantMessage === next.AssistantMessage &&\n prev.SystemMessage === next.SystemMessage\n );\n};\n\nconst DEFAULT_SYSTEM_MESSAGE = () => null;\n\nconst getComponent = (\n components: ThreadPrimitiveMessagesProps[\"components\"],\n role: ThreadMessageType[\"role\"],\n isEditing: boolean,\n) => {\n switch (role) {\n case \"user\":\n if (isEditing) {\n return (\n components.UserEditComposer ??\n components.EditComposer ??\n components.UserMessage ??\n (components.Message as ComponentType)\n );\n } else {\n return components.UserMessage ?? (components.Message as ComponentType);\n }\n case \"assistant\":\n if (isEditing) {\n return (\n components.AssistantEditComposer ??\n components.EditComposer ??\n components.AssistantMessage ??\n (components.Message as ComponentType)\n );\n } else {\n return (\n components.AssistantMessage ?? (components.Message as ComponentType)\n );\n }\n case \"system\":\n if (isEditing) {\n return (\n components.SystemEditComposer ??\n components.EditComposer ??\n components.SystemMessage ??\n (components.Message as ComponentType)\n );\n } else {\n return components.SystemMessage ?? DEFAULT_SYSTEM_MESSAGE;\n }\n default:\n const _exhaustiveCheck: never = role;\n throw new Error(`Unknown message role: ${_exhaustiveCheck}`);\n }\n};\n\ntype ThreadMessageComponentProps = {\n components: ThreadPrimitiveMessagesProps[\"components\"];\n};\n\nconst ThreadMessageComponent: FC<ThreadMessageComponentProps> = ({\n components,\n}) => {\n const role = useMessage((m) => m.message.role);\n const isEditing = useEditComposer((c) => c.isEditing);\n const Component = getComponent(components, role, isEditing);\n\n return <Component />;\n};\n\ntype ThreadMessageProps = {\n messageIndex: number;\n components: ThreadPrimitiveMessagesProps[\"components\"];\n};\n\nconst ThreadMessageImpl: FC<ThreadMessageProps> = ({\n messageIndex,\n components,\n}) => {\n return (\n <MessageProvider messageIndex={messageIndex}>\n <ThreadMessageComponent components={components} />\n </MessageProvider>\n );\n};\n\nconst ThreadMessage = memo(\n ThreadMessageImpl,\n (prev, next) =>\n prev.messageIndex === next.messageIndex &&\n isComponentsSame(prev.components, next.components),\n);\n\nexport const ThreadPrimitiveMessagesImpl: FC<ThreadPrimitiveMessagesProps> = ({\n components,\n}) => {\n const messagesLength = useThreadMessages((t) => t.length);\n if (messagesLength === 0) return null;\n\n return Array.from({ length: messagesLength }, (_, index) => (\n <ThreadMessage key={index} messageIndex={index} components={components} />\n ));\n};\n\nThreadPrimitiveMessagesImpl.displayName = \"ThreadPrimitive.Messages\";\n\nexport const ThreadPrimitiveMessages = memo(\n ThreadPrimitiveMessagesImpl,\n (prev, next) => isComponentsSame(prev.components, next.components),\n);\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport type {\n CoreUserContentPart,\n ThreadMessage,\n} from \"../../types/AssistantTypes\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { MessageContext } from \"../react/MessageContext\";\nimport type { MessageContextValue } from \"../react/MessageContext\";\nimport {\n useThreadActionsStore,\n useThreadMessagesStore,\n} from \"../react/ThreadContext\";\nimport type { MessageState } from \"../stores/Message\";\nimport { makeEditComposerStore } from \"../stores/EditComposer\";\nimport { makeMessageUtilsStore } from \"../stores/MessageUtils\";\nimport { ThreadMessagesState } from \"../stores/ThreadMessages\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype MessageProviderProps = PropsWithChildren<{\n messageIndex: number;\n}>;\n\nconst getIsLast = (messages: ThreadMessagesState, message: ThreadMessage) => {\n return messages[messages.length - 1]?.id === message.id;\n};\n\nconst getMessageState = (\n messages: ThreadMessagesState,\n getBranches: (messageId: string) => readonly string[],\n useMessage: MessageContextValue[\"useMessage\"] | undefined,\n messageIndex: number,\n) => {\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const message = messages[messageIndex];\n if (!message) return null;\n\n const isLast = getIsLast(messages, message);\n const branches = getBranches(message.id);\n\n // if the message is the same, don't update\n const currentState = useMessage?.getState();\n if (\n currentState &&\n currentState.message === message &&\n currentState.parentId === parentId &&\n currentState.branches === branches &&\n currentState.isLast === isLast\n )\n return null;\n\n return Object.freeze({\n message,\n parentId,\n branches,\n isLast,\n });\n};\n\nconst useMessageContext = (messageIndex: number) => {\n const threadMessagesStore = useThreadMessagesStore();\n const threadActionsStore = useThreadActionsStore();\n const [context] = useState<MessageContextValue>(() => {\n const useMessage = create<MessageState>(\n () =>\n getMessageState(\n threadMessagesStore.getState(),\n threadActionsStore.getState().getBranches,\n undefined,\n messageIndex,\n )!,\n );\n const useMessageUtils = makeMessageUtilsStore();\n const useEditComposer = makeEditComposerStore({\n onEdit: () => {\n const message = useMessage.getState().message;\n const text = getThreadMessageText(message);\n\n return text;\n },\n onSend: (text) => {\n const { message, parentId } = useMessage.getState();\n const previousText = getThreadMessageText(message);\n if (previousText === text) return;\n\n const nonTextParts = message.content.filter(\n (part): part is CoreUserContentPart =>\n part.type !== \"text\" && part.type !== \"ui\",\n );\n\n // TODO fix types here\n threadActionsStore.getState().append({\n parentId,\n role: message.role,\n content: [{ type: \"text\", text }, ...nonTextParts] as any,\n attachments: (message as any).attachments,\n });\n },\n });\n\n return { useMessage, useMessageUtils, useEditComposer };\n });\n\n useEffect(() => {\n const syncMessage = (thread: ThreadMessagesState) => {\n const newState = getMessageState(\n thread,\n threadActionsStore.getState().getBranches,\n context.useMessage,\n messageIndex,\n );\n if (!newState) return;\n writableStore(context.useMessage).setState(newState, true);\n };\n\n syncMessage(threadMessagesStore.getState());\n\n return threadMessagesStore.subscribe(syncMessage);\n }, [threadMessagesStore, threadActionsStore, context, messageIndex]);\n\n return context;\n};\n\nexport const MessageProvider: FC<MessageProviderProps> = ({\n messageIndex,\n children,\n}) => {\n const context = useMessageContext(messageIndex);\n\n return (\n <MessageContext.Provider value={context}>\n {children}\n </MessageContext.Provider>\n );\n};\n","import { create, UseBoundStore } from \"zustand\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\n\nexport type EditComposerState = Readonly<{\n type: \"edit\";\n\n /** @deprecated Use `text` instead. This will be removed in 0.6.0. */\n value: string;\n /** @deprecated Use `setText` instead. This will be removed in 0.6.0. */\n setValue: (value: string) => void;\n\n text: string;\n setText: (value: string) => void;\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n\n edit: () => void;\n send: () => void;\n cancel: () => void;\n}>;\n\nexport const makeEditComposerStore = ({\n onEdit,\n onSend,\n}: {\n onEdit: () => string;\n onSend: (text: string) => void;\n}): UseBoundStore<ReadonlyStore<EditComposerState>> =>\n create<EditComposerState>()((set, get) => ({\n type: \"edit\",\n\n get value() {\n return get().text;\n },\n setValue(value) {\n get().setText(value);\n },\n\n text: \"\",\n setText: (text) => {\n set({ text, isEmpty: text.trim().length === 0 });\n },\n\n canCancel: false,\n isEditing: false,\n isEmpty: true,\n\n edit: () => {\n const text = onEdit();\n set({\n isEditing: true,\n canCancel: true,\n isEmpty: text.trim().length === 0,\n text,\n });\n },\n send: () => {\n const text = get().text;\n set({ isEditing: false, canCancel: false });\n onSend(text);\n },\n cancel: () => {\n set({ isEditing: false, canCancel: false });\n },\n }));\n","import { create } from \"zustand\";\nimport { SpeechSynthesisAdapter } from \"../../runtimes/speech/SpeechAdapterTypes\";\n\nexport type MessageUtilsState = Readonly<{\n isCopied: boolean;\n setIsCopied: (value: boolean) => void;\n isHovering: boolean;\n setIsHovering: (value: boolean) => void;\n\n isSpeaking: boolean;\n stopSpeaking: () => void;\n addUtterance: (utterance: SpeechSynthesisAdapter.Utterance) => void;\n}>;\n\nexport const makeMessageUtilsStore = () =>\n create<MessageUtilsState>((set) => {\n let utterance: SpeechSynthesisAdapter.Utterance | null = null;\n return {\n isCopied: false,\n setIsCopied: (value) => {\n set({ isCopied: value });\n },\n isHovering: false,\n setIsHovering: (value) => {\n set({ isHovering: value });\n },\n isSpeaking: false,\n stopSpeaking: () => {\n utterance?.cancel();\n },\n addUtterance: (utt) => {\n utterance = utt;\n set({ isSpeaking: true });\n utt.onEnd(() => {\n set({ isSpeaking: false });\n });\n },\n };\n });\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadScrollToBottom } from \"../../primitive-hooks/thread/useThreadScrollToBottom\";\n\nexport type ThreadPrimitiveScrollToBottomProps = ActionButtonProps<\n typeof useThreadScrollToBottom\n>;\n\nexport const ThreadPrimitiveScrollToBottom = createActionButton(\n \"ThreadPrimitive.ScrollToBottom\",\n useThreadScrollToBottom,\n);\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadSuggestion } from \"../../primitive-hooks/thread/useThreadSuggestion\";\n\nexport type ThreadPrimitiveSuggestionProps = ActionButtonProps<\n typeof useThreadSuggestion\n>;\n\nexport const ThreadPrimitiveSuggestion = createActionButton(\n \"ThreadPrimitive.Suggestion\",\n useThreadSuggestion,\n [\"prompt\", \"autoSend\", \"method\"],\n);\n","\"use client\";\n\nimport {\n ComponentType,\n FC,\n PropsWithChildren,\n ReactNode,\n createContext,\n useContext,\n} from \"react\";\n\nimport { AvatarProps } from \"./base/avatar\";\nimport { TextContentPartComponent, ToolCallContentPartProps } from \"../types\";\nimport { AssistantRuntime } from \"../runtimes\";\nimport { AssistantRuntimeProvider } from \"../context\";\nimport { AssistantToolUI } from \"../model-config\";\nimport { useAssistantRuntimeStore as useAssistantActionsStore } from \"../context/react/AssistantContext\";\n\nexport type SuggestionConfig = {\n text?: ReactNode;\n prompt: string;\n};\n\nexport type ThreadWelcomeConfig = {\n message?: string | null | undefined;\n suggestions?: SuggestionConfig[] | undefined;\n};\n\nexport type UserMessageConfig = {\n allowEdit?: boolean | undefined;\n};\n\nexport type AssistantMessageConfig = {\n allowReload?: boolean | undefined;\n allowCopy?: boolean | undefined;\n allowSpeak?: boolean | undefined;\n components?:\n | {\n Text?: TextContentPartComponent | undefined;\n ToolFallback?: ComponentType<ToolCallContentPartProps> | undefined;\n }\n | undefined;\n};\n\nexport type BranchPickerConfig = {\n allowBranchPicker?: boolean | undefined;\n};\n\nexport type ComposerConfig = {\n allowAttachments?: boolean | undefined;\n};\n\nexport type StringsConfig = {\n assistantModal?: {\n open: {\n button: {\n tooltip?: string | undefined;\n };\n };\n closed: {\n button: {\n tooltip?: string | undefined;\n };\n };\n };\n thread?: {\n scrollToBottom?: {\n tooltip?: string | undefined;\n };\n };\n userMessage?: {\n edit?: {\n tooltip?: string | undefined;\n };\n };\n assistantMessage?: {\n reload?: {\n tooltip?: string | undefined;\n };\n copy?: {\n tooltip?: string | undefined;\n };\n speak?: {\n tooltip?: string | undefined;\n stop?: {\n tooltip?: string | undefined;\n };\n };\n };\n branchPicker?: {\n previous?: {\n tooltip?: string | undefined;\n };\n next?: {\n tooltip?: string | undefined;\n };\n };\n composer?: {\n send?:\n | {\n tooltip?: string | undefined;\n }\n | undefined;\n cancel?:\n | {\n tooltip?: string | undefined;\n }\n | undefined;\n addAttachment?:\n | {\n tooltip?: string | undefined;\n }\n | undefined;\n removeAttachment?: {\n tooltip?: string | undefined;\n };\n input?: {\n placeholder?: string | undefined;\n };\n };\n editComposer?: {\n send?: {\n label?: string | undefined;\n };\n cancel?: {\n label?: string | undefined;\n };\n };\n code?: {\n header?: {\n copy?: {\n tooltip?: string | undefined;\n };\n };\n };\n};\n\nconst ThreadConfigContext = createContext<ThreadConfig>({});\n\nexport type ThreadConfig = {\n runtime?: AssistantRuntime;\n\n assistantAvatar?: AvatarProps;\n\n welcome?: ThreadWelcomeConfig;\n assistantMessage?: AssistantMessageConfig;\n userMessage?: UserMessageConfig;\n\n branchPicker?: BranchPickerConfig;\n\n composer?: ComposerConfig;\n\n strings?: StringsConfig;\n\n tools?: AssistantToolUI[]; // TODO add AssistantTool support\n};\n\nexport const useThreadConfig = (): Omit<ThreadConfig, \"runtime\"> => {\n return useContext(ThreadConfigContext);\n};\n\nexport type ThreadConfigProviderProps = PropsWithChildren<{\n config?: ThreadConfig | undefined;\n}>;\n\nexport const ThreadConfigProvider: FC<ThreadConfigProviderProps> = ({\n children,\n config,\n}) => {\n const hasAssistant = !!useAssistantActionsStore({ optional: true });\n\n const configProvider =\n config && Object.keys(config ?? {}).length > 0 ? (\n <ThreadConfigContext.Provider value={config}>\n {children}\n </ThreadConfigContext.Provider>\n ) : (\n <>{children}</>\n );\n if (!config?.runtime) return configProvider;\n\n if (hasAssistant) {\n throw new Error(\n \"You provided a runtime to <Thread> while simulataneously using <AssistantRuntimeProvider>. This is not allowed.\",\n );\n }\n return (\n <AssistantRuntimeProvider runtime={config.runtime}>\n {configProvider}\n </AssistantRuntimeProvider>\n );\n};\n\nThreadConfigProvider.displayName = \"ThreadConfigProvider\";\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\nimport {\n AudioLinesIcon,\n CheckIcon,\n CopyIcon,\n RefreshCwIcon,\n StopCircleIcon,\n} from \"lucide-react\";\nimport { ActionBarPrimitive, MessagePrimitive } from \"../primitives\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { useThread } from \"../context\";\n\nconst useAllowCopy = (ensureCapability = false) => {\n const { assistantMessage: { allowCopy = true } = {} } = useThreadConfig();\n const copySupported = useThread((t) => t.capabilities.unstable_copy);\n return allowCopy && (!ensureCapability || copySupported);\n};\n\nconst useAllowSpeak = (ensureCapability = false) => {\n const { assistantMessage: { allowSpeak = true } = {} } = useThreadConfig();\n const speakSupported = useThread((t) => t.capabilities.speak);\n return allowSpeak && (!ensureCapability || speakSupported);\n};\n\nconst useAllowReload = (ensureCapability = false) => {\n const { assistantMessage: { allowReload = true } = {} } = useThreadConfig();\n const reloadSupported = useThread((t) => t.capabilities.reload);\n return allowReload && (!ensureCapability || reloadSupported);\n};\n\nconst AssistantActionBar: FC = () => {\n const allowCopy = useAllowCopy(true);\n const allowReload = useAllowReload(true);\n const allowSpeak = useAllowSpeak(true);\n if (!allowCopy && !allowReload && !allowSpeak) return null;\n return (\n <AssistantActionBarRoot\n hideWhenRunning\n autohide=\"not-last\"\n autohideFloat=\"single-branch\"\n >\n {allowSpeak && <AssistantActionBarSpeechControl />}\n {allowCopy && <AssistantActionBarCopy />}\n {allowReload && <AssistantActionBarReload />}\n </AssistantActionBarRoot>\n );\n};\n\nAssistantActionBar.displayName = \"AssistantActionBar\";\n\nconst AssistantActionBarRoot = withDefaults(ActionBarPrimitive.Root, {\n className: \"aui-assistant-action-bar-root\",\n});\n\nAssistantActionBarRoot.displayName = \"AssistantActionBarRoot\";\n\nconst AssistantActionBarCopy = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: { copy: { tooltip = \"Copy\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n return (\n <ActionBarPrimitive.Copy asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? (\n <>\n <MessagePrimitive.If copied>\n <CheckIcon />\n </MessagePrimitive.If>\n <MessagePrimitive.If copied={false}>\n <CopyIcon />\n </MessagePrimitive.If>\n </>\n )}\n </TooltipIconButton>\n </ActionBarPrimitive.Copy>\n );\n});\n\nAssistantActionBarCopy.displayName = \"AssistantActionBarCopy\";\n\nconst AssistantActionBarSpeechControl: FC = () => {\n return (\n <>\n <MessagePrimitive.If speaking={false}>\n <AssistantActionBarSpeak />\n </MessagePrimitive.If>\n <MessagePrimitive.If speaking>\n <AssistantActionBarStopSpeaking />\n </MessagePrimitive.If>\n </>\n );\n};\n\nconst AssistantActionBarSpeak = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: { speak: { tooltip = \"Read aloud\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowSpeak = useAllowSpeak();\n\n return (\n <ActionBarPrimitive.Speak disabled={!allowSpeak} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <AudioLinesIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.Speak>\n );\n});\n\nAssistantActionBarSpeak.displayName = \"AssistantActionBarSpeak\";\n\nconst AssistantActionBarStopSpeaking = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: {\n speak: { stop: { tooltip: stopTooltip = \"Stop\" } = {} } = {},\n } = {},\n } = {},\n } = useThreadConfig();\n const allowSpeak = useAllowSpeak();\n\n return (\n <ActionBarPrimitive.StopSpeaking disabled={!allowSpeak} asChild>\n <TooltipIconButton tooltip={stopTooltip} {...props} ref={ref}>\n {props.children ?? <StopCircleIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.StopSpeaking>\n );\n});\n\nAssistantActionBarStopSpeaking.displayName = \"AssistantActionBarStopSpeaking\";\n\nconst AssistantActionBarReload = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: { reload: { tooltip = \"Refresh\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowReload = useAllowReload();\n return (\n <ActionBarPrimitive.Reload disabled={!allowReload} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n <RefreshCwIcon />\n </TooltipIconButton>\n </ActionBarPrimitive.Reload>\n );\n});\n\nAssistantActionBarReload.displayName = \"AssistantActionBarReload\";\n\nconst exports = {\n Root: AssistantActionBarRoot,\n Reload: AssistantActionBarReload,\n Copy: AssistantActionBarCopy,\n Speak: AssistantActionBarSpeak,\n StopSpeaking: AssistantActionBarStopSpeaking,\n SpeechControl: AssistantActionBarSpeechControl,\n};\n\nexport default Object.assign(\n AssistantActionBar,\n exports,\n) as typeof AssistantActionBar & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, useMemo, type FC } from \"react\";\nimport { MessagePrimitive, MessagePrimitiveContentProps } from \"../primitives\";\nimport BranchPicker from \"./branch-picker\";\nimport { Avatar } from \"./base/avatar\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport AssistantActionBar from \"./assistant-action-bar\";\nimport ContentPart from \"./content-part\";\n\nconst AssistantMessage: FC = () => {\n return (\n <AssistantMessageRoot>\n <AssistantMessageAvatar />\n <AssistantMessageContent />\n <BranchPicker />\n <AssistantActionBar />\n </AssistantMessageRoot>\n );\n};\n\nAssistantMessage.displayName = \"AssistantMessage\";\n\nconst AssistantMessageAvatar: FC = () => {\n const { assistantAvatar: avatar = { fallback: \"A\" } } = useThreadConfig();\n return <Avatar {...avatar} />;\n};\n\nconst AssistantMessageRoot = withDefaults(MessagePrimitive.Root, {\n className: \"aui-assistant-message-root\",\n});\n\nAssistantMessageRoot.displayName = \"AssistantMessageRoot\";\n\nconst AssistantMessageContentWrapper = withDefaults(\"div\", {\n className: \"aui-assistant-message-content\",\n});\n\nexport type AssistantMessageContentProps = MessagePrimitiveContentProps &\n ComponentPropsWithoutRef<\"div\">;\n\nconst AssistantMessageContent = forwardRef<\n HTMLDivElement,\n AssistantMessageContentProps\n>(({ components: componentsProp, ...rest }, ref) => {\n const { tools, assistantMessage: { components = {} } = {} } =\n useThreadConfig();\n\n const toolsComponents = useMemo(\n () => ({\n by_name: !tools\n ? undefined\n : Object.fromEntries(\n tools.map((t) => [\n t.unstable_tool.toolName,\n t.unstable_tool.render,\n ]),\n ),\n Fallback: components.ToolFallback,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [...(tools ?? []), components.ToolFallback],\n );\n\n return (\n <AssistantMessageContentWrapper {...rest} ref={ref}>\n <MessagePrimitive.Content\n components={{\n ...componentsProp,\n Text: componentsProp?.Text ?? components.Text ?? ContentPart.Text,\n tools: toolsComponents,\n }}\n />\n </AssistantMessageContentWrapper>\n );\n});\n\nAssistantMessageContent.displayName = \"AssistantMessageContent\";\n\nconst exports = {\n Root: AssistantMessageRoot,\n Avatar: AssistantMessageAvatar,\n Content: AssistantMessageContent,\n};\n\nexport default Object.assign(\n AssistantMessage,\n exports,\n) as typeof AssistantMessage & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\nimport { ChevronLeftIcon, ChevronRightIcon } from \"lucide-react\";\n\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { BranchPickerPrimitive } from \"../primitives\";\nimport { useThread } from \"../context\";\n\nconst useAllowBranchPicker = (ensureCapability = false) => {\n const { branchPicker: { allowBranchPicker = true } = {} } = useThreadConfig();\n const branchPickerSupported = useThread((t) => t.capabilities.edit);\n return allowBranchPicker && (!ensureCapability || branchPickerSupported);\n};\n\nconst BranchPicker: FC = () => {\n const allowBranchPicker = useAllowBranchPicker();\n if (!allowBranchPicker) return null;\n return (\n <BranchPickerRoot hideWhenSingleBranch>\n <BranchPickerPrevious />\n <BranchPickerState />\n <BranchPickerNext />\n </BranchPickerRoot>\n );\n};\n\nBranchPicker.displayName = \"BranchPicker\";\n\nconst BranchPickerRoot = withDefaults(BranchPickerPrimitive.Root, {\n className: \"aui-branch-picker-root\",\n});\n\nBranchPickerRoot.displayName = \"BranchPickerRoot\";\n\nconst BranchPickerPrevious = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n branchPicker: { previous: { tooltip = \"Previous\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowBranchPicker = useAllowBranchPicker();\n return (\n <BranchPickerPrimitive.Previous disabled={!allowBranchPicker} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ChevronLeftIcon />}\n </TooltipIconButton>\n </BranchPickerPrimitive.Previous>\n );\n});\n\nBranchPickerPrevious.displayName = \"BranchPickerPrevious\";\n\nconst BranchPickerStateWrapper = withDefaults(\"span\", {\n className: \"aui-branch-picker-state\",\n});\n\nconst BranchPickerState = forwardRef<\n HTMLSpanElement,\n ComponentPropsWithoutRef<\"span\">\n>((props, ref) => {\n return (\n <BranchPickerStateWrapper {...props} ref={ref}>\n <BranchPickerPrimitive.Number /> / <BranchPickerPrimitive.Count />\n </BranchPickerStateWrapper>\n );\n});\n\nBranchPickerState.displayName = \"BranchPickerState\";\n\nconst BranchPickerNext = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { branchPicker: { next: { tooltip = \"Next\" } = {} } = {} } = {},\n } = useThreadConfig();\n const allowBranchPicker = useAllowBranchPicker();\n return (\n <BranchPickerPrimitive.Next disabled={!allowBranchPicker} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ChevronRightIcon />}\n </TooltipIconButton>\n </BranchPickerPrimitive.Next>\n );\n});\n\nBranchPickerNext.displayName = \"BranchPickerNext\";\n\nconst exports = {\n Root: BranchPickerRoot,\n Previous: BranchPickerPrevious,\n Next: BranchPickerNext,\n};\n\nexport default Object.assign(BranchPicker, exports) as typeof BranchPicker &\n typeof exports;\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport * as AvatarPrimitive from \"@radix-ui/react-avatar\";\n\nimport { withDefaults } from \"../utils/withDefaults\";\n\nexport type AvatarProps = {\n src?: string | undefined;\n alt?: string | undefined;\n fallback?: string | undefined;\n};\n\nexport const Avatar: FC<AvatarProps> = ({ src, alt, fallback }) => {\n if (src == null && fallback == null) return null;\n\n return (\n <AvatarRoot>\n {src != null && <AvatarImage src={src} alt={alt} />}\n {fallback != null && <AvatarFallback>{fallback}</AvatarFallback>}\n </AvatarRoot>\n );\n};\n\nAvatar.displayName = \"Avatar\";\n\nexport const AvatarRoot = withDefaults(AvatarPrimitive.Root, {\n className: \"aui-avatar-root\",\n});\n\nAvatarRoot.displayName = \"AvatarRoot\";\n\nexport const AvatarImage = withDefaults(AvatarPrimitive.Image, {\n className: \"aui-avatar-image\",\n});\n\nAvatarImage.displayName = \"AvatarImage\";\n\nexport const AvatarFallback = withDefaults(AvatarPrimitive.Fallback, {\n className: \"aui-avatar-fallback\",\n});\n\nAvatarFallback.displayName = \"AvatarFallback\";\n","import { FC } from \"react\";\nimport { ContentPartPrimitive } from \"../primitives\";\nimport { useSmoothStatus, withSmoothContextProvider } from \"../utils/smooth\";\nimport classNames from \"classnames\";\n\nexport const Text: FC = () => {\n const status = useSmoothStatus();\n return (\n <ContentPartPrimitive.Text\n className={classNames(\n \"aui-text\",\n status.type === \"running\" && \"aui-text-running\",\n )}\n component=\"p\"\n />\n );\n};\n\nconst exports = { Text: withSmoothContextProvider(Text) };\n\nexport default exports;\n","\"use client\";\n\nimport { type FC, forwardRef } from \"react\";\nimport { BotIcon, ChevronDownIcon } from \"lucide-react\";\n\nimport {\n AssistantModalPrimitive,\n AssistantModalPrimitiveRootProps,\n} from \"../primitives\";\nimport Thread from \"./thread\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport {\n ThreadConfig,\n ThreadConfigProvider,\n ThreadConfigProviderProps,\n useThreadConfig,\n} from \"./thread-config\";\n\nconst AssistantModal: FC<ThreadConfig> = (config) => {\n return (\n <AssistantModalRoot config={config}>\n <AssistantModalTrigger />\n <AssistantModalContent>\n <Thread />\n </AssistantModalContent>\n </AssistantModalRoot>\n );\n};\n\nAssistantModal.displayName = \"AssistantModal\";\n\nconst AssistantModalRoot: FC<\n AssistantModalPrimitiveRootProps & ThreadConfigProviderProps\n> = ({ config, ...props }) => {\n return (\n <ThreadConfigProvider config={config}>\n <AssistantModalPrimitive.Root {...props} />\n </ThreadConfigProvider>\n );\n};\n\nAssistantModalRoot.displayName = \"AssistantModalRoot\";\n\nconst AssistantModalTrigger = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n return (\n <AssistantModalAnchor>\n <AssistantModalPrimitive.Trigger asChild>\n <AssistantModalButton {...props} ref={ref} />\n </AssistantModalPrimitive.Trigger>\n </AssistantModalAnchor>\n );\n});\n\nAssistantModalTrigger.displayName = \"AssistantModalTrigger\";\n\nconst AssistantModalAnchor = withDefaults(AssistantModalPrimitive.Anchor, {\n className: \"aui-root aui-modal-anchor\",\n});\n\nAssistantModalAnchor.displayName = \"AssistantModalAnchor\";\n\nconst ModalButtonStyled = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-modal-button\",\n});\n\ntype AssistantModalButtonProps = TooltipIconButtonProps & {\n \"data-state\"?: \"open\" | \"closed\";\n};\n\nconst AssistantModalButton = forwardRef<\n HTMLButtonElement,\n Partial<AssistantModalButtonProps>\n>(({ \"data-state\": state, ...rest }, ref) => {\n const {\n strings: {\n assistantModal: {\n open: {\n button: { tooltip: openTooltip = \"Close Assistant\" } = {},\n } = {},\n closed: {\n button: { tooltip: closedTooltip = \"Open Assistant\" } = {},\n } = {},\n } = {},\n } = {},\n } = useThreadConfig();\n const tooltip = state === \"open\" ? openTooltip : closedTooltip;\n\n return (\n <ModalButtonStyled\n side=\"left\"\n tooltip={tooltip}\n data-state={state}\n {...rest}\n ref={ref}\n >\n {rest.children ?? (\n <>\n <BotIcon\n data-state={state}\n className=\"aui-modal-button-closed-icon\"\n />\n <ChevronDownIcon\n data-state={state}\n className=\"aui-modal-button-open-icon\"\n />\n </>\n )}\n </ModalButtonStyled>\n );\n});\n\nAssistantModalButton.displayName = \"AssistantModalButton\";\n\nconst AssistantModalContent = withDefaults(AssistantModalPrimitive.Content, {\n className: \"aui-root aui-modal-content\",\n sideOffset: 16,\n});\n\nAssistantModalContent.displayName = \"AssistantModalContent\";\n\nconst exports = {\n Root: AssistantModalRoot,\n Trigger: AssistantModalTrigger,\n Content: AssistantModalContent,\n Button: AssistantModalButton,\n Anchor: AssistantModalAnchor,\n};\n\nexport default Object.assign(AssistantModal, exports) as typeof AssistantModal &\n typeof exports;\n","\"use client\";\n\nimport { ComponentType, forwardRef, type FC } from \"react\";\nimport { ArrowDownIcon } from \"lucide-react\";\n\nimport { withDefaults } from \"./utils/withDefaults\";\nimport Composer from \"./composer\";\nimport ThreadWelcome from \"./thread-welcome\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport AssistantMessage from \"./assistant-message\";\nimport UserMessage from \"./user-message\";\nimport EditComposer from \"./edit-composer\";\nimport {\n ThreadConfig,\n ThreadConfigProvider,\n ThreadConfigProviderProps,\n useThreadConfig,\n} from \"./thread-config\";\nimport { ThreadPrimitive, ThreadPrimitiveRootProps } from \"../primitives\";\n\nconst Thread: FC<ThreadConfig> = (config) => {\n return (\n <ThreadRoot config={config}>\n <ThreadViewport>\n <ThreadWelcome />\n <ThreadMessages />\n <ThreadViewportFooter>\n <ThreadScrollToBottom />\n <Composer />\n </ThreadViewportFooter>\n </ThreadViewport>\n </ThreadRoot>\n );\n};\n\nexport type ThreadRootProps = ThreadPrimitiveRootProps &\n ThreadConfigProviderProps;\n\nconst ThreadRootStyled = withDefaults(ThreadPrimitive.Root, {\n className: \"aui-root aui-thread-root\",\n});\n\nconst ThreadRoot = forwardRef<HTMLDivElement, ThreadRootProps>(\n ({ config, ...props }, ref) => {\n return (\n <ThreadConfigProvider config={config}>\n <ThreadRootStyled {...props} ref={ref} />\n </ThreadConfigProvider>\n );\n },\n);\n\nThreadRoot.displayName = \"ThreadRoot\";\n\nconst ThreadViewport = withDefaults(ThreadPrimitive.Viewport, {\n className: \"aui-thread-viewport\",\n});\n\nThreadViewport.displayName = \"ThreadViewport\";\n\nconst ThreadViewportFooter = withDefaults(\"div\", {\n className: \"aui-thread-viewport-footer\",\n});\n\nThreadViewportFooter.displayName = \"ThreadViewportFooter\";\n\nconst SystemMessage = () => null;\n\nconst ThreadMessages: FC<{\n components?: {\n UserMessage?: ComponentType | undefined;\n EditComposer?: ComponentType | undefined;\n AssistantMessage?: ComponentType | undefined;\n SystemMessage?: ComponentType | undefined;\n };\n}> = ({ components, ...rest }) => {\n return (\n <ThreadPrimitive.Messages\n components={{\n UserMessage: components?.UserMessage ?? UserMessage,\n EditComposer: components?.EditComposer ?? EditComposer,\n AssistantMessage: components?.AssistantMessage ?? AssistantMessage,\n SystemMessage: components?.SystemMessage ?? SystemMessage,\n }}\n {...rest}\n />\n );\n};\n\nThreadMessages.displayName = \"ThreadMessages\";\n\nconst ThreadScrollToBottomIconButton = withDefaults(TooltipIconButton, {\n variant: \"outline\",\n className: \"aui-thread-scroll-to-bottom\",\n});\n\nconst ThreadScrollToBottom = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n thread: { scrollToBottom: { tooltip = \"Scroll to bottom\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ThreadPrimitive.ScrollToBottom asChild>\n <ThreadScrollToBottomIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ArrowDownIcon />}\n </ThreadScrollToBottomIconButton>\n </ThreadPrimitive.ScrollToBottom>\n );\n});\n\nThreadScrollToBottom.displayName = \"ThreadScrollToBottom\";\n\nconst exports = {\n Root: ThreadRoot,\n Viewport: ThreadViewport,\n Messages: ThreadMessages,\n ScrollToBottom: ThreadScrollToBottom,\n ViewportFooter: ThreadViewportFooter,\n};\n\nexport default Object.assign(Thread, exports) as typeof Thread & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\n\nimport { PaperclipIcon, SendHorizontalIcon } from \"lucide-react\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { CircleStopIcon } from \"./base/CircleStopIcon\";\nimport { ComposerPrimitive, ThreadPrimitive } from \"../primitives\";\nimport { useThread } from \"../context/react/ThreadContext\";\nimport ComposerAttachment from \"./composer-attachment\";\nimport { ComposerPrimitiveAttachmentsProps } from \"../primitives/composer/ComposerAttachments\";\n\nconst useAllowAttachments = (ensureCapability = false) => {\n const { composer: { allowAttachments = true } = {} } = useThreadConfig();\n const attachmentsSupported = useThread((t) => t.capabilities.attachments);\n return allowAttachments && (!ensureCapability || attachmentsSupported);\n};\n\nconst Composer: FC = () => {\n const allowAttachments = useAllowAttachments(true);\n return (\n <ComposerRoot>\n {allowAttachments && <ComposerAttachments />}\n {allowAttachments && <ComposerAddAttachment />}\n <ComposerInput autoFocus />\n <ComposerAction />\n </ComposerRoot>\n );\n};\n\nComposer.displayName = \"Composer\";\n\nconst ComposerRoot = withDefaults(ComposerPrimitive.Root, {\n className: \"aui-composer-root\",\n});\n\nComposerRoot.displayName = \"ComposerRoot\";\n\nconst ComposerInputStyled = withDefaults(ComposerPrimitive.Input, {\n rows: 1,\n autoFocus: true,\n className: \"aui-composer-input\",\n});\n\nexport type ComposerInputProps = ComponentPropsWithoutRef<\n typeof ComposerInputStyled\n>;\nconst ComposerInput = forwardRef<HTMLTextAreaElement, ComposerInputProps>(\n (props, ref) => {\n const {\n strings: {\n composer: { input: { placeholder = \"Write a message...\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ComposerInputStyled placeholder={placeholder} {...props} ref={ref} />\n );\n },\n);\n\nComposerInput.displayName = \"ComposerInput\";\n\nconst ComposerAttachmentsContainer = withDefaults(\"div\", {\n className: \"aui-composer-attachments\",\n});\n\ntype ComposerAttachmentsProps = Partial<ComposerPrimitiveAttachmentsProps>;\n\nconst ComposerAttachments: FC<ComposerAttachmentsProps> = ({ components }) => {\n return (\n <ComposerAttachmentsContainer>\n <ComposerPrimitive.Attachments\n components={{\n ...components,\n Attachment: components?.Attachment ?? ComposerAttachment,\n }}\n />\n </ComposerAttachmentsContainer>\n );\n};\n\nconst ComposerAttachButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-attach\",\n});\n\nconst ComposerAddAttachment = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n composer: { addAttachment: { tooltip = \"Attach file\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowAttachments = useAllowAttachments();\n return (\n <ComposerPrimitive.AddAttachment disabled={!allowAttachments} asChild>\n <ComposerAttachButton\n tooltip={tooltip}\n variant={\"ghost\"}\n {...props}\n ref={ref}\n >\n {props.children ?? <PaperclipIcon />}\n </ComposerAttachButton>\n </ComposerPrimitive.AddAttachment>\n );\n});\n\nComposerAddAttachment.displayName = \"ComposerAddAttachment\";\n\nconst useAllowCancel = () => {\n const cancelSupported = useThread((t) => t.capabilities.cancel);\n return cancelSupported;\n};\n\nconst ComposerAction: FC = () => {\n const allowCancel = useAllowCancel();\n if (!allowCancel) return <ComposerSend />;\n return (\n <>\n <ThreadPrimitive.If running={false}>\n <ComposerSend />\n </ThreadPrimitive.If>\n <ThreadPrimitive.If running>\n <ComposerCancel />\n </ThreadPrimitive.If>\n </>\n );\n};\n\nComposerAction.displayName = \"ComposerAction\";\n\nconst ComposerSendButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-send\",\n});\n\nconst ComposerSend = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { composer: { send: { tooltip = \"Send\" } = {} } = {} } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Send asChild>\n <ComposerSendButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <SendHorizontalIcon />}\n </ComposerSendButton>\n </ComposerPrimitive.Send>\n );\n});\n\nComposerSend.displayName = \"ComposerSend\";\n\nconst ComposerCancelButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-cancel\",\n});\n\nconst ComposerCancel = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { composer: { cancel: { tooltip = \"Cancel\" } = {} } = {} } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Cancel asChild>\n <ComposerCancelButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <CircleStopIcon />}\n </ComposerCancelButton>\n </ComposerPrimitive.Cancel>\n );\n});\n\nComposerCancel.displayName = \"ComposerCancel\";\n\nconst exports = {\n Root: ComposerRoot,\n Input: ComposerInput,\n Action: ComposerAction,\n Send: ComposerSend,\n Cancel: ComposerCancel,\n AddAttachment: ComposerAddAttachment,\n Attachments: ComposerAttachments,\n};\n\nexport default Object.assign(Composer, exports) as typeof Composer &\n typeof exports;\n","import { FC } from \"react\";\n\nexport const CircleStopIcon: FC = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n width=\"16\"\n height=\"16\"\n >\n <rect width=\"10\" height=\"10\" x=\"3\" y=\"3\" rx=\"2\" />\n </svg>\n );\n};\n\nCircleStopIcon.displayName = \"CircleStopIcon\";\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\n\nimport { CircleXIcon } from \"lucide-react\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\nimport {\n useAttachmentStore,\n useComposerAttachment,\n} from \"../context/react/AttachmentContext\";\n\nconst ComposerAttachmentRoot = withDefaults(\"div\", {\n className: \"aui-composer-attachment-root\",\n});\n\nComposerAttachmentRoot.displayName = \"ComposerAttachmentRoot\";\n\nconst ComposerAttachment: FC = () => {\n const attachment = useComposerAttachment((a) => a.attachment);\n\n return (\n <ComposerAttachmentRoot>\n .{attachment.name.split(\".\").pop()}\n <ComposerAttachmentRemove />\n </ComposerAttachmentRoot>\n );\n};\n\nComposerAttachment.displayName = \"ComposerAttachment\";\n\nconst ComposerAttachmentRemove = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n composer: { removeAttachment: { tooltip = \"Remove file\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n const composerStore = useThreadComposerStore();\n const attachmentStore = useAttachmentStore();\n const handleRemoveAttachment = () => {\n composerStore\n .getState()\n .removeAttachment(attachmentStore.getState().attachment.id);\n };\n\n return (\n <TooltipIconButton\n tooltip={tooltip}\n className=\"aui-composer-attachment-remove\"\n side=\"top\"\n {...props}\n onClick={handleRemoveAttachment}\n ref={ref}\n >\n {props.children ?? <CircleXIcon />}\n </TooltipIconButton>\n );\n});\n\nComposerAttachmentRemove.displayName = \"ComposerAttachmentRemove\";\n\nconst exports = {\n Root: ComposerAttachmentRoot,\n Remove: ComposerAttachmentRemove,\n};\n\nexport default Object.assign(\n ComposerAttachment,\n exports,\n) as typeof ComposerAttachment & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { Avatar } from \"./base/avatar\";\nimport { SuggestionConfig, useThreadConfig } from \"./thread-config\";\nimport { ThreadPrimitive } from \"../primitives\";\n\nconst ThreadWelcome: FC = () => {\n return (\n <ThreadWelcomeRoot>\n <ThreadWelcomeCenter>\n <ThreadWelcomeAvatar />\n <ThreadWelcomeMessage />\n </ThreadWelcomeCenter>\n <ThreadWelcomeSuggestions />\n </ThreadWelcomeRoot>\n );\n};\n\nThreadWelcome.displayName = \"ThreadWelcome\";\n\nconst ThreadWelcomeRootStyled = withDefaults(\"div\", {\n className: \"aui-thread-welcome-root\",\n});\n\nconst ThreadWelcomeCenter = withDefaults(\"div\", {\n className: \"aui-thread-welcome-center\",\n});\n\ntype ThreadWelcomeRootProps = ComponentPropsWithoutRef<\"div\">;\n\nconst ThreadWelcomeRoot = forwardRef<HTMLDivElement, ThreadWelcomeRootProps>(\n (props, ref) => {\n return (\n <ThreadPrimitive.Empty>\n <ThreadWelcomeRootStyled {...props} ref={ref} />\n </ThreadPrimitive.Empty>\n );\n },\n);\n\nThreadWelcomeRoot.displayName = \"ThreadWelcomeRoot\";\n\nconst ThreadWelcomeAvatar: FC = () => {\n const { assistantAvatar: avatar = { fallback: \"A\" } } = useThreadConfig();\n return <Avatar {...avatar} />;\n};\n\nconst ThreadWelcomeMessageStyled = withDefaults(\"p\", {\n className: \"aui-thread-welcome-message\",\n});\n\nexport type ThreadWelcomeMessageProps = Omit<\n ComponentPropsWithoutRef<typeof ThreadWelcomeMessageStyled>,\n \"children\"\n> & { message?: string | undefined };\n\nconst ThreadWelcomeMessage = forwardRef<\n HTMLParagraphElement,\n ThreadWelcomeMessageProps\n>(({ message: messageProp, ...rest }, ref) => {\n const { welcome: { message = \"How can I help you today?\" } = {} } =\n useThreadConfig();\n return (\n <ThreadWelcomeMessageStyled {...rest} ref={ref}>\n {messageProp ?? message}\n </ThreadWelcomeMessageStyled>\n );\n});\n\nThreadWelcomeMessage.displayName = \"ThreadWelcomeMessage\";\n\nconst ThreadWelcomeSuggestionContainer = withDefaults(\"div\", {\n className: \"aui-thread-welcome-suggestion-container\",\n});\n\nconst ThreadWelcomeSuggestionStyled = withDefaults(ThreadPrimitive.Suggestion, {\n className: \"aui-thread-welcome-suggestion\",\n});\n\nexport type ThreadWelcomeSuggestionProps = {\n suggestion: SuggestionConfig;\n};\n\nconst ThreadWelcomeSuggestion: FC<ThreadWelcomeSuggestionProps> = ({\n suggestion: { text, prompt },\n}) => {\n return (\n <ThreadWelcomeSuggestionStyled\n prompt={prompt}\n method=\"replace\"\n autoSend\n >\n <span className=\"aui-thread-welcome-suggestion-text\">{text ?? prompt}</span>\n </ThreadWelcomeSuggestionStyled>\n );\n};\n\nconst ThreadWelcomeSuggestions: FC = () => {\n const { welcome: { suggestions } = {} } = useThreadConfig();\n return (\n <ThreadWelcomeSuggestionContainer>\n {suggestions?.map((suggestion, idx) => {\n const key = `${suggestion.prompt}-${idx}`;\n return <ThreadWelcomeSuggestion key={key} suggestion={suggestion} />;\n })}\n </ThreadWelcomeSuggestionContainer>\n );\n};\n\nThreadWelcomeSuggestions.displayName = \"ThreadWelcomeSuggestions\";\n\nconst exports = {\n Root: ThreadWelcomeRoot,\n Center: ThreadWelcomeCenter,\n Avatar: ThreadWelcomeAvatar,\n Message: ThreadWelcomeMessage,\n Suggestions: ThreadWelcomeSuggestions,\n Suggestion: ThreadWelcomeSuggestion,\n};\n\nexport default Object.assign(ThreadWelcome, exports) as typeof ThreadWelcome &\n typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\n\nimport BranchPicker from \"./branch-picker\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport UserActionBar from \"./user-action-bar\";\nimport ContentPart from \"./content-part\";\nimport { MessagePrimitive, MessagePrimitiveContentProps } from \"../primitives\";\nimport UserMessageAttachment from \"./user-message-attachment\";\nimport { MessagePrimitiveAttachmentsProps } from \"../primitives/message/MessageAttachments\";\n\nconst UserMessage: FC = () => {\n return (\n <UserMessageRoot>\n <UserMessageAttachments />\n <UserActionBar />\n <UserMessageContent />\n <BranchPicker />\n </UserMessageRoot>\n );\n};\n\nUserMessage.displayName = \"UserMessage\";\n\nconst UserMessageRoot = withDefaults(MessagePrimitive.Root, {\n className: \"aui-user-message-root\",\n});\n\nUserMessageRoot.displayName = \"UserMessageRoot\";\n\nconst UserMessageContentWrapper = withDefaults(\"div\", {\n className: \"aui-user-message-content\",\n});\n\nexport type UserMessageContentProps = MessagePrimitiveContentProps &\n ComponentPropsWithoutRef<\"div\">;\n\nconst UserMessageContent = forwardRef<HTMLDivElement, UserMessageContentProps>(\n ({ components, ...props }, ref) => {\n return (\n <UserMessageContentWrapper {...props} ref={ref}>\n <MessagePrimitive.Content\n components={{\n ...components,\n Text: components?.Text ?? ContentPart.Text,\n }}\n />\n </UserMessageContentWrapper>\n );\n },\n);\n\nUserMessageContent.displayName = \"UserMessageContent\";\n\nconst UserMessageAttachmentsContainer = withDefaults(\"div\", {\n className: \"aui-user-message-attachments\",\n});\n\nexport type UserMessageAttachmentsProps =\n Partial<MessagePrimitiveAttachmentsProps>;\n\nconst UserMessageAttachments: FC<UserMessageAttachmentsProps> = ({\n components,\n}) => {\n return (\n <MessagePrimitive.If hasAttachments>\n <UserMessageAttachmentsContainer>\n <MessagePrimitive.Attachments\n components={{\n ...components,\n Attachment: components?.Attachment ?? UserMessageAttachment,\n }}\n />\n </UserMessageAttachmentsContainer>\n </MessagePrimitive.If>\n );\n};\n\nconst exports = {\n Root: UserMessageRoot,\n Content: UserMessageContent,\n Attachments: UserMessageAttachments,\n};\n\nexport default Object.assign(UserMessage, exports) as typeof UserMessage &\n typeof exports;\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\nimport { PencilIcon } from \"lucide-react\";\n\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { useThread } from \"../context\";\nimport { ActionBarPrimitive } from \"../primitives\";\n\nconst useAllowEdit = (ensureCapability = false) => {\n const { userMessage: { allowEdit = true } = {} } = useThreadConfig();\n const editSupported = useThread((t) => t.capabilities.edit);\n return allowEdit && (!ensureCapability || editSupported);\n};\n\nconst UserActionBar: FC = () => {\n const allowEdit = useAllowEdit(true);\n if (!allowEdit) return null;\n return (\n <UserActionBarRoot hideWhenRunning autohide=\"not-last\">\n <UserActionBarEdit />\n </UserActionBarRoot>\n );\n};\n\nUserActionBar.displayName = \"UserActionBar\";\n\nconst UserActionBarRoot = withDefaults(ActionBarPrimitive.Root, {\n className: \"aui-user-action-bar-root\",\n});\n\nUserActionBarRoot.displayName = \"UserActionBarRoot\";\n\nconst UserActionBarEdit = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { userMessage: { edit: { tooltip = \"Edit\" } = {} } = {} } = {},\n } = useThreadConfig();\n const allowEdit = useAllowEdit();\n return (\n <ActionBarPrimitive.Edit disabled={!allowEdit} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <PencilIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.Edit>\n );\n});\n\nUserActionBarEdit.displayName = \"UserActionBarEdit\";\n\nconst exports = {\n Root: UserActionBarRoot,\n Edit: UserActionBarEdit,\n};\n\nexport default Object.assign(UserActionBar, exports) as typeof UserActionBar &\n typeof exports;\n","\"use client\";\n\nimport { type FC } from \"react\";\n\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useAttachment } from \"../context/react/AttachmentContext\";\n\nconst UserMessageAttachmentRoot = withDefaults(\"div\", {\n className: \"aui-user-message-attachment-root\",\n});\n\nUserMessageAttachmentRoot.displayName = \"UserMessageAttachmentRoot\";\n\nconst UserMessageAttachment: FC = () => {\n const attachment = useAttachment((a) => a.attachment);\n\n return (\n <UserMessageAttachmentRoot>\n .{attachment.name.split(\".\").pop()}\n </UserMessageAttachmentRoot>\n );\n};\n\nUserMessageAttachment.displayName = \"UserMessageAttachment\";\n\nconst exports = {\n Root: UserMessageAttachmentRoot,\n};\n\nexport default Object.assign(\n UserMessageAttachment,\n exports,\n) as typeof UserMessageAttachment & typeof exports;\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\n\nimport { Button, ButtonProps } from \"./base/button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { ComposerPrimitive } from \"../primitives\";\n\nconst EditComposer: FC = () => {\n return (\n <EditComposerRoot>\n <EditComposerInput />\n\n <EditComposerFooter>\n <EditComposerCancel />\n <EditComposerSend />\n </EditComposerFooter>\n </EditComposerRoot>\n );\n};\n\nEditComposer.displayName = \"EditComposer\";\n\nconst EditComposerRoot = withDefaults(ComposerPrimitive.Root, {\n className: \"aui-edit-composer-root\",\n});\n\nEditComposerRoot.displayName = \"EditComposerRoot\";\n\nconst EditComposerInput = withDefaults(ComposerPrimitive.Input, {\n className: \"aui-edit-composer-input\",\n});\n\nEditComposerInput.displayName = \"EditComposerInput\";\n\nconst EditComposerFooter = withDefaults(\"div\", {\n className: \"aui-edit-composer-footer\",\n});\n\nEditComposerFooter.displayName = \"EditComposerFooter\";\n\nconst EditComposerCancel = forwardRef<HTMLButtonElement, Partial<ButtonProps>>(\n (props, ref) => {\n const {\n strings: {\n editComposer: { cancel: { label = \"Cancel\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Cancel asChild>\n <Button variant=\"ghost\" {...props} ref={ref}>\n {props.children ?? label}\n </Button>\n </ComposerPrimitive.Cancel>\n );\n },\n);\n\nEditComposerCancel.displayName = \"EditComposerCancel\";\n\nconst EditComposerSend = forwardRef<HTMLButtonElement, Partial<ButtonProps>>(\n (props, ref) => {\n const {\n strings: { editComposer: { send: { label = \"Send\" } = {} } = {} } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Send asChild>\n <Button {...props} ref={ref}>\n {props.children ?? label}\n </Button>\n </ComposerPrimitive.Send>\n );\n },\n);\n\nEditComposerSend.displayName = \"EditComposerSend\";\n\nconst exports = {\n Root: EditComposerRoot,\n Input: EditComposerInput,\n Footer: EditComposerFooter,\n Cancel: EditComposerCancel,\n Send: EditComposerSend,\n};\n\nexport default Object.assign(EditComposer, exports) as typeof EditComposer &\n typeof exports;\n"]}
1
+ {"version":3,"sources":["/home/runner/work/assistant-ui/assistant-ui/packages/react/dist/index.js","../src/context/providers/AssistantRuntimeProvider.tsx","../src/context/providers/AssistantProvider.tsx","../src/context/react/AssistantContext.ts","../src/context/react/utils/createContextHook.ts","../src/context/react/utils/createContextStoreHook.ts","../src/context/stores/AssistantToolUIs.ts","../src/context/providers/ThreadProvider.tsx","../src/context/react/ThreadContext.ts","../src/context/stores/ThreadComposer.ts","../src/context/stores/Thread.ts","../src/context/stores/ThreadViewport.tsx","../src/context/stores/ThreadActions.ts","../src/context/stores/ThreadMessages.ts","../src/context/stores/ThreadRuntime.tsx","../src/runtimes/core/subscribeToMainThread.ts","../src/runtimes/local/useLocalRuntime.tsx","../src/runtimes/core/BaseAssistantRuntime.tsx","../src/internal.ts","../src/runtimes/utils/ThreadRuntimeComposer.tsx","../src/utils/ProxyConfigProvider.ts","../src/utils/idUtils.tsx","../src/runtimes/edge/converters/fromCoreMessage.ts","../src/runtimes/utils/MessageRepository.tsx","../src/utils/smooth/useSmooth.tsx","../src/utils/smooth/SmoothContext.tsx","../src/context/react/ContentPartContext.ts","../src/context/ReadonlyStore.ts","../src/ui/base/tooltip-icon-button.tsx","../src/ui/base/tooltip.tsx","../src/ui/utils/withDefaults.tsx","../src/ui/base/button.tsx","../src/runtimes/edge/converters/fromLanguageModelMessages.ts","../src/runtimes/edge/converters/fromLanguageModelTools.ts","../src/runtimes/edge/streams/utils/chunkByLineStream.ts","../src/runtimes/edge/streams/utils/streamPartDecoderStream.ts","../src/runtimes/edge/streams/utils/index.ts","../src/runtimes/edge/useEdgeRuntime.ts","../src/runtimes/edge/streams/assistantDecoderStream.ts","../src/runtimes/edge/EdgeChatAdapter.ts","../src/runtimes/local/shouldContinue.tsx","../src/runtimes/local/LocalThreadRuntime.tsx","../src/runtimes/local/LocalRuntime.tsx","../src/runtimes/external-store/getExternalStoreMessage.tsx","../src/runtimes/external-store/ThreadMessageConverter.ts","../src/runtimes/external-store/auto-status.tsx","../src/runtimes/external-store/ThreadMessageLike.tsx","../src/utils/getThreadMessageText.tsx","../src/runtimes/external-store/ExternalStoreThreadRuntime.tsx","../src/runtimes/external-store/ExternalStoreRuntime.tsx","../src/runtimes/external-store/useExternalStoreRuntime.tsx","../src/runtimes/external-store/external-message-converter.tsx","../src/runtimes/dangerous-in-browser/useDangerousInBrowserRuntime.ts","../src/runtimes/dangerous-in-browser/DangerousInBrowserAdapter.ts","../src/runtimes/speech/WebSpeechSynthesisAdapter.ts","../src/runtimes/attachment/SimpleImageAttachmentAdapter.ts","../src/runtimes/attachment/SimpleTextAttachmentAdapter.ts","../src/runtimes/attachment/CompositeAttachmentAdapter.ts","../src/context/stores/AssistantActions.tsx","../src/context/stores/AssistantRuntime.tsx","../src/context/providers/TextContentPartProvider.tsx","../src/context/react/MessageContext.ts","../src/context/react/ComposerContext.ts","../src/hooks/useAppendMessage.tsx","../src/hooks/useSwitchToNewThread.tsx","../src/model-config/useAssistantTool.tsx","../src/model-config/makeAssistantTool.tsx","../src/model-config/useAssistantToolUI.tsx","../src/model-config/makeAssistantToolUI.tsx","../src/model-config/useAssistantInstructions.tsx","../src/primitive-hooks/actionBar/useActionBarCopy.tsx","../src/utils/combined/useCombinedStore.ts","../src/utils/combined/createCombinedStore.ts","../src/primitive-hooks/actionBar/useActionBarEdit.tsx","../src/primitive-hooks/actionBar/useActionBarReload.tsx","../src/primitive-hooks/actionBar/useActionBarSpeak.tsx","../src/primitive-hooks/actionBar/useActionBarStopSpeaking.tsx","../src/primitive-hooks/actionBar/useActionBarFeedbackPositive.tsx","../src/primitive-hooks/actionBar/useActionBarFeedbackNegative.tsx","../src/primitive-hooks/branchPicker/useBranchPickerCount.tsx","../src/primitive-hooks/branchPicker/useBranchPickerNext.tsx","../src/primitive-hooks/branchPicker/useBranchPickerNumber.tsx","../src/primitive-hooks/branchPicker/useBranchPickerPrevious.tsx","../src/primitive-hooks/composer/useComposerCancel.tsx","../src/primitive-hooks/composer/useComposerIf.tsx","../src/primitive-hooks/composer/useComposerSend.tsx","../src/primitive-hooks/composer/useComposerAddAttachment.tsx","../src/primitive-hooks/contentPart/useContentPartDisplay.tsx","../src/primitive-hooks/contentPart/useContentPartImage.tsx","../src/primitive-hooks/contentPart/useContentPartText.tsx","../src/primitive-hooks/message/useMessageIf.tsx","../src/primitive-hooks/thread/useThreadIf.tsx","../src/primitive-hooks/thread/useThreadEmpty.tsx","../src/primitive-hooks/thread/useThreadScrollToBottom.tsx","../src/primitive-hooks/thread/useThreadSuggestion.tsx","../src/primitives/actionBar/index.ts","../src/primitives/actionBar/ActionBarRoot.tsx","../src/primitives/actionBar/useActionBarFloatStatus.tsx","../src/primitives/actionBar/ActionBarCopy.tsx","../src/utils/createActionButton.tsx","../src/primitives/actionBar/ActionBarReload.tsx","../src/primitives/actionBar/ActionBarEdit.tsx","../src/primitives/actionBar/ActionBarSpeak.tsx","../src/primitives/actionBar/ActionBarStopSpeaking.tsx","../src/primitives/actionBar/ActionBarFeedbackPositive.tsx","../src/primitives/actionBar/ActionBarFeedbackNegative.tsx","../src/primitives/assistantModal/index.ts","../src/primitives/assistantModal/AssistantModalRoot.tsx","../src/utils/hooks/useOnComposerFocus.tsx","../src/primitives/assistantModal/scope.tsx","../src/primitives/assistantModal/AssistantModalTrigger.tsx","../src/primitives/assistantModal/AssistantModalContent.tsx","../src/primitives/assistantModal/AssistantModalAnchor.tsx","../src/primitives/branchPicker/index.ts","../src/primitives/branchPicker/BranchPickerNext.tsx","../src/primitives/branchPicker/BranchPickerPrevious.tsx","../src/primitives/branchPicker/BranchPickerCount.tsx","../src/primitives/branchPicker/BranchPickerNumber.tsx","../src/primitives/branchPicker/BranchPickerRoot.tsx","../src/primitives/message/index.ts","../src/primitives/message/MessageRoot.tsx","../src/utils/hooks/useManagedRef.ts","../src/primitives/message/MessageIf.tsx","../src/primitives/message/MessageContent.tsx","../src/context/providers/ContentPartProvider.tsx","../src/primitives/contentPart/ContentPartText.tsx","../src/primitives/contentPart/ContentPartImage.tsx","../src/primitives/contentPart/ContentPartDisplay.tsx","../src/primitives/contentPart/ContentPartInProgress.tsx","../src/primitives/message/MessageInProgress.tsx","../src/primitives/message/MessageAttachments.tsx","../src/context/react/AttachmentContext.ts","../src/context/providers/MessageAttachmentProvider.tsx","../src/primitives/composer/index.ts","../src/primitives/composer/ComposerRoot.tsx","../src/primitives/composer/ComposerInput.tsx","../src/primitives/composer/ComposerSend.tsx","../src/primitives/composer/ComposerCancel.tsx","../src/primitives/composer/ComposerAddAttachment.tsx","../src/primitives/composer/ComposerAttachments.tsx","../src/context/providers/ComposerAttachmentProvider.tsx","../src/primitives/composer/ComposerIf.tsx","../src/primitives/contentPart/index.ts","../src/primitives/thread/index.ts","../src/primitives/thread/ThreadRoot.tsx","../src/primitives/thread/ThreadEmpty.tsx","../src/primitives/thread/ThreadIf.tsx","../src/primitives/thread/ThreadViewport.tsx","../src/primitive-hooks/thread/useThreadViewportAutoScroll.tsx","../src/utils/hooks/useOnResizeContent.tsx","../src/utils/hooks/useOnScrollToBottom.tsx","../src/primitives/thread/ThreadMessages.tsx","../src/context/providers/MessageProvider.tsx","../src/context/stores/EditComposer.ts","../src/context/stores/MessageUtils.ts","../src/primitives/thread/ThreadScrollToBottom.tsx","../src/primitives/thread/ThreadSuggestion.tsx","../src/ui/thread-config.tsx","../src/ui/assistant-action-bar.tsx","../src/ui/assistant-message.tsx","../src/ui/branch-picker.tsx","../src/ui/base/avatar.tsx","../src/ui/content-part.tsx","../src/ui/assistant-modal.tsx","../src/ui/thread.tsx","../src/ui/composer.tsx","../src/ui/base/CircleStopIcon.tsx","../src/ui/composer-attachment.tsx","../src/ui/thread-welcome.tsx","../src/ui/user-message.tsx","../src/ui/user-action-bar.tsx","../src/ui/user-message-attachment.tsx","../src/ui/edit-composer.tsx"],"names":["useEffect","useInsertionEffect","useEditComposer","Primitive","COMPLETE_STATUS","useContentPartContext","useMessageAttachmentContext","useEscapeKeydown","getAttachment","useComposerAttachmentContext","getComponent","AttachmentComponent","create","useMessageContext","BranchPickerPrevious","exports","ComposerAttachment"],"mappings":"AAAA,irCAAY;AACZ;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;AChBA,8BAAqB;ADkBrB;AACA;AEjBA;AFmBA;AACA;AGrBA;AHuBA;AACA;AI1BA;AAQO,SAAS,iBAAA,CACd,OAAA,EACA,YAAA,EACA;AAKA,EAAA,SAAS,cAAA,CAAe,OAAA,EAA8C;AACpE,IAAA,MAAM,aAAA,EAAe,+BAAA,OAAkB,CAAA;AACvC,IAAA,GAAA,CAAI,iBAAC,OAAA,6BAAS,WAAA,GAAY,CAAC,YAAA,EAAc;AACvC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mCAAA,EAAsC,YAAY,CAAA,CAAA,CAAG,CAAA;AAAA,IACvE;AACA,IAAA,OAAO,YAAA;AAAA,EACT;AAEA,EAAA,OAAO,cAAA;AACT;AJa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,EAAA;AACG,IAAA;AAAA,IAAA;AACC,MAAA;AACA,MAAA;AACA,MAAA;AACC,MAAA;AACD,MAAA;AAEC,MAAA;AAEG,wBAAA;AAAA,UAAA;AAAC,UAAA;AAAA,YAAA;AACa,YAAA;AACF,UAAA;AAAA,QAAA;AACZ,wBAAA;AACA,UAAA;AAAC,UAAA;AAAA,YAAA;AACa,YAAA;AACF,UAAA;AAAA,QAAA;AACZ,MAAA;AACF,IAAA;AAEJ,EAAA;AAEH;AAED;AAEM;AACJ,EAAA;AACA,EAAA;AACD;AAED;AAEMA;AACJ,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAEO;AnKooKD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/assistant-ui/assistant-ui/packages/react/dist/index.js","sourcesContent":[null,"import type { FC, PropsWithChildren } from \"react\";\nimport { memo } from \"react\";\nimport type { AssistantRuntime } from \"../../runtimes/core/AssistantRuntime\";\nimport { AssistantProvider } from \"./AssistantProvider\";\n\ntype AssistantRuntimeProviderProps = {\n runtime: AssistantRuntime;\n};\n\nconst AssistantRuntimeProviderImpl: FC<\n PropsWithChildren<AssistantRuntimeProviderProps>\n> = ({ children, runtime }) => {\n return <AssistantProvider runtime={runtime}>{children}</AssistantProvider>;\n};\n\nexport const AssistantRuntimeProvider = memo(AssistantRuntimeProviderImpl);\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useInsertionEffect, useRef, useState } from \"react\";\nimport type { AssistantRuntime } from \"../../runtimes\";\nimport { AssistantContext } from \"../react/AssistantContext\";\nimport { makeAssistantToolUIsStore } from \"../stores/AssistantToolUIs\";\nimport { ThreadProvider } from \"./ThreadProvider\";\nimport { makeAssistantActionsStore } from \"../stores/AssistantActions\";\nimport { makeAssistantRuntimeStore } from \"../stores/AssistantRuntime\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype AssistantProviderProps = {\n runtime: AssistantRuntime;\n};\n\nexport const AssistantProvider: FC<\n PropsWithChildren<AssistantProviderProps>\n> = ({ children, runtime }) => {\n const runtimeRef = useRef(runtime);\n useInsertionEffect(() => {\n runtimeRef.current = runtime;\n });\n\n const [context] = useState(() => {\n const useAssistantRuntime = makeAssistantRuntimeStore(runtime);\n const useToolUIs = makeAssistantToolUIsStore();\n const useAssistantActions = makeAssistantActionsStore(runtimeRef);\n\n return {\n useToolUIs,\n useAssistantRuntime,\n useAssistantActions,\n };\n });\n\n useEffect(\n () => writableStore(context.useAssistantRuntime).setState(runtime, true),\n [runtime, context],\n );\n\n return (\n <AssistantContext.Provider value={context}>\n <ThreadProvider provider={runtime}>{children}</ThreadProvider>\n </AssistantContext.Provider>\n );\n};\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { AssistantToolUIsState } from \"../stores/AssistantToolUIs\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { AssistantActionsState } from \"../stores/AssistantActions\";\nimport { AssistantRuntime } from \"../../runtimes\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type AssistantContextValue = {\n useToolUIs: UseBoundStore<ReadonlyStore<AssistantToolUIsState>>;\n useAssistantRuntime: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n useAssistantActions: UseBoundStore<ReadonlyStore<AssistantActionsState>>;\n};\n\nexport const AssistantContext = createContext<AssistantContextValue | null>(\n null,\n);\n\nexport const useAssistantContext = createContextHook(\n AssistantContext,\n \"AssistantRuntimeProvider\",\n);\n\nexport const { useAssistantRuntime, useAssistantRuntimeStore } =\n createContextStoreHook(useAssistantContext, \"useAssistantRuntime\");\n\nexport const { useToolUIs, useToolUIsStore } = createContextStoreHook(\n useAssistantContext,\n \"useToolUIs\",\n);\n\nexport const { useAssistantActions, useAssistantActionsStore } =\n createContextStoreHook(useAssistantContext, \"useAssistantActions\");\n","import { useContext, Context } from \"react\";\n\n/**\n * Creates a context hook with optional support.\n * @param context - The React context to consume.\n * @param providerName - The name of the provider for error messages.\n * @returns A hook function that provides the context value.\n */\nexport function createContextHook<T>(\n context: Context<T | null>,\n providerName: string,\n) {\n function useContextHook(options?: { optional?: false | undefined }): T;\n function useContextHook(options?: {\n optional?: boolean | undefined;\n }): T | null;\n function useContextHook(options?: { optional?: boolean | undefined }) {\n const contextValue = useContext(context);\n if (!options?.optional && !contextValue) {\n throw new Error(`This component must be used within ${providerName}.`);\n }\n return contextValue;\n }\n\n return useContextHook;\n}\n","import { UseBoundStore } from \"zustand\";\nimport { ReadonlyStore } from \"../../ReadonlyStore\";\n\n/**\n * Creates hooks for accessing a store within a context.\n * @param contextHook - The hook to access the context.\n * @param contextKey - The key of the store in the context.\n * @returns An object containing the hooks: `use...` and `use...Store`.\n */\nexport function createContextStoreHook<T, K extends keyof T & string>(\n contextHook: (options?: { optional?: boolean }) => T | null,\n contextKey: K,\n) {\n type StoreType = T[K];\n type StateType = StoreType extends ReadonlyStore<infer S> ? S : never;\n\n // Define useStoreStoreHook with overloads\n function useStoreStoreHook(): ReadonlyStore<StateType>;\n function useStoreStoreHook(options: {\n optional: true;\n }): ReadonlyStore<StateType> | null;\n function useStoreStoreHook(options?: {\n optional?: boolean;\n }): ReadonlyStore<StateType> | null {\n const context = contextHook(options);\n if (!context) {\n if (!options?.optional) {\n throw new Error(`This component must be used within a ${contextKey}.`);\n }\n return null;\n }\n return context[contextKey] as ReadonlyStore<StateType>;\n }\n\n // Define useStoreHook with overloads\n function useStoreHook(): StateType;\n function useStoreHook<TSelected>(\n selector: (state: StateType) => TSelected,\n ): TSelected;\n function useStoreHook(options: { optional: true }): StateType | null;\n function useStoreHook<TSelected>(options: {\n optional: true;\n selector?: (state: StateType) => TSelected;\n }): TSelected | null;\n function useStoreHook<TSelected>(\n param?:\n | ((state: StateType) => TSelected)\n | {\n optional?: boolean;\n selector?: (state: StateType) => TSelected;\n },\n ): TSelected | StateType | null {\n let optional = false;\n let selector: ((state: StateType) => TSelected) | undefined;\n\n if (typeof param === \"function\") {\n selector = param;\n } else if (param && typeof param === \"object\") {\n optional = !!param.optional;\n selector = param.selector;\n }\n\n const store = useStoreStoreHook({\n optional,\n } as any) as UseBoundStore<ReadonlyStore<StateType>>;\n if (!store) return null;\n return selector ? store(selector) : store();\n }\n\n // Return an object with keys based on contextKey\n return {\n [contextKey]: useStoreHook,\n [`${contextKey}Store`]: useStoreStoreHook,\n } as {\n [P in K]: typeof useStoreHook;\n } & {\n [P in `${K}Store`]: typeof useStoreStoreHook;\n };\n}\n","\"use client\";\n\nimport { create } from \"zustand\";\nimport type { ToolCallContentPartComponent } from \"../../types/ContentPartComponentTypes\";\n\nexport type AssistantToolUIsState = Readonly<{\n getToolUI: (toolName: string) => ToolCallContentPartComponent | null;\n setToolUI: (\n toolName: string,\n render: ToolCallContentPartComponent,\n ) => () => void;\n}>;\n\nexport const makeAssistantToolUIsStore = () =>\n create<AssistantToolUIsState>((set) => {\n const renderers = new Map<string, ToolCallContentPartComponent[]>();\n\n return Object.freeze({\n getToolUI: (name) => {\n const arr = renderers.get(name);\n const last = arr?.at(-1);\n if (last) return last;\n return null;\n },\n setToolUI: (name, render) => {\n let arr = renderers.get(name);\n if (!arr) {\n arr = [];\n renderers.set(name, arr);\n }\n arr.push(render);\n set({}); // notify the store listeners\n\n return () => {\n const index = arr.indexOf(render);\n if (index !== -1) {\n arr.splice(index, 1);\n }\n if (index === arr.length) {\n set({}); // notify the store listeners\n }\n };\n },\n }) satisfies AssistantToolUIsState;\n });\n","import type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useInsertionEffect, useState } from \"react\";\nimport type { ReactThreadRuntime } from \"../../runtimes/core/ReactThreadRuntime\";\nimport type { ThreadContextValue } from \"../react/ThreadContext\";\nimport { ThreadContext } from \"../react/ThreadContext\";\nimport { makeThreadComposerStore } from \"../stores/ThreadComposer\";\nimport { getThreadStateFromRuntime, makeThreadStore } from \"../stores/Thread\";\nimport { makeThreadViewportStore } from \"../stores/ThreadViewport\";\nimport { makeThreadActionStore } from \"../stores/ThreadActions\";\nimport { makeThreadMessagesStore } from \"../stores/ThreadMessages\";\nimport { ThreadRuntimeWithSubscribe } from \"../../runtimes/core/AssistantRuntime\";\nimport { makeThreadRuntimeStore } from \"../stores/ThreadRuntime\";\nimport { subscribeToMainThread } from \"../../runtimes\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype ThreadProviderProps = {\n provider: ThreadRuntimeWithSubscribe;\n};\n\nexport const ThreadProvider: FC<PropsWithChildren<ThreadProviderProps>> = ({\n children,\n provider,\n}) => {\n const [context] = useState<ThreadContextValue>(() => {\n const useThreadRuntime = makeThreadRuntimeStore(provider.thread);\n const useThread = makeThreadStore(useThreadRuntime);\n const useThreadMessages = makeThreadMessagesStore(useThreadRuntime);\n const useThreadActions = makeThreadActionStore(useThreadRuntime);\n const useViewport = makeThreadViewportStore();\n const useComposer = makeThreadComposerStore(useThreadRuntime);\n\n return {\n useThread,\n useThreadRuntime,\n useThreadMessages,\n useThreadActions,\n useComposer,\n useViewport,\n };\n });\n\n // TODO it might make sense to move this into the make* functions\n useEffect(() => {\n const onThreadUpdate = () => {\n const thread = provider.thread;\n\n const oldState = context.useThread.getState();\n const state = getThreadStateFromRuntime(thread);\n if (\n oldState.threadId !== state.threadId ||\n oldState.isDisabled !== state.isDisabled ||\n oldState.isRunning !== state.isRunning ||\n // TODO ensure capabilities is memoized\n oldState.capabilities !== state.capabilities\n ) {\n writableStore(context.useThread).setState(state, true);\n }\n\n if (thread.messages !== context.useThreadMessages.getState()) {\n writableStore(context.useThreadMessages).setState(\n thread.messages,\n true,\n );\n }\n\n const composerState = context.useComposer.getState();\n if (\n thread.composer.isEmpty !== composerState.isEmpty ||\n thread.composer.text !== composerState.text ||\n thread.composer.attachmentAccept !== composerState.attachmentAccept ||\n thread.composer.attachments !== composerState.attachments ||\n state.capabilities.cancel !== composerState.canCancel\n ) {\n writableStore(context.useComposer).setState({\n isEmpty: thread.composer.isEmpty,\n text: thread.composer.text,\n attachmentAccept: thread.composer.attachmentAccept,\n attachments: thread.composer.attachments,\n canCancel: state.capabilities.cancel,\n });\n }\n };\n\n onThreadUpdate();\n return subscribeToMainThread(provider, onThreadUpdate);\n }, [provider, context]);\n\n useInsertionEffect(\n () =>\n provider.subscribe(() => {\n writableStore(context.useThreadRuntime).setState(provider.thread, true);\n }),\n [provider, context],\n );\n\n // subscribe to thread updates\n const Synchronizer = context.useThreadRuntime(\n (t) => (t as ReactThreadRuntime).unstable_synchronizer,\n );\n\n return (\n <ThreadContext.Provider value={context}>\n {Synchronizer && <Synchronizer />}\n {children}\n </ThreadContext.Provider>\n );\n};\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { ThreadComposerState } from \"../stores/ThreadComposer\";\nimport type { ThreadState } from \"../stores/Thread\";\nimport type { ThreadViewportState } from \"../stores/ThreadViewport\";\nimport { ThreadActionsState } from \"../stores/ThreadActions\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadMessagesState } from \"../stores/ThreadMessages\";\nimport { ThreadRuntimeStore } from \"../stores/ThreadRuntime\";\nimport { UseBoundStore } from \"zustand\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\n\nexport type ThreadContextValue = {\n useThread: UseBoundStore<ReadonlyStore<ThreadState>>;\n useThreadRuntime: UseBoundStore<ReadonlyStore<ThreadRuntimeStore>>;\n useThreadMessages: UseBoundStore<ReadonlyStore<ThreadMessagesState>>;\n useThreadActions: UseBoundStore<ReadonlyStore<ThreadActionsState>>;\n useComposer: UseBoundStore<ReadonlyStore<ThreadComposerState>>;\n useViewport: UseBoundStore<ReadonlyStore<ThreadViewportState>>;\n};\n\nexport const ThreadContext = createContext<ThreadContextValue | null>(null);\n\nexport const useThreadContext = createContextHook(\n ThreadContext,\n \"AssistantRuntimeProvider\",\n);\n\nexport const { useThreadRuntime, useThreadRuntimeStore } =\n createContextStoreHook(useThreadContext, \"useThreadRuntime\");\n\nexport const { useThread, useThreadStore } = createContextStoreHook(\n useThreadContext,\n \"useThread\",\n);\n\nexport const { useThreadMessages, useThreadMessagesStore } =\n createContextStoreHook(useThreadContext, \"useThreadMessages\");\n\nexport const { useThreadActions, useThreadActionsStore } =\n createContextStoreHook(useThreadContext, \"useThreadActions\");\n\nexport const {\n useComposer: useThreadComposer,\n useComposerStore: useThreadComposerStore,\n} = createContextStoreHook(useThreadContext, \"useComposer\");\n\nexport const {\n useViewport: useThreadViewport,\n useViewportStore: useThreadViewportStore,\n} = createContextStoreHook(useThreadContext, \"useViewport\");\n","import { create, UseBoundStore } from \"zustand\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { Unsubscribe } from \"../../types/Unsubscribe\";\nimport { ThreadContextValue } from \"../react\";\nimport { ThreadComposerAttachment } from \"./Attachment\";\n\nexport type ThreadComposerState = Readonly<{\n type: \"thread\";\n\n /** @deprecated Use `text` instead. */\n value: string;\n /** @deprecated Use `setText` instead. */\n setValue: (value: string) => void;\n\n attachmentAccept: string;\n\n attachments: readonly ThreadComposerAttachment[];\n addAttachment: (file: File) => void;\n removeAttachment: (attachmentId: string) => void;\n\n text: string;\n setText: (value: string) => void;\n\n reset: () => void;\n\n canCancel: boolean;\n isEditing: true;\n isEmpty: boolean;\n\n send: () => void;\n cancel: () => void;\n focus: () => void;\n onFocus: (listener: () => void) => Unsubscribe;\n}>;\n\nexport const makeThreadComposerStore = (\n useThreadRuntime: ThreadContextValue[\"useThreadRuntime\"],\n): UseBoundStore<ReadonlyStore<ThreadComposerState>> => {\n const focusListeners = new Set<() => void>();\n return create<ThreadComposerState>()((_, get) => {\n const runtime = useThreadRuntime.getState();\n return {\n type: \"thread\",\n\n get value() {\n return get().text;\n },\n setValue(value) {\n get().setText(value);\n },\n\n attachmentAccept: runtime.composer.attachmentAccept,\n\n attachments: runtime.composer.attachments,\n addAttachment: (file) => {\n useThreadRuntime.getState().composer.addAttachment(file);\n },\n removeAttachment: (attachmentId) => {\n useThreadRuntime.getState().composer.removeAttachment(attachmentId);\n },\n reset: () => {\n useThreadRuntime.getState().composer.reset();\n },\n\n text: runtime.composer.text,\n setText: (text) => {\n useThreadRuntime.getState().composer.setText(text);\n },\n\n canCancel: runtime.capabilities.cancel,\n isEditing: true,\n isEmpty: runtime.composer.isEmpty,\n\n send: () => {\n const runtime = useThreadRuntime.getState();\n runtime.composer.send();\n },\n cancel: () => {\n useThreadRuntime.getState().cancelRun();\n },\n focus: () => {\n for (const listener of focusListeners) {\n listener();\n }\n },\n onFocus: (listener) => {\n focusListeners.add(listener);\n return () => {\n focusListeners.delete(listener);\n };\n },\n };\n });\n};\n","import { create } from \"zustand\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadRuntimeStore } from \"./ThreadRuntime\";\n\nexport type ThreadState = Readonly<{\n capabilities: Readonly<RuntimeCapabilities>;\n threadId: string;\n isRunning: boolean;\n isDisabled: boolean;\n}>;\n\nexport type RuntimeCapabilities = {\n switchToBranch: boolean;\n edit: boolean;\n reload: boolean;\n cancel: boolean;\n unstable_copy: boolean;\n speak: boolean;\n attachments: boolean;\n feedback: boolean;\n};\n\nexport const getThreadStateFromRuntime = (\n runtime: ThreadRuntimeStore,\n): ThreadState => {\n const lastMessage = runtime.messages.at(-1);\n return Object.freeze({\n threadId: runtime.threadId,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isRunning:\n lastMessage?.role !== \"assistant\"\n ? false\n : lastMessage.status.type === \"running\",\n });\n};\n\nexport const makeThreadStore = (\n runtimeRef: ReadonlyStore<ThreadRuntimeStore>,\n) => {\n const runtime = runtimeRef.getState();\n return create<ThreadState>(() => getThreadStateFromRuntime(runtime));\n};\n","\"use client\";\nimport { create } from \"zustand\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\n\nexport type ThreadViewportState = Readonly<{\n isAtBottom: boolean;\n scrollToBottom: () => void;\n onScrollToBottom: (callback: () => void) => Unsubscribe;\n}>;\n\nexport const makeThreadViewportStore = () => {\n const scrollToBottomListeners = new Set<() => void>();\n\n return create<ThreadViewportState>(() => ({\n isAtBottom: true,\n scrollToBottom: () => {\n for (const listener of scrollToBottomListeners) {\n listener();\n }\n },\n onScrollToBottom: (callback) => {\n scrollToBottomListeners.add(callback);\n return () => {\n scrollToBottomListeners.delete(callback);\n };\n },\n }));\n};\n","import { create } from \"zustand\";\nimport type { AppendMessage } from \"../../types/AssistantTypes\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadRuntimeStore } from \"./ThreadRuntime\";\nimport { SpeechSynthesisAdapter } from \"../../runtimes/speech/SpeechAdapterTypes\";\nimport { ModelConfig } from \"../../types\";\n\nexport type AddToolResultOptions = {\n messageId: string;\n toolName: string;\n toolCallId: string;\n result: any;\n};\n\nexport type SubmitFeedbackOptions = {\n messageId: string;\n type: \"negative\" | \"positive\";\n};\n\nexport type ThreadActionsState = Readonly<{\n getBranches: (messageId: string) => readonly string[];\n switchToBranch: (branchId: string) => void;\n\n append: (message: AppendMessage) => void;\n startRun: (parentId: string | null) => void;\n cancelRun: () => void;\n\n addToolResult: (options: AddToolResultOptions) => void;\n\n speak: (messageId: string) => SpeechSynthesisAdapter.Utterance;\n\n submitFeedback: (feedback: SubmitFeedbackOptions) => void;\n\n getModelConfig: () => ModelConfig;\n}>;\n\nexport const makeThreadActionStore = (\n runtimeStore: ReadonlyStore<ThreadRuntimeStore>,\n) => {\n return create<ThreadActionsState>(() =>\n Object.freeze({\n getBranches: (messageId) =>\n runtimeStore.getState().getBranches(messageId),\n switchToBranch: (branchId) =>\n runtimeStore.getState().switchToBranch(branchId),\n\n startRun: (parentId) => runtimeStore.getState().startRun(parentId),\n append: (message) => runtimeStore.getState().append(message),\n cancelRun: () => runtimeStore.getState().cancelRun(),\n\n addToolResult: (options) =>\n runtimeStore.getState().addToolResult(options),\n\n speak: (messageId) => runtimeStore.getState().speak(messageId),\n\n submitFeedback: ({ messageId, type }) =>\n runtimeStore.getState().submitFeedback({ messageId, type }),\n\n getModelConfig: () => runtimeStore.getState().getModelConfig(),\n }),\n );\n};\n","import { create } from \"zustand\";\nimport type { ThreadMessage } from \"../../types/AssistantTypes\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { ThreadRuntimeStore } from \"./ThreadRuntime\";\n\nexport type ThreadMessagesState = readonly ThreadMessage[];\n\nexport const makeThreadMessagesStore = (\n runtimeRef: ReadonlyStore<ThreadRuntimeStore>,\n) => {\n return create<ThreadMessagesState>(() => runtimeRef.getState().messages);\n};\n","import { create } from \"zustand\";\nimport { ThreadRuntime } from \"../../runtimes\";\n\nexport type ThreadRuntimeStore = ThreadRuntime;\n\nexport const makeThreadRuntimeStore = (runtime: ThreadRuntime) => {\n return create<ThreadRuntimeStore>(() => runtime);\n};\n","import { Unsubscribe } from \"../../types\";\nimport { ThreadRuntimeWithSubscribe } from \"./AssistantRuntime\";\n\nexport const subscribeToMainThread = (\n runtime: ThreadRuntimeWithSubscribe,\n callback: () => void,\n) => {\n let first = true;\n let cleanup: Unsubscribe | undefined;\n const inner = () => {\n cleanup?.();\n cleanup = runtime.thread.subscribe(callback);\n\n if (!first) {\n callback();\n }\n first = false;\n };\n\n const unsubscribe = runtime.subscribe(inner);\n inner();\n\n return () => {\n unsubscribe();\n cleanup?.();\n };\n};\n","\"use client\";\n\nimport { useInsertionEffect, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntime } from \"./LocalRuntime\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\n\nexport const useLocalRuntime = (\n adapter: ChatModelAdapter,\n options: LocalRuntimeOptions = {},\n) => {\n const [runtime] = useState(() => new LocalRuntime(adapter, options));\n\n useInsertionEffect(() => {\n runtime.adapter = adapter;\n runtime.options = options;\n });\n\n return runtime;\n};\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport type { AssistantRuntime } from \"./AssistantRuntime\";\nimport { ReactThreadRuntime } from \"./ReactThreadRuntime\";\n\nexport abstract class BaseAssistantRuntime<\n TThreadRuntime extends ReactThreadRuntime,\n> implements AssistantRuntime\n{\n constructor(private _thread: TThreadRuntime) {\n this._thread = _thread;\n }\n\n get thread() {\n return this._thread;\n }\n\n set thread(thread: TThreadRuntime) {\n this._thread = thread;\n this.subscriptionHandler();\n }\n\n public abstract switchToNewThread(): void;\n\n public abstract registerModelConfigProvider(\n provider: ModelConfigProvider,\n ): Unsubscribe;\n public abstract switchToThread(threadId: string | null): void;\n\n private _subscriptions = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private subscriptionHandler = () => {\n for (const callback of this._subscriptions) callback();\n };\n}\n","export { ThreadRuntimeComposer } from \"./runtimes/utils/ThreadRuntimeComposer\";\nexport { ProxyConfigProvider } from \"./utils/ProxyConfigProvider\";\nexport { MessageRepository } from \"./runtimes/utils/MessageRepository\";\nexport { BaseAssistantRuntime } from \"./runtimes/core/BaseAssistantRuntime\";\nexport * from \"./utils/smooth\";\nexport { TooltipIconButton } from \"./ui/base/tooltip-icon-button\";\nexport { generateId } from \"./utils/idUtils\";\n","import { ThreadComposerAttachment } from \"../../context/stores/Attachment\";\nimport { AppendMessage } from \"../../types\";\nimport { AttachmentAdapter } from \"../attachment/AttachmentAdapter\";\nimport { ThreadRuntime } from \"../core\";\n\nexport class ThreadRuntimeComposer implements ThreadRuntime.Composer {\n private _attachmentAdapter?: AttachmentAdapter | undefined;\n\n public attachmentAccept: string = \"*\";\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\n }\n\n constructor(\n private runtime: {\n messages: ThreadRuntime[\"messages\"];\n append: (message: AppendMessage) => void;\n },\n private notifySubscribers: () => void,\n ) {}\n\n public setAttachmentAdapter(adapter: AttachmentAdapter | undefined) {\n this._attachmentAdapter = adapter;\n const accept = adapter?.accept ?? \"*\";\n if (this.attachmentAccept !== accept) {\n this.attachmentAccept = accept;\n return true;\n }\n return false;\n }\n\n private _attachments: ThreadComposerAttachment[] = [];\n\n public get attachments() {\n return this._attachments;\n }\n\n async addAttachment(file: File) {\n if (!this._attachmentAdapter)\n throw new Error(\"Attachments are not supported\");\n\n const attachment = await this._attachmentAdapter.add({ file });\n\n this._attachments = [...this._attachments, attachment];\n this.notifySubscribers();\n }\n\n async removeAttachment(attachmentId: string) {\n if (!this._attachmentAdapter)\n throw new Error(\"Attachments are not supported\");\n\n const index = this._attachments.findIndex((a) => a.id === attachmentId);\n if (index === -1) throw new Error(\"Attachment not found\");\n const attachment = this._attachments[index]!;\n\n await this._attachmentAdapter.remove(attachment);\n\n this._attachments = this._attachments.toSpliced(index, 1);\n this.notifySubscribers();\n }\n\n private _text = \"\";\n\n get text() {\n return this._text;\n }\n\n setText(value: string) {\n this._text = value;\n this.notifySubscribers();\n }\n\n reset() {\n this._text = \"\";\n this._attachments = [];\n this.notifySubscribers();\n }\n\n public async send() {\n const attachments = this._attachmentAdapter\n ? await Promise.all(\n this.attachments.map(\n async (a) => await this._attachmentAdapter!.send(a),\n ),\n )\n : [];\n\n this.runtime.append({\n parentId: this.runtime.messages.at(-1)?.id ?? null,\n role: \"user\",\n content: this.text ? [{ type: \"text\", text: this.text }] : [],\n attachments,\n });\n this.reset();\n }\n}\n","\"use client\";\nimport {\n type ModelConfigProvider,\n mergeModelConfigs,\n} from \"../types/ModelConfigTypes\";\n\nexport class ProxyConfigProvider implements ModelConfigProvider {\n private _providers = new Set<ModelConfigProvider>();\n\n getModelConfig() {\n return mergeModelConfigs(this._providers);\n }\n\n registerModelConfigProvider(provider: ModelConfigProvider) {\n this._providers.add(provider);\n return () => {\n this._providers.delete(provider);\n };\n }\n}\n","import { customAlphabet } from \"nanoid/non-secure\";\n\nexport const generateId = customAlphabet(\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n 7,\n);\n\nconst optimisticPrefix = \"__optimistic__\";\nexport const generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;\nexport const isOptimisticId = (id: string) => id.startsWith(optimisticPrefix);\n","import { MessageAttachment } from \"../../../context/stores/Attachment\";\nimport { generateId } from \"../../../internal\";\nimport {\n ThreadMessage,\n CoreMessage,\n ToolCallContentPart,\n MessageStatus,\n} from \"../../../types\";\n\nexport const fromCoreMessages = (\n message: readonly CoreMessage[],\n): ThreadMessage[] => {\n return message.map((message) => fromCoreMessage(message));\n};\n\nexport const fromCoreMessage = (\n message: CoreMessage,\n {\n id = generateId(),\n status = { type: \"complete\", reason: \"unknown\" } as MessageStatus,\n attachments = [] as readonly MessageAttachment[],\n } = {},\n): ThreadMessage => {\n const commonProps = {\n id,\n createdAt: new Date(),\n };\n\n const role = message.role;\n switch (role) {\n case \"assistant\":\n return {\n ...commonProps,\n role,\n content: message.content.map((part) => {\n if (part.type === \"tool-call\") {\n return {\n ...part,\n argsText: JSON.stringify(part.args),\n } satisfies ToolCallContentPart;\n }\n return part;\n }),\n status,\n } satisfies ThreadMessage;\n\n case \"user\":\n return {\n ...commonProps,\n role,\n content: message.content,\n attachments,\n } satisfies ThreadMessage;\n\n case \"system\":\n return {\n ...commonProps,\n role,\n content: message.content,\n } satisfies ThreadMessage;\n\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n};\n","import type { CoreMessage, ThreadMessage } from \"../../types/AssistantTypes\";\nimport { generateOptimisticId } from \"../../utils/idUtils\";\nimport { fromCoreMessage } from \"../edge/converters/fromCoreMessage\";\n\ntype RepositoryParent = {\n children: string[];\n next: RepositoryMessage | null;\n};\n\ntype RepositoryMessage = RepositoryParent & {\n prev: RepositoryMessage | null;\n current: ThreadMessage;\n level: number;\n};\n\nexport interface ExportedMessageRepository {\n headId?: string | null;\n messages: Array<{\n message: ThreadMessage;\n parentId: string | null;\n }>;\n}\n\nconst findHead = (\n message: RepositoryMessage | RepositoryParent,\n): RepositoryMessage | null => {\n if (message.next) return findHead(message.next);\n if (\"current\" in message) return message;\n return null;\n};\n\nexport class MessageRepository {\n private messages = new Map<string, RepositoryMessage>(); // message_id -> item\n private head: RepositoryMessage | null = null;\n private root: RepositoryParent = {\n children: [],\n next: null,\n };\n\n private performOp(\n newParent: RepositoryMessage | null,\n child: RepositoryMessage,\n operation: \"cut\" | \"link\" | \"relink\",\n ) {\n const parentOrRoot = child.prev ?? this.root;\n const newParentOrRoot = newParent ?? this.root;\n\n if (operation === \"relink\" && parentOrRoot === newParentOrRoot) return;\n\n // cut\n if (operation !== \"link\") {\n // remove from parentOrRoot.children\n parentOrRoot.children = parentOrRoot.children.filter(\n (m) => m !== child.current.id,\n );\n\n // update parentOrRoot.next\n if (parentOrRoot.next === child) {\n const fallbackId = parentOrRoot.children.at(-1);\n const fallback = fallbackId ? this.messages.get(fallbackId) : null;\n if (fallback === undefined) {\n throw new Error(\n \"MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.\",\n );\n }\n parentOrRoot.next = fallback;\n }\n }\n\n // link\n if (operation !== \"cut\") {\n // ensure the child is not part of parent tree\n for (\n let current: RepositoryMessage | null = newParent;\n current;\n current = current.prev\n ) {\n if (current.current.id === child.current.id) {\n throw new Error(\n \"MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.\",\n );\n }\n }\n\n // add to parentOrRoot.children\n newParentOrRoot.children = [\n ...newParentOrRoot.children,\n child.current.id,\n ];\n\n // update parentOrRoot.next\n if (findHead(child) === this.head || newParentOrRoot.next === null) {\n newParentOrRoot.next = child;\n }\n\n child.prev = newParent;\n }\n }\n getMessages() {\n const messages = new Array<ThreadMessage>(this.head?.level ?? 0);\n for (let current = this.head; current; current = current.prev) {\n messages[current.level] = current.current;\n }\n return messages;\n }\n\n addOrUpdateMessage(parentId: string | null, message: ThreadMessage) {\n const existingItem = this.messages.get(message.id);\n const prev = parentId ? this.messages.get(parentId) : null;\n if (prev === undefined)\n throw new Error(\n \"MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n // update existing message\n if (existingItem) {\n existingItem.current = message;\n this.performOp(prev, existingItem, \"relink\");\n return;\n }\n\n // create a new message\n const newItem: RepositoryMessage = {\n prev,\n current: message,\n next: null,\n children: [],\n level: prev ? prev.level + 1 : 0,\n };\n\n this.messages.set(message.id, newItem);\n this.performOp(prev, newItem, \"link\");\n\n if (this.head === prev) {\n this.head = newItem;\n }\n }\n\n getMessage(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n return {\n parentId: message.prev?.current.id ?? null,\n message: message.current,\n };\n }\n\n appendOptimisticMessage(parentId: string | null, message: CoreMessage) {\n let optimisticId: string;\n do {\n optimisticId = generateOptimisticId();\n } while (this.messages.has(optimisticId));\n\n this.addOrUpdateMessage(\n parentId,\n fromCoreMessage(message, {\n id: optimisticId,\n status: { type: \"running\" },\n }),\n );\n\n return optimisticId;\n }\n\n deleteMessage(messageId: string, replacementId?: string | null | undefined) {\n const message = this.messages.get(messageId);\n\n if (!message)\n throw new Error(\n \"MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const replacement =\n replacementId === undefined\n ? message.prev // if no replacementId is provided, use the parent\n : replacementId === null\n ? null\n : this.messages.get(replacementId);\n if (replacement === undefined)\n throw new Error(\n \"MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.\",\n );\n\n for (const child of message.children) {\n const childMessage = this.messages.get(child);\n if (!childMessage)\n throw new Error(\n \"MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.\",\n );\n this.performOp(replacement, childMessage, \"relink\");\n }\n\n this.performOp(null, message, \"cut\");\n this.messages.delete(messageId);\n\n if (this.head === message) {\n this.head = findHead(replacement ?? this.root);\n }\n }\n\n getBranches(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const { children } = message.prev ?? this.root;\n return children;\n }\n\n switchToBranch(messageId: string) {\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.\",\n );\n\n const prevOrRoot = message.prev ?? this.root;\n prevOrRoot.next = message;\n\n this.head = findHead(message);\n }\n\n resetHead(messageId: string | null) {\n if (messageId === null) {\n this.head = null;\n return;\n }\n\n const message = this.messages.get(messageId);\n if (!message)\n throw new Error(\n \"MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.\",\n );\n\n this.head = message;\n for (\n let current: RepositoryMessage | null = message;\n current;\n current = current.prev\n ) {\n if (current.prev) {\n current.prev.next = current;\n }\n }\n }\n\n export(): ExportedMessageRepository {\n const exportItems: ExportedMessageRepository[\"messages\"] = [];\n\n // hint: we are relying on the insertion order of the messages\n // this is important for the import function to properly link the messages\n for (const [, message] of this.messages) {\n exportItems.push({\n message: message.current,\n parentId: message.prev?.current.id ?? null,\n });\n }\n\n return {\n headId: this.head?.current.id ?? null,\n messages: exportItems,\n };\n }\n\n import({ headId, messages }: ExportedMessageRepository) {\n for (const { message, parentId } of messages) {\n this.addOrUpdateMessage(parentId, message);\n }\n\n // switch to the saved head id if it is not the most recent message\n this.resetHead(headId ?? messages.at(-1)?.message.id ?? null);\n }\n}\n","\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useMessage } from \"../../context\";\nimport { ContentPartStatus } from \"../../types/AssistantTypes\";\nimport { TextContentPartState } from \"../../context/stores/ContentPart\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useSmoothStatusStore } from \"./SmoothContext\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\n\nclass TextStreamAnimator {\n private animationFrameId: number | null = null;\n private lastUpdateTime: number = Date.now();\n\n public targetText: string = \"\";\n\n constructor(\n public currentText: string,\n private setText: (newText: string) => void,\n ) {}\n\n start() {\n if (this.animationFrameId !== null) return;\n this.lastUpdateTime = Date.now();\n this.animate();\n }\n\n stop() {\n if (this.animationFrameId !== null) {\n cancelAnimationFrame(this.animationFrameId);\n this.animationFrameId = null;\n }\n }\n\n private animate = () => {\n const currentTime = Date.now();\n const deltaTime = currentTime - this.lastUpdateTime;\n let timeToConsume = deltaTime;\n\n const remainingChars = this.targetText.length - this.currentText.length;\n const baseTimePerChar = Math.min(5, 250 / remainingChars);\n\n let charsToAdd = 0;\n while (timeToConsume >= baseTimePerChar && charsToAdd < remainingChars) {\n charsToAdd++;\n timeToConsume -= baseTimePerChar;\n }\n\n if (charsToAdd !== remainingChars) {\n this.animationFrameId = requestAnimationFrame(this.animate);\n } else {\n this.animationFrameId = null;\n }\n if (charsToAdd === 0) return;\n\n this.currentText = this.targetText.slice(\n 0,\n this.currentText.length + charsToAdd,\n );\n this.lastUpdateTime = currentTime - timeToConsume;\n this.setText(this.currentText);\n };\n}\n\nconst SMOOTH_STATUS: ContentPartStatus = Object.freeze({\n type: \"running\",\n});\n\nexport const useSmooth = (\n state: TextContentPartState,\n smooth: boolean = false,\n): TextContentPartState => {\n const {\n part: { text },\n } = state;\n const id = useMessage({\n optional: true,\n selector: (m: { message: { id: string } }) => m.message.id,\n });\n\n const idRef = useRef(id);\n const [displayedText, setDisplayedText] = useState(text);\n\n const smoothStatusStore = useSmoothStatusStore({ optional: true });\n const setText = useCallbackRef((text: string) => {\n setDisplayedText(text);\n if (smoothStatusStore) {\n writableStore(smoothStatusStore).setState(\n text !== state.part.text ? SMOOTH_STATUS : state.status,\n );\n }\n });\n\n // TODO this is hacky\n useEffect(() => {\n if (smoothStatusStore) {\n writableStore(smoothStatusStore).setState(\n text !== state.part.text ? SMOOTH_STATUS : state.status,\n );\n }\n }, [smoothStatusStore, text, displayedText, state.status, state.part.text]);\n\n const [animatorRef] = useState<TextStreamAnimator>(\n new TextStreamAnimator(text, setText),\n );\n\n useEffect(() => {\n if (!smooth) {\n animatorRef.stop();\n return;\n }\n\n if (idRef.current !== id || !text.startsWith(animatorRef.targetText)) {\n idRef.current = id;\n setText(text);\n\n animatorRef.currentText = text;\n animatorRef.targetText = text;\n animatorRef.stop();\n\n return;\n }\n\n animatorRef.targetText = text;\n animatorRef.start();\n }, [setText, animatorRef, id, smooth, text]);\n\n useEffect(() => {\n return () => {\n animatorRef.stop();\n };\n }, [animatorRef]);\n\n return useMemo(\n () =>\n smooth\n ? {\n part: { type: \"text\", text: displayedText },\n status: text === displayedText ? state.status : SMOOTH_STATUS,\n }\n : state,\n [smooth, displayedText, state, text],\n );\n};\n","import {\n createContext,\n FC,\n forwardRef,\n PropsWithChildren,\n useContext,\n useState,\n} from \"react\";\nimport { ReadonlyStore } from \"../../context/ReadonlyStore\";\nimport { create, UseBoundStore } from \"zustand\";\nimport {\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../../types/AssistantTypes\";\nimport { useContentPartStore } from \"../../context/react/ContentPartContext\";\nimport { createContextStoreHook } from \"../../context/react/utils/createContextStoreHook\";\n\ntype SmoothContextValue = {\n useSmoothStatus: UseBoundStore<\n ReadonlyStore<ContentPartStatus | ToolCallContentPartStatus>\n >;\n};\n\nconst SmoothContext = createContext<SmoothContextValue | null>(null);\n\nconst makeSmoothContext = (\n initialState: ContentPartStatus | ToolCallContentPartStatus,\n) => {\n const useSmoothStatus = create(() => initialState);\n return { useSmoothStatus };\n};\n\nexport const SmoothContextProvider: FC<PropsWithChildren> = ({ children }) => {\n const outer = useSmoothContext({ optional: true });\n const contentPartStore = useContentPartStore();\n\n const [context] = useState(() =>\n makeSmoothContext(contentPartStore.getState().status),\n );\n\n // do not wrap if there is an outer SmoothContextProvider\n if (outer) return children;\n\n return (\n <SmoothContext.Provider value={context}>{children}</SmoothContext.Provider>\n );\n};\n\nexport const withSmoothContextProvider = <C extends React.ComponentType<any>>(\n Component: C,\n): C => {\n const Wrapped = forwardRef((props, ref) => {\n return (\n <SmoothContextProvider>\n <Component {...(props as any)} ref={ref} />\n </SmoothContextProvider>\n );\n });\n Wrapped.displayName = Component.displayName;\n return Wrapped as any;\n};\n\nfunction useSmoothContext(options?: {\n optional?: false | undefined;\n}): SmoothContextValue;\nfunction useSmoothContext(options?: {\n optional?: boolean | undefined;\n}): SmoothContextValue | null;\nfunction useSmoothContext(options?: { optional?: boolean | undefined }) {\n const context = useContext(SmoothContext);\n if (!options?.optional && !context)\n throw new Error(\n \"This component must be used within a SmoothContextProvider.\",\n );\n return context;\n}\n\nexport const { useSmoothStatus, useSmoothStatusStore } = createContextStoreHook(\n useSmoothContext,\n \"useSmoothStatus\",\n);\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { ContentPartState } from \"../stores/ContentPart\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type ContentPartContextValue = {\n useContentPart: UseBoundStore<ReadonlyStore<ContentPartState>>;\n};\n\nexport const ContentPartContext = createContext<ContentPartContextValue | null>(\n null,\n);\n\nexport const useContentPartContext = createContextHook(\n ContentPartContext,\n \"a component passed to <MessagePrimitive.Content components={...}>\",\n);\n\nexport const { useContentPart, useContentPartStore } = createContextStoreHook(\n useContentPartContext,\n \"useContentPart\",\n);\n","import type { StoreApi } from \"zustand\";\n\nexport type ReadonlyStore<T> = Omit<StoreApi<T>, \"setState\" | \"destroy\">;\n\nexport const writableStore = <T>(store: ReadonlyStore<T> | undefined) => {\n return store as unknown as StoreApi<T>;\n};\n","\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"./tooltip\";\nimport { Button, ButtonProps } from \"./button\";\n\nexport type TooltipIconButtonProps = ButtonProps & {\n tooltip: string;\n side?: \"top\" | \"bottom\" | \"left\" | \"right\";\n};\n\nexport const TooltipIconButton = forwardRef<\n HTMLButtonElement,\n TooltipIconButtonProps\n>(({ children, tooltip, side = \"bottom\", ...rest }, ref) => {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button variant=\"ghost\" size=\"icon\" {...rest} ref={ref}>\n {children}\n <span className=\"aui-sr-only\">{tooltip}</span>\n </Button>\n </TooltipTrigger>\n <TooltipContent side={side}>{tooltip}</TooltipContent>\n </Tooltip>\n );\n});\n\nTooltipIconButton.displayName = \"TooltipIconButton\";\n","\"use client\";\n\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\";\nimport { withDefaults } from \"../utils/withDefaults\";\nimport { FC } from \"react\";\n\nexport const Tooltip: FC<TooltipPrimitive.TooltipProps> = (props) => {\n return (\n <TooltipPrimitive.Provider>\n <TooltipPrimitive.Root {...props} />\n </TooltipPrimitive.Provider>\n );\n};\n\nTooltip.displayName = \"Tooltip\";\n\nexport const TooltipTrigger = TooltipPrimitive.Trigger;\n\nexport const TooltipContent = withDefaults(TooltipPrimitive.Content, {\n sideOffset: 4,\n className: \"aui-tooltip-content\",\n});\n\nTooltipContent.displayName = \"TooltipContent\";\n","import {\n ComponentPropsWithoutRef,\n ElementRef,\n ElementType,\n forwardRef,\n} from \"react\";\nimport classNames from \"classnames\";\n\nexport const withDefaultProps =\n <TProps extends { className?: string }>({\n className,\n ...defaultProps\n }: Partial<TProps>) =>\n ({ className: classNameProp, ...props }: TProps) => {\n return {\n className: classNames(className, classNameProp),\n ...defaultProps,\n ...props,\n } as TProps;\n };\n\nexport const withDefaults = <TComponent extends ElementType>(\n Component: TComponent,\n defaultProps: Partial<ComponentPropsWithoutRef<TComponent>>,\n) => {\n type TComponentProps = typeof defaultProps;\n const getProps = withDefaultProps<TComponentProps>(defaultProps);\n const WithDefaults = forwardRef<ElementRef<TComponent>, TComponentProps>(\n (props, ref) => {\n const ComponentAsAny = Component as any;\n return <ComponentAsAny {...getProps(props as any)} ref={ref} />;\n },\n );\n WithDefaults.displayName =\n \"withDefaults(\" +\n (typeof Component === \"string\" ? Component : Component.displayName) +\n \")\";\n return WithDefaults;\n};\n","import { cva, type VariantProps } from \"class-variance-authority\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { ElementRef, forwardRef } from \"react\";\n\nconst buttonVariants = cva(\"aui-button\", {\n variants: {\n variant: {\n default: \"aui-button-primary\",\n outline: \"aui-button-outline\",\n ghost: \"aui-button-ghost\",\n },\n size: {\n default: \"aui-button-medium\",\n icon: \"aui-button-icon\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n});\n\ntype ButtonElement = ElementRef<typeof Primitive.button>;\n\nexport type ButtonProps = React.ComponentPropsWithoutRef<\n typeof Primitive.button\n> &\n VariantProps<typeof buttonVariants>;\n\nconst Button = forwardRef<ButtonElement, ButtonProps>(\n ({ className, variant, size, ...props }, ref) => {\n return (\n <Primitive.button\n className={buttonVariants({ variant, size, className })}\n {...props}\n ref={ref}\n />\n );\n },\n);\n\nButton.displayName = \"Button\";\n\nexport { Button, buttonVariants };\n","import { LanguageModelV1Message } from \"@ai-sdk/provider\";\nimport { CoreMessage, ToolCallContentPart } from \"../../../types\";\n\ntype fromLanguageModelMessagesOptions = {\n mergeRoundtrips: boolean;\n};\n\nexport const fromLanguageModelMessages = (\n lm: LanguageModelV1Message[],\n { mergeRoundtrips }: fromLanguageModelMessagesOptions,\n): CoreMessage[] => {\n const messages: CoreMessage[] = [];\n\n for (const lmMessage of lm) {\n const role = lmMessage.role;\n switch (role) {\n case \"system\": {\n messages.push({\n role: \"system\",\n content: [\n {\n type: \"text\",\n text: lmMessage.content,\n },\n ],\n });\n break;\n }\n case \"user\": {\n messages.push({\n role: \"user\",\n content: lmMessage.content.map((part) => {\n const type = part.type;\n switch (type) {\n case \"text\": {\n return {\n type: \"text\",\n text: part.text,\n };\n }\n case \"image\": {\n if (part.image instanceof URL) {\n return {\n type: \"image\",\n image: part.image.href,\n };\n }\n throw new Error(\"Only images with URL data are supported\");\n }\n default: {\n const unhandledType: never = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n }\n }),\n });\n break;\n }\n case \"assistant\": {\n const newContent = lmMessage.content.map((part) => {\n if (part.type === \"tool-call\") {\n return {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n argsText: JSON.stringify(part.args),\n args: part.args as Record<string, unknown>,\n } satisfies ToolCallContentPart;\n }\n return part;\n });\n\n if (mergeRoundtrips) {\n const previousMessage = messages[messages.length - 1];\n if (previousMessage?.role === \"assistant\") {\n previousMessage.content.push(...newContent);\n break;\n }\n }\n\n messages.push({\n role: \"assistant\",\n content: newContent,\n });\n break;\n }\n case \"tool\": {\n const previousMessage = messages[messages.length - 1];\n if (previousMessage?.role !== \"assistant\")\n throw new Error(\n \"A tool message must be preceded by an assistant message.\",\n );\n\n for (const tool of lmMessage.content) {\n const toolCall = previousMessage.content.find(\n (c): c is ToolCallContentPart =>\n c.type === \"tool-call\" && c.toolCallId === tool.toolCallId,\n );\n if (!toolCall)\n throw new Error(\"Received tool result for an unknown tool call.\");\n if (toolCall.toolName !== tool.toolName)\n throw new Error(\"Tool call name mismatch.\");\n\n toolCall.result = tool.result;\n if (tool.isError) {\n toolCall.isError = true;\n }\n }\n\n break;\n }\n\n default: {\n const unhandledRole: never = role;\n throw new Error(`Unknown message role: ${unhandledRole}`);\n }\n }\n }\n\n return messages;\n};\n","import { LanguageModelV1FunctionTool } from \"@ai-sdk/provider\";\nimport { Tool } from \"../../../types/ModelConfigTypes\";\n\nexport const fromLanguageModelTools = (\n tools: LanguageModelV1FunctionTool[],\n): Record<string, Tool<any, any>> => {\n return Object.fromEntries(\n tools.map((tool) => [\n tool.name,\n {\n description: tool.description,\n parameters: tool.parameters,\n },\n ]),\n );\n};\n","export function chunkByLineStream() {\n let buffer = \"\";\n\n return new TransformStream({\n transform(chunk, controller) {\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n\n // Process all complete lines\n for (let i = 0; i < lines.length - 1; i++) {\n controller.enqueue(lines[i]);\n }\n\n // Keep the last incomplete line in the buffer\n buffer = lines[lines.length - 1]!;\n },\n flush(controller) {\n // flush any remaining content in the buffer\n if (buffer) {\n controller.enqueue(buffer);\n }\n },\n });\n}\n","import { chunkByLineStream } from \"./chunkByLineStream\";\nimport { PipeableTransformStream } from \"./PipeableTransformStream\";\nimport { StreamPart } from \"./StreamPart\";\n\nconst decodeStreamPart = <T extends Record<string, unknown>>(\n part: string,\n): StreamPart<T> => {\n const index = part.indexOf(\":\");\n if (index === -1) throw new Error(\"Invalid stream part\");\n return {\n type: part.slice(0, index),\n value: JSON.parse(part.slice(index + 1)),\n };\n};\n\nexport function streamPartDecoderStream<T extends Record<string, unknown>>() {\n const decodeStream = new TransformStream<string, StreamPart<T>>({\n transform(chunk, controller) {\n controller.enqueue(decodeStreamPart<T>(chunk));\n },\n });\n\n return new PipeableTransformStream((readable) => {\n return readable\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(chunkByLineStream())\n .pipeThrough(decodeStream);\n });\n}\n","import { streamPartDecoderStream } from \"./streamPartDecoderStream\";\nimport { streamPartEncoderStream } from \"./streamPartEncoderStream\";\nimport { StreamPart } from \"./StreamPart\";\n\nexport declare namespace StreamUtils {\n export { StreamPart };\n}\n\nexport const streamUtils = {\n streamPartEncoderStream,\n streamPartDecoderStream,\n};\n","import { LocalRuntimeOptions, useLocalRuntime } from \"..\";\nimport { useState } from \"react\";\nimport { EdgeChatAdapterOptions, EdgeChatAdapter } from \"./EdgeChatAdapter\";\n\nexport type EdgeRuntimeOptions = EdgeChatAdapterOptions & LocalRuntimeOptions;\n\nexport const useEdgeRuntime = ({\n initialMessages,\n maxToolRoundtrips,\n adapters,\n ...options\n}: EdgeRuntimeOptions) => {\n const [adapter] = useState(() => new EdgeChatAdapter(options));\n return useLocalRuntime(adapter, {\n initialMessages,\n maxToolRoundtrips,\n adapters,\n });\n};\n","import {\n AssistantStreamChunk,\n AssistantStreamChunkType,\n} from \"./AssistantStreamChunkType\";\nimport { StreamPart } from \"./utils/StreamPart\";\nimport { ToolResultStreamPart } from \"./toolResultStream\";\n\nexport function assistantDecoderStream() {\n const toolCallNames = new Map<string, string>();\n let currentToolCall:\n | { id: string; name: string; argsText: string }\n | undefined;\n\n return new TransformStream<\n StreamPart<AssistantStreamChunk>,\n ToolResultStreamPart\n >({\n transform({ type, value }, controller) {\n if (\n currentToolCall &&\n type !== AssistantStreamChunkType.ToolCallArgsTextDelta &&\n type !== AssistantStreamChunkType.Error\n ) {\n controller.enqueue({\n type: \"tool-call\",\n toolCallType: \"function\",\n toolCallId: currentToolCall.id,\n toolName: currentToolCall.name,\n args: currentToolCall.argsText,\n });\n currentToolCall = undefined;\n }\n\n switch (type) {\n case AssistantStreamChunkType.TextDelta: {\n controller.enqueue({\n type: \"text-delta\",\n textDelta: value,\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallBegin: {\n const { id, name } = value;\n toolCallNames.set(id, name);\n currentToolCall = { id, name, argsText: \"\" };\n break;\n }\n case AssistantStreamChunkType.ToolCallArgsTextDelta: {\n const delta = value;\n currentToolCall!.argsText += delta;\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId: currentToolCall!.id,\n toolName: currentToolCall!.name,\n argsTextDelta: delta,\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallResult: {\n controller.enqueue({\n type: \"tool-result\",\n toolCallType: \"function\",\n toolCallId: value.id,\n toolName: toolCallNames.get(value.id)!,\n result: value.result,\n });\n break;\n }\n case AssistantStreamChunkType.Finish: {\n controller.enqueue({\n type: \"finish\",\n ...value,\n });\n break;\n }\n case AssistantStreamChunkType.Error: {\n controller.enqueue({\n type: \"error\",\n error: value,\n });\n break;\n }\n default: {\n const unhandledType: never = type;\n throw new Error(`Unhandled chunk type: ${unhandledType}`);\n }\n }\n },\n });\n}\n","import { ChatModelAdapter, ChatModelRunOptions } from \"../local\";\nimport { ChatModelRunResult } from \"../local/ChatModelAdapter\";\nimport { toCoreMessages } from \"./converters/toCoreMessages\";\nimport { toLanguageModelTools } from \"./converters/toLanguageModelTools\";\nimport { EdgeRuntimeRequestOptions } from \"./EdgeRuntimeRequestOptions\";\nimport { assistantDecoderStream } from \"./streams/assistantDecoderStream\";\nimport { streamPartDecoderStream } from \"./streams/utils/streamPartDecoderStream\";\nimport { runResultStream } from \"./streams/runResultStream\";\nimport { toolResultStream } from \"./streams/toolResultStream\";\n\nexport function asAsyncIterable<T>(\n source: ReadableStream<T>,\n): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]: () => {\n const reader = source.getReader();\n return {\n async next(): Promise<IteratorResult<T, undefined>> {\n const { done, value } = await reader.read();\n return done\n ? { done: true, value: undefined }\n : { done: false, value };\n },\n };\n },\n };\n}\nexport type EdgeChatAdapterOptions = {\n api: string;\n\n credentials?: RequestCredentials;\n headers?: Record<string, string> | Headers;\n body?: object;\n};\n\nexport class EdgeChatAdapter implements ChatModelAdapter {\n constructor(private options: EdgeChatAdapterOptions) {}\n\n async *run({ messages, abortSignal, config }: ChatModelRunOptions) {\n const headers = new Headers(this.options.headers);\n headers.set(\"Content-Type\", \"application/json\");\n\n const result = await fetch(this.options.api, {\n method: \"POST\",\n headers,\n credentials: this.options.credentials ?? \"same-origin\",\n body: JSON.stringify({\n system: config.system,\n messages: toCoreMessages(messages),\n tools: config.tools ? toLanguageModelTools(config.tools) : [],\n ...config.callSettings,\n ...config.config,\n\n ...this.options.body,\n } satisfies EdgeRuntimeRequestOptions),\n signal: abortSignal,\n });\n\n if (result.status !== 200) {\n throw new Error(`Status ${result.status}: ${await result.text()}`);\n }\n\n const stream = result\n .body!.pipeThrough(streamPartDecoderStream())\n .pipeThrough(assistantDecoderStream())\n .pipeThrough(toolResultStream(config.tools, abortSignal))\n .pipeThrough(runResultStream());\n\n let update: ChatModelRunResult | undefined;\n for await (update of asAsyncIterable(stream)) {\n yield update;\n }\n\n if (update === undefined)\n throw new Error(\"No data received from Edge Runtime\");\n }\n}\n","import type { ThreadAssistantMessage } from \"../../types\";\n\nexport const shouldContinue = (result: ThreadAssistantMessage) =>\n result.status?.type === \"requires-action\" &&\n result.status.reason === \"tool-calls\" &&\n result.content.every((c) => c.type !== \"tool-call\" || !!c.result);\n","import { AddToolResultOptions } from \"../../context\";\nimport { generateId } from \"../../internal\";\nimport type {\n ModelConfigProvider,\n AppendMessage,\n ThreadAssistantMessage,\n Unsubscribe,\n} from \"../../types\";\nimport { fromCoreMessage, fromCoreMessages } from \"../edge\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/MessageRepository\";\nimport type { ChatModelAdapter, ChatModelRunResult } from \"./ChatModelAdapter\";\nimport { ThreadRuntimeComposer } from \"../utils/ThreadRuntimeComposer\";\nimport { shouldContinue } from \"./shouldContinue\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { ThreadRuntime } from \"../core\";\nimport { SpeechSynthesisAdapter } from \"../speech\";\nimport { SubmitFeedbackOptions } from \"../../context/stores/ThreadActions\";\n\nexport class LocalThreadRuntime implements ThreadRuntime {\n private _subscriptions = new Set<() => void>();\n\n private abortController: AbortController | null = null;\n private readonly repository = new MessageRepository();\n\n public readonly capabilities = {\n switchToBranch: true,\n edit: true,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speak: false,\n attachments: false,\n feedback: false,\n };\n\n public readonly threadId: string;\n public readonly isDisabled = false;\n\n public get messages() {\n return this.repository.getMessages();\n }\n\n public readonly composer = new ThreadRuntimeComposer(\n this,\n this.notifySubscribers.bind(this),\n );\n\n constructor(\n private configProvider: ModelConfigProvider,\n public adapter: ChatModelAdapter,\n { initialMessages, ...options }: LocalRuntimeOptions,\n ) {\n this.threadId = generateId();\n this.options = options;\n if (initialMessages) {\n let parentId: string | null = null;\n const messages = fromCoreMessages(initialMessages);\n for (const message of messages) {\n this.repository.addOrUpdateMessage(parentId, message);\n parentId = message.id;\n }\n }\n }\n\n public getModelConfig() {\n return this.configProvider.getModelConfig();\n }\n\n private _options!: LocalRuntimeOptions;\n\n public get options() {\n return this._options;\n }\n\n public set options({ initialMessages, ...options }: LocalRuntimeOptions) {\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speak !== canSpeak) {\n this.capabilities.speak = canSpeak;\n hasUpdates = true;\n }\n\n this.composer.setAttachmentAdapter(options.adapters?.attachments);\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n if (hasUpdates) this.notifySubscribers();\n }\n\n public getBranches(messageId: string): string[] {\n return this.repository.getBranches(messageId);\n }\n\n public switchToBranch(branchId: string): void {\n this.repository.switchToBranch(branchId);\n this.notifySubscribers();\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const newMessage = fromCoreMessage(message, {\n attachments: message.attachments,\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n\n if (message.role === \"user\") {\n await this.startRun(newMessage.id);\n } else {\n this.repository.resetHead(newMessage.id);\n this.notifySubscribers();\n }\n }\n\n public async startRun(parentId: string | null): Promise<void> {\n this.repository.resetHead(parentId);\n\n // add assistant message\n const id = generateId();\n let message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n createdAt: new Date(),\n };\n\n do {\n message = await this.performRoundtrip(parentId, message);\n } while (shouldContinue(message));\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n const messages = this.repository.getMessages();\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n const initialContent = message.content;\n const initialRoundtrips = message.metadata?.roundtrips;\n const initalCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n // TODO deprecated, remove in v0.6\n ...(m.metadata?.roundtrips\n ? {\n roundtrips: [\n ...(initialRoundtrips ?? []),\n ...m.metadata.roundtrips,\n ],\n }\n : undefined),\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.roundtrips\n ? {\n roundtrips: [\n ...(initialRoundtrips ?? []),\n ...m.metadata.roundtrips,\n ],\n }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: { ...(initalCustom ?? {}), ...m.metadata.custom },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this.notifySubscribers();\n };\n\n const maxToolRoundtrips = this.options.maxToolRoundtrips ?? 1;\n const toolRoundtrips = message.metadata?.roundtrips?.length ?? 0;\n if (toolRoundtrips > maxToolRoundtrips) {\n // reached max tool roundtrips\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n }\n\n try {\n const promiseOrGenerator = this.adapter.run({\n messages,\n abortSignal: this.abortController.signal,\n config: this.configProvider.getModelConfig(),\n onUpdate: updateMessage,\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n this.abortController = null;\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n this.abortController = null;\n\n // TODO this should be handled by the run result stream\n if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: { type: \"incomplete\", reason: \"error\", error: e },\n });\n\n throw e;\n }\n }\n return message;\n }\n\n cancelRun(): void {\n if (!this.abortController) return;\n\n this.abortController.abort();\n this.abortController = null;\n }\n\n private notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (!c.result) added = true;\n return {\n ...c,\n result,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n\n if (added && shouldContinue(message)) {\n this.performRoundtrip(parentId, message);\n }\n }\n\n // TODO lift utterance state to thread runtime\n private _utterance: SpeechSynthesisAdapter.Utterance | undefined;\n\n public speak(messageId: string) {\n const adapter = this.options.adapters?.speech;\n if (!adapter) throw new Error(\"Speech adapter not configured\");\n\n const { message } = this.repository.getMessage(messageId);\n\n if (this._utterance) {\n this._utterance.cancel();\n this._utterance = undefined;\n }\n\n const utterance = adapter.speak(message);\n utterance.onEnd(() => {\n if (this._utterance === utterance) {\n this._utterance = undefined;\n }\n });\n this._utterance = utterance;\n\n return this._utterance;\n }\n\n public submitFeedback({ messageId, type }: SubmitFeedbackOptions) {\n const adapter = this.options.adapters?.feedback;\n if (!adapter) throw new Error(\"Feedback adapter not configured\");\n\n const { message } = this.repository.getMessage(messageId);\n adapter.submit({ message, type });\n }\n\n public export() {\n return this.repository.export();\n }\n\n public import(data: ExportedMessageRepository) {\n this.repository.import(data);\n this.notifySubscribers();\n }\n}\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { CoreMessage } from \"../../types/AssistantTypes\";\nimport { BaseAssistantRuntime } from \"../core/BaseAssistantRuntime\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { ProxyConfigProvider } from \"../../internal\";\nimport { LocalThreadRuntime } from \"./LocalThreadRuntime\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { fromCoreMessages } from \"../edge/converters/fromCoreMessage\";\n\nexport class LocalRuntime extends BaseAssistantRuntime<LocalThreadRuntime> {\n private readonly _proxyConfigProvider: ProxyConfigProvider;\n\n constructor(adapter: ChatModelAdapter, options: LocalRuntimeOptions) {\n const proxyConfigProvider = new ProxyConfigProvider();\n super(new LocalThreadRuntime(proxyConfigProvider, adapter, options));\n this._proxyConfigProvider = proxyConfigProvider;\n }\n\n public set adapter(adapter: ChatModelAdapter) {\n this.thread.adapter = adapter;\n }\n\n public set options(options: LocalRuntimeOptions) {\n this.thread.options = options;\n }\n\n registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n\n public switchToNewThread() {\n const { initialMessages, ...options } = this.thread.options;\n\n return (this.thread = new LocalThreadRuntime(\n this._proxyConfigProvider,\n this.thread.adapter,\n options,\n ));\n }\n\n public switchToThread(threadId: string | null) {\n if (threadId !== null) {\n throw new Error(\"LocalRuntime does not yet support switching threads\");\n }\n\n this.switchToNewThread();\n }\n\n public reset({\n initialMessages,\n }: {\n initialMessages?: readonly CoreMessage[] | undefined;\n } = {}) {\n this.switchToThread(null);\n if (!initialMessages) return;\n\n const messages = fromCoreMessages(initialMessages);\n this.thread.import({\n messages: messages.map((m, idx) => ({\n parentId: messages[idx - 1]?.id ?? null,\n message: m,\n })),\n });\n }\n}\n","import { ThreadMessage } from \"../../types\";\n\nexport const symbolInnerMessage = Symbol(\"innerMessage\");\n\nexport type ExternalStoreThreadMessage<T> = ThreadMessage & {\n [symbolInnerMessage]?: T;\n};\n\nexport const getExternalStoreMessage = <T,>(message: ThreadMessage) => {\n return (message as ExternalStoreThreadMessage<T>)[symbolInnerMessage];\n};\n","import { ThreadMessage } from \"../../types\";\n\nexport type ConverterCallback<TIn> = (\n cache: ThreadMessage | undefined,\n message: TIn,\n idx: number,\n) => ThreadMessage;\n\nexport class ThreadMessageConverter {\n private readonly cache = new WeakMap<WeakKey, ThreadMessage>();\n\n convertMessages<TIn extends WeakKey>(\n messages: TIn[],\n converter: ConverterCallback<TIn>,\n ): ThreadMessage[] {\n return messages.map((m, idx) => {\n const cached = this.cache.get(m);\n const newMessage = converter(cached, m, idx);\n this.cache.set(m, newMessage);\n return newMessage;\n });\n }\n}\n","import { MessageStatus } from \"../../types\";\n\nconst AUTO_STATUS_RUNNING = Object.freeze({ type: \"running\" });\nconst AUTO_STATUS_COMPLETE = Object.freeze({\n type: \"complete\",\n reason: \"unknown\",\n});\n\nexport const isAutoStatus = (status: MessageStatus) =>\n status === AUTO_STATUS_RUNNING || status === AUTO_STATUS_COMPLETE;\n\nexport const getAutoStatus = (isLast: boolean, isRunning: boolean) =>\n isLast && isRunning ? AUTO_STATUS_RUNNING : AUTO_STATUS_COMPLETE;\n","import { MessageAttachment } from \"../../context/stores/Attachment\";\nimport {\n MessageStatus,\n TextContentPart,\n ImageContentPart,\n ToolCallContentPart,\n UIContentPart,\n ThreadMessage,\n ThreadAssistantContentPart,\n ThreadAssistantMessage,\n ThreadUserContentPart,\n ThreadUserMessage,\n ThreadSystemMessage,\n} from \"../../types\";\nimport { CoreToolCallContentPart } from \"../../types/AssistantTypes\";\n\nexport type ThreadMessageLike = {\n role: \"assistant\" | \"user\" | \"system\";\n content:\n | string\n | (\n | TextContentPart\n | ImageContentPart\n | ToolCallContentPart<any, any>\n | CoreToolCallContentPart<any, any>\n | UIContentPart\n )[];\n id?: string | undefined;\n createdAt?: Date | undefined;\n status?: MessageStatus | undefined;\n attachments?: MessageAttachment[] | undefined;\n};\n\nexport const fromThreadMessageLike = (\n like: ThreadMessageLike,\n fallbackId: string,\n fallbackStatus: MessageStatus,\n): ThreadMessage => {\n const { role, id, createdAt, attachments, status } = like;\n const common = {\n id: id ?? fallbackId,\n createdAt: createdAt ?? new Date(),\n };\n\n const content =\n typeof like.content === \"string\"\n ? [{ type: \"text\" as const, text: like.content }]\n : like.content;\n\n if (role !== \"user\" && attachments)\n throw new Error(\"Attachments are only supported for user messages\");\n // TODO add in 0.6\n // if (role !== \"assistant\" && status)\n // throw new Error(\"Status is only supported for assistant messages\");\n\n switch (role) {\n case \"assistant\":\n return {\n ...common,\n role,\n content: content\n .map((part): ThreadAssistantContentPart | null => {\n const type = part.type;\n switch (type) {\n case \"text\":\n if (part.text.trim().length === 0) return null;\n return part;\n\n case \"ui\":\n return part;\n\n case \"tool-call\": {\n if (\"argsText\" in part) return part;\n return {\n ...part,\n argsText: JSON.stringify(part.args),\n };\n }\n\n default: {\n const unhandledType: \"image\" = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n }\n })\n .filter((c) => !!c),\n status: status ?? fallbackStatus,\n } satisfies ThreadAssistantMessage;\n\n case \"user\":\n return {\n ...common,\n role,\n content: content.map((part): ThreadUserContentPart => {\n const type = part.type;\n switch (type) {\n case \"text\":\n case \"ui\":\n case \"image\":\n return part;\n\n default: {\n const unhandledType: \"tool-call\" = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n }\n }),\n attachments: attachments ?? [],\n } satisfies ThreadUserMessage;\n\n case \"system\":\n if (content.length !== 1 || content[0]!.type !== \"text\")\n throw new Error(\n \"System messages must have exactly one text content part.\",\n );\n\n return {\n ...common,\n role,\n content: content as [TextContentPart],\n } satisfies ThreadSystemMessage;\n\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n};\n","import type { TextContentPart, ThreadMessage } from \"../types/AssistantTypes\";\n\nexport const getThreadMessageText = (message: ThreadMessage) => {\n const textParts = message.content.filter(\n (part) => part.type === \"text\",\n ) as TextContentPart[];\n\n return textParts.map((part) => part.text).join(\"\\n\\n\");\n};\n","import { ReactThreadRuntime } from \"../core\";\nimport { MessageRepository } from \"../utils/MessageRepository\";\nimport {\n AppendMessage,\n ModelConfigProvider,\n ThreadMessage,\n Unsubscribe,\n} from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { AddToolResultOptions } from \"../../context\";\nimport {\n getExternalStoreMessage,\n symbolInnerMessage,\n} from \"./getExternalStoreMessage\";\nimport { ThreadMessageConverter } from \"./ThreadMessageConverter\";\nimport { getAutoStatus, isAutoStatus } from \"./auto-status\";\nimport { fromThreadMessageLike } from \"./ThreadMessageLike\";\nimport { RuntimeCapabilities } from \"../../context/stores/Thread\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { generateId } from \"../../internal\";\nimport { ThreadRuntimeComposer } from \"../utils/ThreadRuntimeComposer\";\nimport { SubmitFeedbackOptions } from \"../../context/stores/ThreadActions\";\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntime implements ReactThreadRuntime {\n private _subscriptions = new Set<() => void>();\n private repository = new MessageRepository();\n private assistantOptimisticId: string | null = null;\n\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n edit: false,\n reload: false,\n cancel: false,\n unstable_copy: false,\n speak: false,\n attachments: false,\n feedback: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n public threadId!: string;\n public messages!: ThreadMessage[];\n public isDisabled!: boolean;\n public converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n public readonly composer = new ThreadRuntimeComposer(\n this,\n this.notifySubscribers.bind(this),\n );\n\n constructor(\n private configProvider: ModelConfigProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n this.store = store;\n }\n\n public get store() {\n return this._store;\n }\n\n public set store(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n this.threadId = store.threadId ?? this.threadId ?? generateId();\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n this._capabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n edit: this._store.onEdit !== undefined,\n reload: this._store.onReload !== undefined,\n cancel: this._store.onCancel !== undefined,\n speak: this._store.onSpeak !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false, // default true\n attachments: !!this.store.adapters?.attachments,\n feedback: !!this.store.adapters?.feedback,\n };\n\n this.composer.setAttachmentAdapter(this._store.adapters?.attachments);\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this.converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this.notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n const messages = !store.convertMessage\n ? store.messages\n : this.converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === store.messages.length - 1;\n const autoStatus = getAutoStatus(isLast, isRunning);\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const newMessage = fromThreadMessageLike(\n store.convertMessage(m, idx),\n idx.toString(),\n autoStatus,\n );\n (newMessage as any)[symbolInnerMessage] = m;\n return newMessage;\n });\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n\n if (this.assistantOptimisticId) {\n this.repository.deleteMessage(this.assistantOptimisticId);\n this.assistantOptimisticId = null;\n }\n\n if (hasUpcomingMessage(isRunning, messages)) {\n this.assistantOptimisticId = this.repository.appendOptimisticMessage(\n messages.at(-1)?.id ?? null,\n {\n role: \"assistant\",\n content: [],\n },\n );\n }\n\n this.repository.resetHead(\n this.assistantOptimisticId ?? messages.at(-1)?.id ?? null,\n );\n\n this.messages = this.repository.getMessages();\n this.notifySubscribers();\n }\n\n public getModelConfig() {\n return this.configProvider.getModelConfig();\n }\n\n private notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public getBranches(messageId: string): string[] {\n return this.repository.getBranches(messageId);\n }\n\n public switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n }\n\n public async append(message: AppendMessage): Promise<void> {\n if (message.parentId !== (this.messages.at(-1)?.id ?? null)) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async startRun(parentId: string | null): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n await this._store.onReload(parentId);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.onCancel();\n\n if (this.assistantOptimisticId) {\n this.repository.deleteMessage(this.assistantOptimisticId);\n this.assistantOptimisticId = null;\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this.notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult(options);\n }\n\n public speak(messageId: string) {\n if (!this._store.onSpeak)\n throw new Error(\"Runtime does not support speaking.\");\n\n const { message } = this.repository.getMessage(messageId);\n return this._store.onSpeak(message);\n }\n\n public submitFeedback({ messageId, type }: SubmitFeedbackOptions) {\n const adapter = this._store.adapters?.feedback;\n if (!adapter) throw new Error(\"Feedback adapter not configured\");\n\n const { message } = this.repository.getMessage(messageId);\n adapter.submit({ message, type });\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private updateMessages = (messages: ThreadMessage[]) => {\n this._store.setMessages?.(\n messages.flatMap(getExternalStoreMessage).filter((m) => m != null),\n );\n };\n}\n","import { BaseAssistantRuntime, ProxyConfigProvider } from \"../../internal\";\nimport { ModelConfigProvider } from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { ExternalStoreThreadRuntime } from \"./ExternalStoreThreadRuntime\";\n\nexport class ExternalStoreRuntime extends BaseAssistantRuntime<ExternalStoreThreadRuntime> {\n private readonly _proxyConfigProvider;\n\n constructor(store: ExternalStoreAdapter<any>) {\n const provider = new ProxyConfigProvider();\n super(new ExternalStoreThreadRuntime(provider, store));\n this._proxyConfigProvider = provider;\n }\n\n public get store() {\n return this.thread.store;\n }\n\n public set store(store: ExternalStoreAdapter<any>) {\n this.thread.store = store;\n }\n\n public getModelConfig() {\n return this._proxyConfigProvider.getModelConfig();\n }\n\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n\n public async switchToNewThread() {\n if (!this.store.onSwitchToNewThread)\n throw new Error(\"Runtime does not support switching to new threads.\");\n\n this.thread = new ExternalStoreThreadRuntime(this._proxyConfigProvider, {\n ...this.store,\n messages: [],\n });\n await this.store.onSwitchToNewThread();\n }\n\n public async switchToThread(threadId: string | null) {\n if (threadId !== null) {\n if (!this.store.onSwitchToThread)\n throw new Error(\"Runtime does not support switching threads.\");\n\n this.thread = new ExternalStoreThreadRuntime(this._proxyConfigProvider, {\n ...this.store,\n messages: [], // ignore messages until rerender\n });\n this.store.onSwitchToThread(threadId);\n } else {\n this.switchToNewThread();\n }\n }\n}\n","import { useEffect, useState } from \"react\";\nimport { ExternalStoreRuntime } from \"./ExternalStoreRuntime\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\n\nexport const useExternalStoreRuntime = <T,>(store: ExternalStoreAdapter<T>) => {\n const [runtime] = useState(() => new ExternalStoreRuntime(store));\n\n useEffect(() => {\n runtime.store = store;\n });\n\n return runtime;\n};\n","import { useMemo } from \"react\";\nimport { ThreadMessageConverter } from \"./ThreadMessageConverter\";\nimport {\n getExternalStoreMessage,\n symbolInnerMessage,\n} from \"./getExternalStoreMessage\";\nimport { fromThreadMessageLike, ThreadMessageLike } from \"./ThreadMessageLike\";\nimport { getAutoStatus, isAutoStatus } from \"./auto-status\";\nimport { ToolCallContentPart } from \"../../types\";\n\nexport namespace useExternalMessageConverter {\n export type Message =\n | ThreadMessageLike\n | {\n role: \"tool\";\n toolCallId: string;\n toolName?: string | undefined;\n result: any;\n };\n\n export type Callback<T> = (message: T) => Message | Message[];\n}\n\ntype CallbackResult<T> = {\n input: T;\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype ChunkResult<T> = {\n inputs: T[];\n outputs: useExternalMessageConverter.Message[];\n};\n\nconst joinExternalMessages = (\n messages: useExternalMessageConverter.Message[],\n): ThreadMessageLike => {\n const assistantMessage: ThreadMessageLike & { content: any[] } = {\n role: \"assistant\",\n content: [],\n };\n for (const output of messages) {\n if (output.role === \"tool\") {\n const toolCallIdx = assistantMessage.content.findIndex(\n (c) => c.type === \"tool-call\" && c.toolCallId === output.toolCallId,\n );\n if (toolCallIdx !== -1) {\n const toolCall = assistantMessage.content[\n toolCallIdx\n ]! as ToolCallContentPart;\n if (output.toolName) {\n if (toolCall.toolName !== output.toolName)\n throw new Error(\n `Tool call name ${output.toolCallId} ${output.toolName} does not match existing tool call ${toolCall.toolName}`,\n );\n }\n assistantMessage.content[toolCallIdx] = {\n ...toolCall,\n result: output.result,\n };\n } else {\n throw new Error(\n `Tool call ${output.toolCallId} ${output.toolName} not found in assistant message`,\n );\n }\n } else {\n const content = output.content;\n const role = output.role;\n switch (role) {\n case \"system\":\n case \"user\":\n return { role, content };\n case \"assistant\":\n if (assistantMessage.content.length === 0) {\n assistantMessage.id = output.id;\n assistantMessage.createdAt ??= output.createdAt;\n assistantMessage.status ??= output.status;\n // TODO keep this in sync\n }\n assistantMessage.content.push(...content);\n break;\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n }\n }\n return assistantMessage;\n};\n\nconst chunkExternalMessages = <T,>(callbackResults: CallbackResult<T>[]) => {\n const results: ChunkResult<T>[] = [];\n let isAssistant = false;\n let inputs: T[] = [];\n let outputs: useExternalMessageConverter.Message[] = [];\n\n const flush = () => {\n if (outputs.length) {\n results.push({\n inputs,\n outputs,\n });\n }\n inputs = [];\n outputs = [];\n };\n\n for (const callbackResult of callbackResults) {\n for (const output of callbackResult.outputs) {\n if (!isAssistant || output.role === \"user\" || output.role === \"system\") {\n flush();\n }\n isAssistant = output.role === \"assistant\" || output.role === \"tool\";\n\n if (inputs.at(-1) !== callbackResult.input) {\n inputs.push(callbackResult.input);\n }\n outputs.push(output);\n }\n }\n flush();\n return results;\n};\n\nexport const useExternalMessageConverter = <T extends WeakKey>({\n callback,\n messages,\n isRunning,\n}: {\n callback: useExternalMessageConverter.Callback<T>;\n messages: T[];\n isRunning: boolean;\n}) => {\n const state = useMemo(\n () => ({\n callback,\n callbackCache: new WeakMap<T, CallbackResult<T>>(),\n chunkCache: new WeakMap<\n useExternalMessageConverter.Message,\n ChunkResult<T>\n >(),\n converterCache: new ThreadMessageConverter(),\n }),\n [callback],\n );\n\n return useMemo(() => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n let result = state.callbackCache.get(message);\n if (!result) {\n const output = state.callback(message);\n const outputs = Array.isArray(output) ? output : [output];\n result = { input: message, outputs };\n state.callbackCache.set(message, result);\n }\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults).map((m) => {\n const key = m.outputs[0];\n if (!key) return m;\n\n const cached = state.chunkCache.get(key);\n if (cached && shallowArrayEqual(cached.outputs, m.outputs)) return cached;\n state.chunkCache.set(key, m);\n return m;\n });\n\n return state.converterCache.convertMessages(\n chunks,\n (cache, message, idx) => {\n const isLast = idx === chunks.length - 1;\n const autoStatus = getAutoStatus(isLast, isRunning);\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n ) {\n const inputs = getExternalStoreMessage(cache) as T[];\n if (shallowArrayEqual(inputs, message.inputs)) {\n return cache;\n }\n }\n\n const newMessage = fromThreadMessageLike(\n joinExternalMessages(message.outputs),\n idx.toString(),\n autoStatus,\n );\n (newMessage as any)[symbolInnerMessage] = message.inputs;\n return newMessage;\n },\n );\n }, [state, messages, isRunning]);\n};\n\nconst shallowArrayEqual = (a: unknown[], b: unknown[]) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n};\n","import { LocalRuntimeOptions, useLocalRuntime } from \"..\";\nimport { useState } from \"react\";\nimport {\n DangerousInBrowserAdapter,\n DangerousInBrowserAdapterOptions,\n} from \"./DangerousInBrowserAdapter\";\n\nexport type DangerousInBrowserRuntimeOptions =\n DangerousInBrowserAdapterOptions & LocalRuntimeOptions;\n\nexport const useDangerousInBrowserRuntime = ({\n initialMessages,\n ...options\n}: DangerousInBrowserRuntimeOptions) => {\n const [adapter] = useState(() => new DangerousInBrowserAdapter(options));\n return useLocalRuntime(adapter, { initialMessages });\n};\n","import { ChatModelAdapter, ChatModelRunOptions } from \"../local\";\nimport { toCoreMessages } from \"../edge/converters/toCoreMessages\";\nimport { toLanguageModelTools } from \"../edge/converters/toLanguageModelTools\";\nimport { EdgeRuntimeRequestOptions } from \"../edge/EdgeRuntimeRequestOptions\";\nimport { runResultStream } from \"../edge/streams/runResultStream\";\nimport { toolResultStream } from \"../edge/streams/toolResultStream\";\nimport { asAsyncIterable } from \"../edge/EdgeChatAdapter\";\nimport {\n CreateEdgeRuntimeAPIOptions,\n getEdgeRuntimeStream,\n} from \"../edge/createEdgeRuntimeAPI\";\n\nexport type DangerousInBrowserAdapterOptions = CreateEdgeRuntimeAPIOptions;\n\nexport class DangerousInBrowserAdapter implements ChatModelAdapter {\n constructor(private options: DangerousInBrowserAdapterOptions) {}\n\n async *run({ messages, abortSignal, config }: ChatModelRunOptions) {\n const res = await getEdgeRuntimeStream({\n options: this.options,\n abortSignal,\n requestData: {\n system: config.system,\n messages: toCoreMessages(messages),\n tools: config.tools ? toLanguageModelTools(config.tools) : [],\n ...config.callSettings,\n ...config.config,\n } satisfies EdgeRuntimeRequestOptions,\n });\n\n const stream = res\n .pipeThrough(toolResultStream(config.tools, abortSignal))\n .pipeThrough(runResultStream());\n\n for await (const update of asAsyncIterable(stream)) {\n yield update;\n }\n }\n}\n","import { ThreadMessage } from \"../../types\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { SpeechSynthesisAdapter } from \"./SpeechAdapterTypes\";\n\nexport class WebSpeechSynthesisAdapter implements SpeechSynthesisAdapter {\n speak(message: ThreadMessage): SpeechSynthesisAdapter.Utterance {\n const text = getThreadMessageText(message);\n const utterance = new SpeechSynthesisUtterance(text);\n\n const endHandlers = new Set<() => void>();\n const handleEnd = (\n reason: \"finished\" | \"error\" | \"cancelled\",\n error?: unknown,\n ) => {\n if (res.status.type === \"ended\") return;\n\n res.status = { type: \"ended\", reason, error };\n endHandlers.forEach((handler) => handler());\n };\n\n utterance.addEventListener(\"end\", () => handleEnd(\"finished\"));\n utterance.addEventListener(\"error\", (e) => handleEnd(\"error\", e.error));\n\n window.speechSynthesis.speak(utterance);\n\n const res: SpeechSynthesisAdapter.Utterance = {\n status: { type: \"running\" },\n cancel: () => {\n window.speechSynthesis.cancel();\n handleEnd(\"cancelled\");\n },\n onEnd: (callback) => {\n if (res.status.type === \"ended\") {\n let cancelled = false;\n queueMicrotask(() => {\n if (!cancelled) callback();\n });\n return () => {\n cancelled = true;\n };\n } else {\n endHandlers.add(callback);\n return () => {\n endHandlers.delete(callback);\n };\n }\n },\n };\n return res;\n }\n}\n","import {\n ThreadComposerAttachment,\n MessageAttachment,\n} from \"../../context/stores/Attachment\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nexport class SimpleImageAttachmentAdapter implements AttachmentAdapter {\n public accept = \"image/*\";\n\n public async add(state: { file: File }): Promise<ThreadComposerAttachment> {\n return {\n id: state.file.name,\n type: \"image\",\n name: state.file.name,\n file: state.file,\n };\n }\n\n public async send(\n attachment: ThreadComposerAttachment,\n ): Promise<MessageAttachment> {\n return {\n ...attachment,\n content: [\n {\n type: \"image\",\n image: await getFileDataURL(attachment.file),\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileDataURL = (file: File) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n\n reader.readAsDataURL(file);\n });\n","import {\n ThreadComposerAttachment,\n MessageAttachment,\n} from \"../../context/stores/Attachment\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nexport class SimpleTextAttachmentAdapter implements AttachmentAdapter {\n public accept =\n \"text/plain,text/html,text/markdown,text/csv,text/xml,text/json,text/css\";\n\n public async add(state: { file: File }): Promise<ThreadComposerAttachment> {\n return {\n id: state.file.name,\n type: \"document\",\n name: state.file.name,\n file: state.file,\n };\n }\n\n public async send(\n attachment: ThreadComposerAttachment,\n ): Promise<MessageAttachment> {\n return {\n ...attachment,\n content: [\n {\n type: \"text\",\n text: `<attachment name=${attachment.name}>\\n${await getFileText(attachment.file)}\\n</attachment>`,\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileText = (file: File) =>\n new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n\n reader.readAsText(file);\n });\n","import {\n ThreadComposerAttachment,\n MessageAttachment,\n} from \"../../context/stores/Attachment\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nfunction fileMatchesAccept(file: File, acceptString: string) {\n // Check if the accept string is \"*\", which allows any file\n if (acceptString === \"*\") {\n return true;\n }\n\n // Split the accept string into an array of allowed types\n const allowedTypes = acceptString\n .split(\",\")\n .map((type) => type.trim().toLowerCase());\n\n // Get the file's extension and MIME type\n const fileExtension = \".\" + file.name.split(\".\").pop()!.toLowerCase();\n const fileMimeType = file.type.toLowerCase();\n\n for (const type of allowedTypes) {\n // Check for file extension match\n if (type.startsWith(\".\") && type === fileExtension) {\n return true;\n }\n\n // Check for exact MIME type match\n if (type.includes(\"/\") && type === fileMimeType) {\n return true;\n }\n\n if (type === \"image/*\" || type === \"video/*\" || type === \"audio/*\") {\n // Check for wildcard MIME type match\n if (type.endsWith(\"/*\")) {\n const generalType = type.split(\"/\")[0]!;\n if (fileMimeType.startsWith(generalType + \"/\")) {\n return true;\n }\n }\n }\n }\n\n return false;\n}\n\nexport class CompositeAttachmentAdapter implements AttachmentAdapter {\n private _adapters: AttachmentAdapter[];\n\n public accept: string;\n\n constructor(adapters: AttachmentAdapter[]) {\n this._adapters = adapters;\n\n const wildcardIdx = adapters.findIndex((a) => a.accept === \"*\");\n if (wildcardIdx !== -1) {\n if (wildcardIdx !== adapters.length - 1)\n throw new Error(\n \"A wildcard adapter (handling all files) can only be specified as the last adapter.\",\n );\n\n this.accept = \"*\";\n } else {\n this.accept = adapters.map((a) => a.accept).join(\",\");\n }\n }\n\n public async add(state: { file: File }): Promise<ThreadComposerAttachment> {\n for (const adapter of this._adapters) {\n if (fileMatchesAccept(state.file, adapter.accept)) {\n return adapter.add(state);\n }\n }\n throw new Error(\"No matching adapter found for file\");\n }\n\n public async send(\n attachment: ThreadComposerAttachment,\n ): Promise<MessageAttachment> {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.send(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n\n public async remove(attachment: ThreadComposerAttachment): Promise<void> {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.remove(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n}\n","import { create } from \"zustand\";\nimport { AssistantRuntime } from \"../../runtimes\";\nimport { MutableRefObject } from \"react\";\nimport { ModelConfigProvider, Unsubscribe } from \"../../types\";\n\nexport type AssistantActionsState = Readonly<{\n /**\n * @deprecated Use `switchToNewThread` instead. This will be removed in 0.6.0.\n */\n switchToThread(threadId: null): void;\n switchToThread(threadId: string): void;\n\n switchToNewThread: () => void;\n registerModelConfigProvider: (provider: ModelConfigProvider) => Unsubscribe;\n}>;\n\nexport const makeAssistantActionsStore = (\n runtimeRef: MutableRefObject<AssistantRuntime>,\n) =>\n create<AssistantActionsState>(() =>\n Object.freeze({\n switchToThread: () => runtimeRef.current.switchToThread(null),\n switchToNewThread: () => runtimeRef.current.switchToNewThread(),\n registerModelConfigProvider: (provider: ModelConfigProvider) =>\n runtimeRef.current.registerModelConfigProvider(provider),\n getRuntime: () => runtimeRef.current,\n }),\n );\n","import { create } from \"zustand\";\nimport { AssistantRuntime } from \"../../runtimes\";\n\nexport type AssistantRuntimeStore = AssistantRuntime;\n\nexport const makeAssistantRuntimeStore = (runtime: AssistantRuntime) => {\n return create<AssistantRuntimeStore>(() => runtime);\n};\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useState } from \"react\";\nimport { ContentPartState } from \"../stores\";\nimport { create } from \"zustand\";\nimport {\n ContentPartContext,\n ContentPartContextValue,\n} from \"../react/ContentPartContext\";\nimport { ContentPartStatus, TextContentPart } from \"../../types/AssistantTypes\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype TextContentPartProviderProps = {\n text: string;\n isRunning?: boolean | undefined;\n};\n\nconst COMPLETE_STATUS: ContentPartStatus = {\n type: \"complete\",\n};\n\nconst RUNNING_STATUS: ContentPartStatus = {\n type: \"running\",\n};\n\nexport const TextContentPartProvider: FC<\n PropsWithChildren<TextContentPartProviderProps>\n> = ({ children, text, isRunning }) => {\n const [context] = useState<ContentPartContextValue>(() => {\n const useContentPart = create<ContentPartState>(() => ({\n status: isRunning ? RUNNING_STATUS : COMPLETE_STATUS,\n part: { type: \"text\", text },\n }));\n\n return {\n useContentPart,\n };\n });\n\n useEffect(() => {\n const state = context.useContentPart.getState();\n const textUpdated = (state.part as TextContentPart).text !== text;\n const targetTextPart = textUpdated\n ? { type: \"text\" as const, text }\n : state.part;\n const targetStatus = isRunning ? RUNNING_STATUS : COMPLETE_STATUS;\n const statusUpdated = state.status !== targetStatus;\n\n if (!textUpdated && !statusUpdated) return;\n\n writableStore(context.useContentPart).setState(\n {\n part: targetTextPart,\n status: targetStatus,\n },\n true,\n );\n }, [context, isRunning, text]);\n\n return (\n <ContentPartContext.Provider value={context}>\n {children}\n </ContentPartContext.Provider>\n );\n};\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { MessageState } from \"../stores/Message\";\nimport type { EditComposerState } from \"../stores/EditComposer\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { MessageUtilsState } from \"../stores/MessageUtils\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type MessageContextValue = {\n useMessage: UseBoundStore<ReadonlyStore<MessageState>>;\n useMessageUtils: UseBoundStore<ReadonlyStore<MessageUtilsState>>;\n useEditComposer: UseBoundStore<ReadonlyStore<EditComposerState>>;\n};\n\nexport const MessageContext = createContext<MessageContextValue | null>(null);\n\nexport const useMessageContext = createContextHook(\n MessageContext,\n \"a component passed to <ThreadPrimitive.Messages components={...} />\",\n);\n\n// TODO make this only return the message itself?\nexport const { useMessage, useMessageStore } = createContextStoreHook(\n useMessageContext,\n \"useMessage\",\n);\n\nexport const { useMessageUtils, useMessageUtilsStore } = createContextStoreHook(\n useMessageContext,\n \"useMessageUtils\",\n);\n\nexport const { useEditComposer, useEditComposerStore } = createContextStoreHook(\n useMessageContext,\n \"useEditComposer\",\n);\n","import { useMemo } from \"react\";\nimport { useMessageContext } from \"./MessageContext\";\nimport { useThreadContext } from \"./ThreadContext\";\nimport type { ThreadComposerState } from \"../stores/ThreadComposer\";\nimport type { EditComposerState } from \"../stores/EditComposer\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\n\nexport type ComposerContextValue = {\n useComposer: ReadonlyStore<EditComposerState | ThreadComposerState>;\n type: \"edit\" | \"new\";\n};\n\nexport const useComposerContext = (): ComposerContextValue => {\n const { useComposer } = useThreadContext();\n const { useEditComposer } = useMessageContext({ optional: true }) ?? {};\n return useMemo(\n () => ({\n useComposer: (useEditComposer ?? useComposer) as ReadonlyStore<\n EditComposerState | ThreadComposerState\n >,\n type: useEditComposer ? (\"edit\" as const) : (\"new\" as const),\n }),\n [useEditComposer, useComposer],\n );\n};\n\nexport const { useComposer, useComposerStore } = createContextStoreHook(\n useComposerContext,\n \"useComposer\",\n);\n","import { useCallback } from \"react\";\nimport {\n ThreadMessagesState,\n useThreadActionsStore,\n useThreadMessagesStore,\n useThreadViewportStore,\n} from \"../context\";\nimport { AppendMessage } from \"../types\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\nimport { ReadonlyStore } from \"../context/ReadonlyStore\";\n\ntype CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n };\n\nconst toAppendMessage = (\n useThreadMessages: ReadonlyStore<ThreadMessagesState>,\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n parentId: useThreadMessages.getState().at(-1)?.id ?? null,\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n };\n }\n\n return {\n parentId:\n message.parentId ?? useThreadMessages.getState().at(-1)?.id ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n } as AppendMessage;\n};\n\nexport const useAppendMessage = () => {\n const threadMessagesStore = useThreadMessagesStore();\n const threadActionsStore = useThreadActionsStore();\n const threadViewportStore = useThreadViewportStore();\n const threadComposerStore = useThreadComposerStore();\n\n const append = useCallback(\n (message: CreateAppendMessage) => {\n const appendMessage = toAppendMessage(threadMessagesStore, message);\n threadActionsStore.getState().append(appendMessage);\n\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n },\n [\n threadMessagesStore,\n threadActionsStore,\n threadViewportStore,\n threadComposerStore,\n ],\n );\n\n return append;\n};\n","import { useCallback } from \"react\";\nimport { useAssistantActionsStore } from \"../context\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\n\n/**\n * @deprecated Use `useRuntimeActions().switchToNewThread()` instead. This will be removed in 0.6.0.\n */\nexport const useSwitchToNewThread = () => {\n const assistantActionsStore = useAssistantActionsStore();\n const threadComposerStore = useThreadComposerStore();\n const switchToNewThread = useCallback(() => {\n assistantActionsStore.getState().switchToNewThread();\n threadComposerStore.getState().focus();\n }, [assistantActionsStore, threadComposerStore]);\n\n return switchToNewThread;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport {\n useAssistantActionsStore,\n useToolUIsStore,\n} from \"../context/react/AssistantContext\";\nimport type { ToolCallContentPartComponent } from \"../types/ContentPartComponentTypes\";\nimport type { Tool } from \"../types/ModelConfigTypes\";\n\nexport type AssistantToolProps<\n TArgs extends Record<string, unknown>,\n TResult,\n> = Tool<TArgs, TResult> & {\n toolName: string;\n render?: ToolCallContentPartComponent<TArgs, TResult> | undefined;\n};\n\nexport const useAssistantTool = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n tool: AssistantToolProps<TArgs, TResult>,\n) => {\n const assistantActionsStore = useAssistantActionsStore();\n const toolUIsStore = useToolUIsStore();\n useEffect(() => {\n const { toolName, render, ...rest } = tool;\n const config = {\n tools: {\n [tool.toolName]: rest,\n },\n };\n const unsub1 = assistantActionsStore\n .getState()\n .registerModelConfigProvider({\n getModelConfig: () => config,\n });\n const unsub2 = render\n ? toolUIsStore.getState().setToolUI(toolName, render)\n : undefined;\n return () => {\n unsub1();\n unsub2?.();\n };\n }, [assistantActionsStore, toolUIsStore, tool]);\n};\n","\"use client\";\nimport { FC } from \"react\";\nimport { type AssistantToolProps, useAssistantTool } from \"./useAssistantTool\";\n\nexport type AssistantTool = FC & {\n unstable_tool: AssistantToolProps<any, any>;\n};\n\nexport const makeAssistantTool = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n tool: AssistantToolProps<TArgs, TResult>,\n) => {\n const Tool: AssistantTool = () => {\n useAssistantTool(tool);\n return null;\n };\n Tool.unstable_tool = tool;\n return Tool;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useToolUIsStore } from \"../context/react/AssistantContext\";\nimport type { ToolCallContentPartComponent } from \"../types/ContentPartComponentTypes\";\n\nexport type AssistantToolUIProps<\n TArgs extends Record<string, unknown>,\n TResult,\n> = {\n toolName: string;\n render: ToolCallContentPartComponent<TArgs, TResult>;\n};\n\nexport const useAssistantToolUI = (\n tool: AssistantToolUIProps<any, any> | null,\n) => {\n const toolUIsStore = useToolUIsStore();\n useEffect(() => {\n if (!tool) return;\n const { toolName, render } = tool;\n return toolUIsStore.getState().setToolUI(toolName, render);\n }, [toolUIsStore, tool]);\n};\n","\"use client\";\nimport { FC } from \"react\";\nimport {\n type AssistantToolUIProps,\n useAssistantToolUI,\n} from \"./useAssistantToolUI\";\n\nexport type AssistantToolUI = FC & {\n unstable_tool: AssistantToolUIProps<any, any>;\n};\n\nexport const makeAssistantToolUI = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n tool: AssistantToolUIProps<TArgs, TResult>,\n) => {\n const ToolUI: AssistantToolUI = () => {\n useAssistantToolUI(tool);\n return null;\n };\n ToolUI.unstable_tool = tool;\n return ToolUI;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useAssistantActionsStore } from \"../context\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const actionsStore = useAssistantActionsStore();\n useEffect(() => {\n const config = {\n system: instruction,\n };\n return actionsStore\n .getState()\n .registerModelConfigProvider({ getModelConfig: () => config });\n }, [actionsStore, instruction]);\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposerStore,\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\n\nexport type UseActionBarCopyProps = {\n copiedDuration?: number | undefined;\n};\n\nexport const useActionBarCopy = ({\n copiedDuration = 3000,\n}: UseActionBarCopyProps = {}) => {\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n const editComposerStore = useEditComposerStore();\n const hasCopyableContent = useCombinedStore(\n [messageStore, editComposerStore],\n ({ message }, c) => {\n return (\n !c.isEditing &&\n (message.role !== \"assistant\" || message.status.type !== \"running\") &&\n message.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n },\n );\n\n const callback = useCallback(() => {\n const { message } = messageStore.getState();\n const { setIsCopied } = messageUtilsStore.getState();\n const { isEditing, text: composerValue } = editComposerStore.getState();\n\n const valueToCopy = isEditing\n ? composerValue\n : getThreadMessageText(message);\n\n navigator.clipboard.writeText(valueToCopy).then(() => {\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), copiedDuration);\n });\n }, [messageStore, messageUtilsStore, editComposerStore, copiedDuration]);\n\n if (!hasCopyableContent) return null;\n return callback;\n};\n","import { useMemo } from \"react\";\nimport {\n type CombinedSelector,\n createCombinedStore,\n} from \"./createCombinedStore\";\nimport { ReadonlyStore } from \"../../context/ReadonlyStore\";\n\nexport const useCombinedStore = <T extends Array<unknown>, R>(\n stores: { [K in keyof T]: ReadonlyStore<T[K]> },\n selector: CombinedSelector<T, R>,\n): R => {\n // eslint-disable-next-line react-hooks/exhaustive-deps -- shallow-compare the store array\n const useCombined = useMemo(() => createCombinedStore<T, R>(stores), stores);\n return useCombined(selector);\n};\n","\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport { ReadonlyStore } from \"../../context/ReadonlyStore\";\n\nexport type CombinedSelector<T extends Array<unknown>, R> = (...args: T) => R;\n\nexport const createCombinedStore = <T extends Array<unknown>, R>(stores: {\n [K in keyof T]: ReadonlyStore<T[K]>;\n}) => {\n const subscribe = (callback: () => void): Unsubscribe => {\n const unsubscribes = stores.map((store) => store.subscribe(callback));\n return () => {\n for (const unsub of unsubscribes) {\n unsub();\n }\n };\n };\n\n return (selector: CombinedSelector<T, R>): R => {\n const getSnapshot = (): R =>\n selector(...(stores.map((store) => store.getState()) as T));\n\n return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n };\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposer,\n useEditComposerStore,\n} from \"../../context/react/MessageContext\";\n\nexport const useActionBarEdit = () => {\n const editComposerStore = useEditComposerStore();\n const disabled = useEditComposer((c) => c.isEditing);\n\n const callback = useCallback(() => {\n const { edit } = editComposerStore.getState();\n edit();\n }, [editComposerStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageStore } from \"../../context/react/MessageContext\";\nimport {\n useThreadActionsStore,\n useThreadComposerStore,\n useThreadStore,\n useThreadViewportStore,\n} from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useActionBarReload = () => {\n const messageStore = useMessageStore();\n const threadStore = useThreadStore();\n const threadActionsStore = useThreadActionsStore();\n const threadComposerStore = useThreadComposerStore();\n const threadViewportStore = useThreadViewportStore();\n\n const disabled = useCombinedStore(\n [threadStore, messageStore],\n (t, m) => t.isRunning || t.isDisabled || m.message.role !== \"assistant\",\n );\n\n const callback = useCallback(() => {\n const { parentId } = messageStore.getState();\n threadActionsStore.getState().startRun(parentId);\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [\n threadActionsStore,\n threadComposerStore,\n threadViewportStore,\n messageStore,\n ]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\n\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport {\n useEditComposerStore,\n useMessageStore,\n useMessageUtilsStore,\n useThreadActionsStore,\n} from \"../../context\";\n\nexport const useActionBarSpeak = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const threadActionsStore = useThreadActionsStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n const hasSpeakableContent = useCombinedStore(\n [messageStore, editComposerStore],\n ({ message }, c) => {\n return (\n !c.isEditing &&\n (message.role !== \"assistant\" || message.status.type !== \"running\") &&\n message.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n },\n );\n\n const callback = useCallback(async () => {\n const { message } = messageStore.getState();\n const utt = threadActionsStore.getState().speak(message.id);\n messageUtilsStore.getState().addUtterance(utt);\n }, [threadActionsStore, messageStore, messageUtilsStore]);\n\n if (!hasSpeakableContent) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport {\n useMessageUtils,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\n\nexport const useActionBarStopSpeaking = () => {\n const messageUtilsStore = useMessageUtilsStore();\n const isSpeaking = useMessageUtils((u) => u.isSpeaking);\n\n const callback = useCallback(async () => {\n messageUtilsStore.getState().stopSpeaking();\n }, [messageUtilsStore]);\n\n if (!isSpeaking) return null;\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useThreadActions } from \"../../context/react/ThreadContext\";\nimport { useMessageStore, useMessageUtilsStore } from \"../../context\";\n\nexport const useActionBarFeedbackPositive = () => {\n const threadActions = useThreadActions();\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n const callback = useCallback(() => {\n threadActions.submitFeedback({\n messageId: messageStore.getState().message.id,\n type: \"positive\",\n });\n messageUtilsStore.getState().setSubmittedFeedback(\"positive\");\n }, [messageStore, messageUtilsStore, threadActions]);\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useThreadActions } from \"../../context/react/ThreadContext\";\nimport { useMessageStore, useMessageUtilsStore } from \"../../context\";\n\nexport const useActionBarFeedbackNegative = () => {\n const threadActions = useThreadActions();\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n const callback = useCallback(() => {\n threadActions.submitFeedback({\n messageId: messageStore.getState().message.id,\n type: \"negative\",\n });\n messageUtilsStore.getState().setSubmittedFeedback(\"negative\");\n }, [messageStore, messageUtilsStore, threadActions]);\n\n return callback;\n};\n","\"use client\";\nimport { useMessage } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerCount = () => {\n const branchCount = useMessage((s) => s.branches.length);\n return branchCount;\n};\n","import { useCallback } from \"react\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport {\n useEditComposerStore,\n useMessageStore,\n useThreadActionsStore,\n} from \"../../context\";\n\nexport const useBranchPickerNext = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const threadActionsStore = useThreadActionsStore();\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) =>\n c.isEditing || m.branches.indexOf(m.message.id) + 1 >= m.branches.length,\n );\n\n const callback = useCallback(() => {\n const { message, branches } = messageStore.getState();\n threadActionsStore\n .getState()\n .switchToBranch(branches[branches.indexOf(message.id) + 1]!);\n }, [threadActionsStore, messageStore]);\n\n if (disabled) return null;\n return callback;\n};\n","\"use client\";\n\nimport { useMessage } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerNumber = () => {\n const branchIdx = useMessage((s) => s.branches.indexOf(s.message.id));\n return branchIdx + 1;\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposerStore,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport { useThreadActionsStore } from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useBranchPickerPrevious = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const threadActionsStore = useThreadActionsStore();\n\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) => c.isEditing || m.branches.indexOf(m.message.id) <= 0,\n );\n\n const callback = useCallback(() => {\n const { message, branches } = messageStore.getState();\n threadActionsStore\n .getState()\n .switchToBranch(branches[branches.indexOf(message.id) - 1]!);\n }, [threadActionsStore, messageStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useComposer, useComposerStore } from \"../../context\";\n\nexport const useComposerCancel = () => {\n const composerStore = useComposerStore();\n const disabled = useComposer((c) => !c.canCancel);\n\n const callback = useCallback(() => {\n const { cancel } = composerStore.getState();\n cancel();\n }, [composerStore]);\n\n if (disabled) return null;\n return callback;\n};\n","\"use client\";\n\nimport { useComposer } from \"../../context/react/ComposerContext\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\n\ntype ComposerIfFilters = {\n editing: boolean | undefined;\n};\n\nexport type UseComposerIfProps = RequireAtLeastOne<ComposerIfFilters>;\n\nexport const useComposerIf = (props: UseComposerIfProps) => {\n return useComposer((composer) => {\n if (props.editing === true && !composer.isEditing) return false;\n if (props.editing === false && composer.isEditing) return false;\n\n return true;\n });\n};\n","import { useCallback } from \"react\";\nimport { useComposerStore } from \"../../context\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport {\n useThreadComposerStore,\n useThreadStore,\n useThreadViewportStore,\n} from \"../../context/react/ThreadContext\";\n\nexport const useComposerSend = () => {\n const threadStore = useThreadStore();\n const threadViewportStore = useThreadViewportStore();\n const composerStore = useComposerStore();\n const threadComposerStore = useThreadComposerStore();\n\n const disabled = useCombinedStore(\n [threadStore, composerStore],\n (t, c) => t.isRunning || !c.isEditing || c.isEmpty,\n );\n\n const callback = useCallback(() => {\n const composerState = composerStore.getState();\n if (!composerState.isEditing) return;\n\n composerState.send();\n\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [threadComposerStore, composerStore, threadViewportStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useComposer } from \"../../context\";\nimport { useThreadComposerStore } from \"../../context/react/ThreadContext\";\n\nexport const useComposerAddAttachment = () => {\n const disabled = useComposer((c) => !c.isEditing);\n\n const threadComposerStore = useThreadComposerStore();\n const threadRuntimeStore = useThreadComposerStore();\n const callback = useCallback(() => {\n const { addAttachment } = threadComposerStore.getState();\n const { attachmentAccept } = threadRuntimeStore.getState();\n\n const input = document.createElement(\"input\");\n input.type = \"file\";\n if (attachmentAccept !== \"*\") {\n input.accept = attachmentAccept;\n }\n\n input.onchange = (e) => {\n const file = (e.target as HTMLInputElement).files?.[0];\n if (!file) return;\n addAttachment(file);\n };\n\n input.click();\n }, [threadComposerStore, threadRuntimeStore]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { UIContentPartState } from \"../../context/stores/ContentPart\";\n\nexport const useContentPartDisplay = () => {\n const display = useContentPart((c) => {\n if (c.part.type !== \"ui\")\n throw new Error(\n \"This component can only be used inside ui content parts.\",\n );\n\n return c as UIContentPartState;\n });\n\n return display;\n};\n","import { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { ImageContentPartState } from \"../../context/stores/ContentPart\";\n\nexport const useContentPartImage = () => {\n const image = useContentPart((c) => {\n if (c.part.type !== \"image\")\n throw new Error(\n \"ContentPartImage can only be used inside image content parts.\",\n );\n\n return c as ImageContentPartState;\n });\n\n return image;\n};\n","import { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { TextContentPartState } from \"../../context/stores/ContentPart\";\n\nexport const useContentPartText = () => {\n const text = useContentPart((c) => {\n if (c.part.type !== \"text\")\n throw new Error(\n \"ContentPartText can only be used inside text content parts.\",\n );\n\n return c as TextContentPartState;\n });\n\n return text;\n};\n","\"use client\";\nimport {\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\ntype MessageIfFilters = {\n user: boolean | undefined;\n assistant: boolean | undefined;\n system: boolean | undefined;\n hasBranches: boolean | undefined;\n copied: boolean | undefined;\n lastOrHover: boolean | undefined;\n speaking: boolean | undefined;\n hasAttachments: boolean | undefined;\n submittedFeedback: \"positive\" | \"negative\" | null | undefined;\n};\nexport type UseMessageIfProps = RequireAtLeastOne<MessageIfFilters>;\n\nexport const useMessageIf = (props: UseMessageIfProps) => {\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [messageStore, messageUtilsStore],\n (\n { message, branches, isLast },\n { isCopied, isHovering, isSpeaking, submittedFeedback },\n ) => {\n if (props.hasBranches === true && branches.length < 2) return false;\n\n if (props.user && message.role !== \"user\") return false;\n if (props.assistant && message.role !== \"assistant\") return false;\n if (props.system && message.role !== \"system\") return false;\n\n if (props.lastOrHover === true && !isHovering && !isLast) return false;\n\n if (props.copied === true && !isCopied) return false;\n if (props.copied === false && isCopied) return false;\n\n if (props.speaking === true && !isSpeaking) return false;\n if (props.speaking === false && isSpeaking) return false;\n\n if (\n props.hasAttachments === true &&\n (message.role !== \"user\" || !message.attachments.length)\n )\n return false;\n if (\n props.hasAttachments === false &&\n message.role === \"user\" &&\n !!message.attachments.length\n )\n return false;\n\n if (\n props.submittedFeedback !== undefined &&\n submittedFeedback !== props.submittedFeedback\n )\n return false;\n\n return true;\n },\n );\n};\n","\"use client\";\n\nimport { useThreadMessagesStore, useThreadStore } from \"../../context\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\ntype ThreadIfFilters = {\n empty: boolean | undefined;\n running: boolean | undefined;\n disabled: boolean | undefined;\n};\n\nexport type UseThreadIfProps = RequireAtLeastOne<ThreadIfFilters>;\n\nexport const useThreadIf = (props: UseThreadIfProps) => {\n const threadStore = useThreadStore();\n const threadMessagesStore = useThreadMessagesStore();\n return useCombinedStore(\n [threadStore, threadMessagesStore],\n (thread, messages) => {\n if (props.empty === true && messages.length !== 0) return false;\n if (props.empty === false && messages.length === 0) return false;\n if (props.running === true && !thread.isRunning) return false;\n if (props.running === false && thread.isRunning) return false;\n if (props.disabled === true && thread.isDisabled) return false;\n if (props.disabled === false && thread.isDisabled) return false;\n\n return true;\n },\n );\n};\n","import { useThreadIf } from \"./useThreadIf\";\n\nexport const useThreadEmpty = () => {\n return useThreadIf({ empty: true });\n};\n","import { useCallback } from \"react\";\nimport { useThreadViewport } from \"../../context\";\nimport {\n useThreadComposerStore,\n useThreadViewportStore,\n} from \"../../context/react/ThreadContext\";\n\nexport const useThreadScrollToBottom = () => {\n const isAtBottom = useThreadViewport((s) => s.isAtBottom);\n\n const threadViewportStore = useThreadViewportStore();\n const threadComposerStore = useThreadComposerStore();\n\n const handleScrollToBottom = useCallback(() => {\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [threadViewportStore, threadComposerStore]);\n\n if (isAtBottom) return null;\n return handleScrollToBottom;\n};\n","import { useCallback } from \"react\";\nimport { useThread, useThreadStore } from \"../../context\";\nimport { useAppendMessage } from \"../../hooks\";\nimport { useThreadComposerStore } from \"../../context/react/ThreadContext\";\n\nexport type UseApplyThreadSuggestionProps = {\n prompt: string;\n method: \"replace\";\n autoSend?: boolean | undefined;\n};\n\nexport const useThreadSuggestion = ({\n prompt,\n autoSend,\n}: UseApplyThreadSuggestionProps) => {\n const threadStore = useThreadStore();\n const composerStore = useThreadComposerStore();\n\n const append = useAppendMessage();\n const disabled = useThread((t) => t.isDisabled);\n const callback = useCallback(() => {\n const thread = threadStore.getState();\n const composer = composerStore.getState();\n if (autoSend && !thread.isRunning) {\n append(prompt);\n composer.setText(\"\");\n } else {\n composer.setText(prompt);\n }\n }, [threadStore, composerStore, autoSend, append, prompt]);\n\n if (disabled) return null;\n return callback;\n};\n","export { ActionBarPrimitiveRoot as Root } from \"./ActionBarRoot\";\nexport { ActionBarPrimitiveCopy as Copy } from \"./ActionBarCopy\";\nexport { ActionBarPrimitiveReload as Reload } from \"./ActionBarReload\";\nexport { ActionBarPrimitiveEdit as Edit } from \"./ActionBarEdit\";\nexport { ActionBarPrimitiveSpeak as Speak } from \"./ActionBarSpeak\";\nexport { ActionBarPrimitiveStopSpeaking as StopSpeaking } from \"./ActionBarStopSpeaking\";\nexport { ActionBarPrimitiveFeedbackPositive as FeedbackPositive } from \"./ActionBarFeedbackPositive\";\nexport { ActionBarPrimitiveFeedbackNegative as FeedbackNegative } from \"./ActionBarFeedbackNegative\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport {\n useActionBarFloatStatus,\n HideAndFloatStatus,\n UseActionBarFloatStatusProps,\n} from \"./useActionBarFloatStatus\";\n\ntype ActionBarPrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type ActionBarPrimitiveRootProps = PrimitiveDivProps &\n UseActionBarFloatStatusProps;\n\nexport const ActionBarPrimitiveRoot = forwardRef<\n ActionBarPrimitiveRootElement,\n ActionBarPrimitiveRootProps\n>(({ hideWhenRunning, autohide, autohideFloat, ...rest }, ref) => {\n const hideAndfloatStatus = useActionBarFloatStatus({\n hideWhenRunning,\n autohide,\n autohideFloat,\n });\n\n if (hideAndfloatStatus === HideAndFloatStatus.Hidden) return null;\n\n return (\n <Primitive.div\n {...(hideAndfloatStatus === HideAndFloatStatus.Floating\n ? { \"data-floating\": \"true\" }\n : null)}\n {...rest}\n ref={ref}\n />\n );\n});\n\nActionBarPrimitiveRoot.displayName = \"ActionBarPrimitive.Root\";\n","\"use client\";\nimport {\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport { useThreadStore } from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport enum HideAndFloatStatus {\n Hidden = \"hidden\",\n Floating = \"floating\",\n Normal = \"normal\",\n}\n\nexport type UseActionBarFloatStatusProps = {\n hideWhenRunning?: boolean | undefined;\n autohide?: \"always\" | \"not-last\" | \"never\" | undefined;\n autohideFloat?: \"always\" | \"single-branch\" | \"never\" | undefined;\n};\n\nexport const useActionBarFloatStatus = ({\n hideWhenRunning,\n autohide,\n autohideFloat,\n}: UseActionBarFloatStatusProps) => {\n const threadStore = useThreadStore();\n const messageStore = useMessageStore();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [threadStore, messageStore, messageUtilsStore],\n (t, m, mu) => {\n if (hideWhenRunning && t.isRunning) return HideAndFloatStatus.Hidden;\n\n const autohideEnabled =\n autohide === \"always\" || (autohide === \"not-last\" && !m.isLast);\n\n // normal status\n if (!autohideEnabled) return HideAndFloatStatus.Normal;\n\n // hidden status\n if (!mu.isHovering) return HideAndFloatStatus.Hidden;\n\n // floating status\n if (\n autohideFloat === \"always\" ||\n (autohideFloat === \"single-branch\" && m.branches.length <= 1)\n )\n return HideAndFloatStatus.Floating;\n\n return HideAndFloatStatus.Normal;\n },\n );\n};\n","\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { useActionBarCopy } from \"../../primitive-hooks/actionBar/useActionBarCopy\";\nimport { ActionButtonProps } from \"../../utils/createActionButton\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { useMessageUtils } from \"../../context\";\n\nexport type ActionBarPrimitiveCopyProps = ActionButtonProps<\n typeof useActionBarCopy\n>;\n\nexport const ActionBarPrimitiveCopy = forwardRef<\n HTMLButtonElement,\n Partial<ActionBarPrimitiveCopyProps>\n>(({ copiedDuration, onClick, disabled, ...props }, forwardedRef) => {\n const isCopied = useMessageUtils((u) => u.isCopied);\n const callback = useActionBarCopy({ copiedDuration });\n return (\n <Primitive.button\n type=\"button\"\n {...(isCopied ? { \"data-copied\": \"true\" } : {})}\n {...props}\n ref={forwardedRef}\n disabled={disabled || !callback}\n onClick={composeEventHandlers(onClick, () => {\n callback?.();\n })}\n />\n );\n});\n\nActionBarPrimitiveCopy.displayName = \"ActionBarPrimitive.Copy\";\n","\"use client\";\n\nimport { ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\n\ntype ActionButtonCallback<TProps> = (props: TProps) => null | (() => void);\n\ntype PrimitiveButtonElement = ElementRef<typeof Primitive.button>;\ntype PrimitiveButtonProps = ComponentPropsWithoutRef<typeof Primitive.button>;\n\nexport type ActionButtonProps<THook> = PrimitiveButtonProps &\n (THook extends (props: infer TProps) => unknown ? TProps : never);\n\nexport const createActionButton = <TProps,>(\n displayName: string,\n useActionButton: ActionButtonCallback<TProps>,\n forwardProps: (keyof NonNullable<TProps>)[] = [],\n) => {\n const ActionButton = forwardRef<\n PrimitiveButtonElement,\n PrimitiveButtonProps & TProps\n >((props, forwardedRef) => {\n const forwardedProps = {} as TProps;\n const primitiveProps = {} as PrimitiveButtonProps;\n\n (Object.keys(props) as Array<keyof typeof props>).forEach((key) => {\n if (forwardProps.includes(key as keyof TProps)) {\n (forwardedProps as any)[key] = props[key];\n } else {\n (primitiveProps as any)[key] = props[key];\n }\n });\n\n const callback = useActionButton(forwardedProps as TProps);\n return (\n <Primitive.button\n type=\"button\"\n {...primitiveProps}\n ref={forwardedRef}\n disabled={primitiveProps.disabled || !callback}\n onClick={composeEventHandlers(primitiveProps.onClick, () => {\n callback?.();\n })}\n />\n );\n });\n\n ActionButton.displayName = displayName;\n\n return ActionButton;\n};\n","\"use client\";\n\nimport { useActionBarReload } from \"../../primitive-hooks/actionBar/useActionBarReload\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type ActionBarPrimitiveReloadProps = ActionButtonProps<\n typeof useActionBarReload\n>;\n\nexport const ActionBarPrimitiveReload = createActionButton(\n \"ActionBarPrimitive.Reload\",\n useActionBarReload,\n);\n","\"use client\";\n\nimport { useActionBarEdit } from \"../../primitive-hooks/actionBar/useActionBarEdit\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type ActionBarPrimitiveEditProps = ActionButtonProps<\n typeof useActionBarEdit\n>;\n\nexport const ActionBarPrimitiveEdit = createActionButton(\n \"ActionBarPrimitive.Edit\",\n useActionBarEdit,\n);\n","\"use client\";\n\nimport { useActionBarSpeak } from \"../../primitive-hooks/actionBar/useActionBarSpeak\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type ActionBarPrimitiveSpeakProps = ActionButtonProps<\n typeof useActionBarSpeak\n>;\n\nexport const ActionBarPrimitiveSpeak = createActionButton(\n \"ActionBarPrimitive.Speak\",\n useActionBarSpeak,\n);\n","\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { useActionBarStopSpeaking } from \"../../primitive-hooks/actionBar/useActionBarStopSpeaking\";\nimport { ActionButtonProps } from \"../../utils/createActionButton\";\nimport { useEscapeKeydown } from \"@radix-ui/react-use-escape-keydown\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\n\nexport type ActionBarPrimitiveStopSpeakingProps = ActionButtonProps<\n typeof useActionBarStopSpeaking\n>;\n\nexport const ActionBarPrimitiveStopSpeaking = forwardRef<\n HTMLButtonElement,\n Partial<ActionBarPrimitiveStopSpeakingProps>\n>((props, ref) => {\n const callback = useActionBarStopSpeaking();\n\n // TODO this stops working if the user is not hovering over an older message\n useEscapeKeydown((e) => {\n if (callback) {\n e.preventDefault();\n callback();\n }\n });\n\n return (\n <Primitive.button\n type=\"button\"\n disabled={!callback}\n {...props}\n ref={ref}\n onClick={composeEventHandlers(props.onClick, () => {\n callback?.();\n })}\n />\n );\n});\n\nActionBarPrimitiveStopSpeaking.displayName = \"ActionBarPrimitive.StopSpeaking\";\n","\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { useActionBarFeedbackPositive } from \"../../primitive-hooks/actionBar/useActionBarFeedbackPositive\";\nimport { ActionButtonProps } from \"../../utils/createActionButton\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useMessageUtils } from \"../../context\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\nexport type ActionBarPrimitiveFeedbackPositiveProps = ActionButtonProps<\n typeof useActionBarFeedbackPositive\n>;\n\nexport const ActionBarPrimitiveFeedbackPositive = forwardRef<\n HTMLButtonElement,\n Partial<ActionBarPrimitiveFeedbackPositiveProps>\n>(({ onClick, disabled, ...props }, forwardedRef) => {\n const isSubmitted = useMessageUtils(\n (u) => u.submittedFeedback === \"positive\",\n );\n const callback = useActionBarFeedbackPositive();\n return (\n <Primitive.button\n type=\"button\"\n {...(isSubmitted ? { \"data-submitted\": \"true\" } : {})}\n {...props}\n ref={forwardedRef}\n disabled={disabled || !callback}\n onClick={composeEventHandlers(onClick, () => {\n callback?.();\n })}\n />\n );\n});\n\nActionBarPrimitiveFeedbackPositive.displayName =\n \"ActionBarPrimitive.FeedbackPositive\";\n","\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { useActionBarFeedbackNegative } from \"../../primitive-hooks/actionBar/useActionBarFeedbackNegative\";\nimport { ActionButtonProps } from \"../../utils/createActionButton\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useMessageUtils } from \"../../context\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\nexport type ActionBarPrimitiveFeedbackNegativeProps = ActionButtonProps<\n typeof useActionBarFeedbackNegative\n>;\n\nexport const ActionBarPrimitiveFeedbackNegative = forwardRef<\n HTMLButtonElement,\n Partial<ActionBarPrimitiveFeedbackNegativeProps>\n>(({ onClick, disabled, ...props }, forwardedRef) => {\n const isSubmitted = useMessageUtils(\n (u) => u.submittedFeedback === \"negative\",\n );\n const callback = useActionBarFeedbackNegative();\n return (\n <Primitive.button\n type=\"button\"\n {...(isSubmitted ? { \"data-submitted\": \"true\" } : {})}\n {...props}\n ref={forwardedRef}\n disabled={disabled || !callback}\n onClick={composeEventHandlers(onClick, () => {\n callback?.();\n })}\n />\n );\n});\n\nActionBarPrimitiveFeedbackNegative.displayName =\n \"ActionBarPrimitive.FeedbackNegative\";\n","export { AssistantModalPrimitiveRoot as Root } from \"./AssistantModalRoot\";\nexport { AssistantModalPrimitiveTrigger as Trigger } from \"./AssistantModalTrigger\";\nexport { AssistantModalPrimitiveContent as Content } from \"./AssistantModalContent\";\nexport { AssistantModalPrimitiveAnchor as Anchor } from \"./AssistantModalAnchor\";\n","\"use client\";\n\nimport { FC, useState } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useOnComposerFocus } from \"../../utils/hooks/useOnComposerFocus\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\n\nexport type AssistantModalPrimitiveRootProps = PopoverPrimitive.PopoverProps;\n\nconst useAssistantModalOpenState = (defaultOpen = false) => {\n const state = useState(defaultOpen);\n\n const [, setOpen] = state;\n useOnComposerFocus(() => {\n setOpen(true);\n });\n\n return state;\n};\n\nexport const AssistantModalPrimitiveRoot: FC<\n AssistantModalPrimitiveRootProps\n> = ({\n __scopeAssistantModal,\n defaultOpen,\n open,\n onOpenChange,\n ...rest\n}: ScopedProps<AssistantModalPrimitiveRootProps>) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n const [modalOpen, setOpen] = useAssistantModalOpenState(defaultOpen);\n\n return (\n <PopoverPrimitive.Root\n {...scope}\n open={open === undefined ? modalOpen : open}\n onOpenChange={composeEventHandlers(onOpenChange, setOpen)}\n {...rest}\n />\n );\n};\n\nAssistantModalPrimitiveRoot.displayName = \"AssistantModalPrimitive.Root\";\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useEffect } from \"react\";\nimport { useThreadComposerStore } from \"../../context/react/ThreadContext\";\n\nexport const useOnComposerFocus = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n\n const threadComposerStore = useThreadComposerStore();\n useEffect(() => {\n return threadComposerStore.getState().onFocus(() => {\n callbackRef();\n });\n }, [threadComposerStore, callbackRef]);\n};\n","import * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport type { Scope } from \"@radix-ui/react-context\";\n\nexport type ScopedProps<P> = P & { __scopeAssistantModal?: Scope };\nexport const usePopoverScope = PopoverPrimitive.createPopoverScope();\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\n\ntype AssistantModalPrimitiveTriggerElement = ElementRef<\n typeof PopoverPrimitive.Trigger\n>;\nexport type AssistantModalPrimitiveTriggerProps = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Trigger\n>;\n\nexport const AssistantModalPrimitiveTrigger = forwardRef<\n AssistantModalPrimitiveTriggerElement,\n AssistantModalPrimitiveTriggerProps\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveTriggerProps>,\n ref,\n ) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n return <PopoverPrimitive.Trigger {...scope} {...rest} ref={ref} />;\n },\n);\n\nAssistantModalPrimitiveTrigger.displayName = \"AssistantModalPrimitive.Trigger\";\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\n\ntype AssistantModalPrimitiveContentElement = ElementRef<\n typeof PopoverPrimitive.Content\n>;\nexport type AssistantModalPrimitiveContentProps = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Content\n> & {\n dissmissOnInteractOutside?: boolean | undefined;\n};\n\nexport const AssistantModalPrimitiveContent = forwardRef<\n AssistantModalPrimitiveContentElement,\n AssistantModalPrimitiveContentProps\n>(\n (\n {\n __scopeAssistantModal,\n side,\n align,\n onInteractOutside,\n dissmissOnInteractOutside = false,\n ...props\n }: ScopedProps<AssistantModalPrimitiveContentProps>,\n forwardedRef,\n ) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n return (\n <PopoverPrimitive.Portal {...scope}>\n <PopoverPrimitive.Content\n {...scope}\n {...props}\n ref={forwardedRef}\n side={side ?? \"top\"}\n align={align ?? \"end\"}\n onInteractOutside={composeEventHandlers(\n onInteractOutside,\n dissmissOnInteractOutside ? undefined : (e) => e.preventDefault(),\n )}\n />\n </PopoverPrimitive.Portal>\n );\n },\n);\n\nAssistantModalPrimitiveContent.displayName = \"AssistantModalPrimitive.Content\";\n","\"use client\";\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\n\ntype AssistantModalPrimitiveAnchorElement = ElementRef<\n typeof PopoverPrimitive.Anchor\n>;\ntype AssistantModalPrimitiveAnchorProps = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Anchor\n>;\n\nexport const AssistantModalPrimitiveAnchor = forwardRef<\n AssistantModalPrimitiveAnchorElement,\n AssistantModalPrimitiveAnchorProps\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveAnchorProps>,\n ref,\n ) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n return <PopoverPrimitive.Anchor {...scope} {...rest} ref={ref} />;\n },\n);\nAssistantModalPrimitiveAnchor.displayName = \"AssistantModalPrimitive.Anchor\";\n","export { BranchPickerPrimitiveNext as Next } from \"./BranchPickerNext\";\nexport { BranchPickerPrevious as Previous } from \"./BranchPickerPrevious\";\nexport { BranchPickerPrimitiveCount as Count } from \"./BranchPickerCount\";\nexport { BranchPickerPrimitiveNumber as Number } from \"./BranchPickerNumber\";\nexport { BranchPickerPrimitiveRoot as Root } from \"./BranchPickerRoot\";\n","\"use client\";\n\nimport { useBranchPickerNext } from \"../../primitive-hooks/branchPicker/useBranchPickerNext\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type BranchPickerPrimitiveNextProps = ActionButtonProps<\n typeof useBranchPickerNext\n>;\n\nexport const BranchPickerPrimitiveNext = createActionButton(\n \"BranchPickerPrimitive.Next\",\n useBranchPickerNext,\n);\n","\"use client\";\n\nimport { useBranchPickerPrevious } from \"../../primitive-hooks/branchPicker/useBranchPickerPrevious\";\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport type BranchPickerPrimitivePreviousProps = ActionButtonProps<\n typeof useBranchPickerPrevious\n>;\n\nexport const BranchPickerPrevious = createActionButton(\n \"BranchPickerPrimitive.Previous\",\n useBranchPickerPrevious,\n);\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport { useBranchPickerCount } from \"../../primitive-hooks/branchPicker/useBranchPickerCount\";\n\nexport type BranchPickerPrimitiveCountProps = Record<string, never>;\n\nexport const BranchPickerPrimitiveCount: FC<\n BranchPickerPrimitiveCountProps\n> = () => {\n const branchCount = useBranchPickerCount();\n return <>{branchCount}</>;\n};\n\nBranchPickerPrimitiveCount.displayName = \"BranchPickerPrimitive.Count\";\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport { useBranchPickerNumber } from \"../../primitive-hooks/branchPicker/useBranchPickerNumber\";\n\nexport type BranchPickerPrimitiveNumberProps = Record<string, never>;\n\nexport const BranchPickerPrimitiveNumber: FC<\n BranchPickerPrimitiveNumberProps\n> = () => {\n const branchNumber = useBranchPickerNumber();\n return <>{branchNumber}</>;\n};\n\nBranchPickerPrimitiveNumber.displayName = \"BranchPickerPrimitive.Number\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport { If } from \"../message\";\n\ntype BranchPickerPrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type BranchPickerPrimitiveRootProps = PrimitiveDivProps & {\n hideWhenSingleBranch?: boolean | undefined;\n};\n\nexport const BranchPickerPrimitiveRoot = forwardRef<\n BranchPickerPrimitiveRootElement,\n BranchPickerPrimitiveRootProps\n>(({ hideWhenSingleBranch, ...rest }, ref) => {\n return (\n <If hasBranches={hideWhenSingleBranch ? true : undefined}>\n <Primitive.div {...rest} ref={ref} />\n </If>\n );\n});\n\nBranchPickerPrimitiveRoot.displayName = \"BranchPickerPrimitive.Root\";\n","export { MessagePrimitiveRoot as Root } from \"./MessageRoot\";\nexport { MessagePrimitiveIf as If } from \"./MessageIf\";\nexport { MessagePrimitiveContent as Content } from \"./MessageContent\";\nexport { MessagePrimitiveInProgress as InProgress } from \"./MessageInProgress\";\nexport { MessagePrimitiveAttachments as Attachments } from \"./MessageAttachments\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport {\n type ElementRef,\n forwardRef,\n ComponentPropsWithoutRef,\n useCallback,\n} from \"react\";\nimport { useMessageUtilsStore } from \"../../context/react/MessageContext\";\nimport { useManagedRef } from \"../../utils/hooks/useManagedRef\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\n\ntype MessagePrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nconst useIsHoveringRef = () => {\n const messageUtilsStore = useMessageUtilsStore();\n const callbackRef = useCallback(\n (el: HTMLElement) => {\n const setIsHovering = messageUtilsStore.getState().setIsHovering;\n\n const handleMouseEnter = () => {\n setIsHovering(true);\n };\n const handleMouseLeave = () => {\n setIsHovering(false);\n };\n\n el.addEventListener(\"mouseenter\", handleMouseEnter);\n el.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n el.removeEventListener(\"mouseenter\", handleMouseEnter);\n el.removeEventListener(\"mouseleave\", handleMouseLeave);\n setIsHovering(false);\n };\n },\n [messageUtilsStore],\n );\n\n return useManagedRef(callbackRef);\n};\n\nexport type MessagePrimitiveRootProps = PrimitiveDivProps;\n\nexport const MessagePrimitiveRoot = forwardRef<\n MessagePrimitiveRootElement,\n MessagePrimitiveRootProps\n>((props, forwardRef) => {\n const isHoveringRef = useIsHoveringRef();\n const ref = useComposedRefs<HTMLDivElement>(forwardRef, isHoveringRef);\n\n return <Primitive.div {...props} ref={ref} />;\n});\n\nMessagePrimitiveRoot.displayName = \"MessagePrimitive.Root\";\n","import { useCallback, useRef } from \"react\";\n\nexport const useManagedRef = <TNode>(\n callback: (node: TNode) => (() => void) | void,\n) => {\n const cleanupRef = useRef<(() => void) | void>();\n\n const ref = useCallback(\n (el: TNode | null) => {\n // Call the previous cleanup function\n if (cleanupRef.current) {\n cleanupRef.current();\n }\n\n // Call the new callback and store its cleanup function\n if (el) {\n cleanupRef.current = callback(el);\n }\n },\n [callback],\n );\n\n return ref;\n};\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport {\n UseMessageIfProps,\n useMessageIf,\n} from \"../../primitive-hooks/message/useMessageIf\";\n\nexport type MessagePrimitiveIfProps = PropsWithChildren<UseMessageIfProps>;\n\nexport const MessagePrimitiveIf: FC<MessagePrimitiveIfProps> = ({\n children,\n ...query\n}) => {\n const result = useMessageIf(query);\n return result ? children : null;\n};\n\nMessagePrimitiveIf.displayName = \"MessagePrimitive.If\";\n","\"use client\";\n\nimport { type ComponentType, type FC, memo } from \"react\";\nimport {\n useContentPart,\n useThreadActionsStore,\n useToolUIs,\n} from \"../../context\";\nimport {\n useMessage,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport {\n ContentPartProvider,\n EMPTY_CONTENT,\n} from \"../../context/providers/ContentPartProvider\";\nimport { ContentPartPrimitiveText } from \"../contentPart/ContentPartText\";\nimport { ContentPartPrimitiveImage } from \"../contentPart/ContentPartImage\";\nimport { ContentPartPrimitiveDisplay } from \"../contentPart/ContentPartDisplay\";\nimport type {\n EmptyContentPartComponent,\n ImageContentPartComponent,\n TextContentPartComponent,\n ToolCallContentPartComponent,\n ToolCallContentPartProps,\n UIContentPartComponent,\n} from \"../../types/ContentPartComponentTypes\";\nimport { ContentPartPrimitiveInProgress } from \"../contentPart/ContentPartInProgress\";\n\nexport type MessagePrimitiveContentProps = {\n components?:\n | {\n Empty?: EmptyContentPartComponent | undefined;\n Text?: TextContentPartComponent | undefined;\n Image?: ImageContentPartComponent | undefined;\n UI?: UIContentPartComponent | undefined;\n tools?:\n | {\n by_name?:\n | Record<string, ToolCallContentPartComponent | undefined>\n | undefined;\n Fallback?: ComponentType<ToolCallContentPartProps> | undefined;\n }\n | undefined;\n }\n | undefined;\n};\n\nconst ToolUIDisplay = ({\n UI,\n ...props\n}: {\n UI: ToolCallContentPartComponent | undefined;\n} & ToolCallContentPartProps) => {\n const Render = useToolUIs((s) => s.getToolUI(props.part.toolName)) ?? UI;\n if (!Render) return null;\n return <Render {...props} />;\n};\n\nconst defaultComponents = {\n Text: () => (\n <p style={{ whiteSpace: \"pre-line\" }}>\n <ContentPartPrimitiveText />\n <ContentPartPrimitiveInProgress>\n <span style={{ fontFamily: \"revert\" }}>{\" \\u25CF\"}</span>\n </ContentPartPrimitiveInProgress>\n </p>\n ),\n Image: () => <ContentPartPrimitiveImage />,\n UI: () => <ContentPartPrimitiveDisplay />,\n} satisfies MessagePrimitiveContentProps[\"components\"];\n\ntype MessageContentPartComponentProps = {\n components: MessagePrimitiveContentProps[\"components\"];\n};\n\nconst MessageContentPartComponent: FC<MessageContentPartComponentProps> = ({\n components: {\n Text = defaultComponents.Text,\n Empty,\n Image = defaultComponents.Image,\n UI = defaultComponents.UI,\n tools: { by_name = {}, Fallback = undefined } = {},\n } = {},\n}) => {\n const messageStore = useMessageStore();\n const threadActionsStore = useThreadActionsStore();\n\n const { part, status } = useContentPart();\n\n const type = part.type;\n switch (type) {\n case \"text\":\n if (status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n if (part === EMPTY_CONTENT && !!Empty) {\n return <Empty status={status} />;\n }\n\n return <Text part={part} status={status} />;\n\n case \"image\":\n if (status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n // eslint-disable-next-line jsx-a11y/alt-text\n return <Image part={part} status={status} />;\n\n case \"ui\":\n if (status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n return <UI part={part} status={status} />;\n\n case \"tool-call\": {\n const Tool = by_name[part.toolName] || Fallback;\n const addResult = (result: any) =>\n threadActionsStore.getState().addToolResult({\n messageId: messageStore.getState().message.id,\n toolName: part.toolName,\n toolCallId: part.toolCallId,\n result,\n });\n return (\n <ToolUIDisplay\n UI={Tool}\n part={part}\n status={status}\n addResult={addResult}\n />\n );\n }\n default:\n const unhandledType: never = type;\n throw new Error(`Unknown content part type: ${unhandledType}`);\n }\n};\n\ntype MessageContentPartProps = {\n partIndex: number;\n components: MessagePrimitiveContentProps[\"components\"];\n};\n\nconst MessageContentPartImpl: FC<MessageContentPartProps> = ({\n partIndex,\n components,\n}) => {\n return (\n <ContentPartProvider partIndex={partIndex}>\n <MessageContentPartComponent components={components} />\n </ContentPartProvider>\n );\n};\n\nconst MessageContentPart = memo(\n MessageContentPartImpl,\n (prev, next) =>\n prev.partIndex === next.partIndex &&\n prev.components?.Text === next.components?.Text &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.UI === next.components?.UI &&\n prev.components?.tools === next.components?.tools,\n);\n\nexport const MessagePrimitiveContent: FC<MessagePrimitiveContentProps> = ({\n components,\n}) => {\n const contentLength = useMessage((s) => s.message.content.length) || 1;\n\n return Array.from({ length: contentLength }, (_, index) => (\n <MessageContentPart key={index} partIndex={index} components={components} />\n ));\n};\n\nMessagePrimitiveContent.displayName = \"MessagePrimitive.Content\";\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport { ContentPartContext } from \"../react/ContentPartContext\";\nimport type { ContentPartContextValue } from \"../react/ContentPartContext\";\nimport { useMessageStore } from \"../react/MessageContext\";\nimport type { MessageState } from \"../stores\";\nimport type { ContentPartState } from \"../stores/ContentPart\";\nimport {\n ContentPartStatus,\n ThreadAssistantContentPart,\n ThreadMessage,\n ThreadUserContentPart,\n ToolCallContentPartStatus,\n} from \"../../types/AssistantTypes\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype ContentPartProviderProps = PropsWithChildren<{\n partIndex: number;\n}>;\n\nconst COMPLETE_STATUS: ContentPartStatus = {\n type: \"complete\",\n};\n\nconst toContentPartStatus = (\n message: ThreadMessage,\n partIndex: number,\n part: ThreadUserContentPart | ThreadAssistantContentPart,\n): ToolCallContentPartStatus => {\n if (message.role !== \"assistant\") return COMPLETE_STATUS;\n\n const isLastPart = partIndex === Math.max(0, message.content.length - 1);\n if (part.type !== \"tool-call\") {\n if (\n \"reason\" in message.status &&\n message.status.reason === \"tool-calls\" &&\n isLastPart\n )\n throw new Error(\n \"Encountered unexpected requires-action status. This is likely an internal bug in assistant-ui.\",\n );\n\n return isLastPart ? (message.status as ContentPartStatus) : COMPLETE_STATUS;\n }\n\n if (!!part.result) {\n return COMPLETE_STATUS;\n }\n\n return message.status as ToolCallContentPartStatus;\n};\n\nexport const EMPTY_CONTENT = Object.freeze({ type: \"text\", text: \"\" });\n\nconst getContentPartState = (\n { message }: MessageState,\n useContentPart: ContentPartContextValue[\"useContentPart\"] | undefined,\n partIndex: number,\n) => {\n let part = message.content[partIndex];\n if (!part) {\n // for empty messages, show an empty text content part\n if (message.content.length === 0 && partIndex === 0) {\n part = EMPTY_CONTENT;\n } else {\n return null;\n }\n } else if (\n message.content.length === 1 &&\n part.type === \"text\" &&\n part.text.length === 0\n ) {\n // ensure reference equality for equivalent empty text parts\n part = EMPTY_CONTENT;\n }\n\n // if the content part is the same, don't update\n const status = toContentPartStatus(message, partIndex, part);\n const currentState = useContentPart?.getState();\n if (\n currentState &&\n currentState.part === part &&\n currentState.status === status\n )\n return null;\n\n return Object.freeze({ part, status });\n};\n\nconst useContentPartContext = (partIndex: number) => {\n const messageStore = useMessageStore();\n const [context] = useState<ContentPartContextValue>(() => {\n const useContentPart = create<ContentPartState>(\n () => getContentPartState(messageStore.getState(), undefined, partIndex)!,\n );\n\n return { useContentPart };\n });\n\n useEffect(() => {\n const syncContentPart = (message: MessageState) => {\n const newState = getContentPartState(\n message,\n context.useContentPart,\n partIndex,\n );\n if (!newState) return;\n writableStore(context.useContentPart).setState(newState, true);\n };\n\n syncContentPart(messageStore.getState());\n return messageStore.subscribe(syncContentPart);\n }, [context, messageStore, partIndex]);\n\n return context;\n};\n\nexport const ContentPartProvider: FC<ContentPartProviderProps> = ({\n partIndex,\n children,\n}) => {\n const context = useContentPartContext(partIndex);\n\n return (\n <ContentPartContext.Provider value={context}>\n {children}\n </ContentPartContext.Provider>\n );\n};\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport {\n type ElementRef,\n forwardRef,\n ComponentPropsWithoutRef,\n ElementType,\n} from \"react\";\nimport { useContentPartText } from \"../../primitive-hooks/contentPart/useContentPartText\";\nimport { useSmooth } from \"../../utils/smooth/useSmooth\";\n\ntype ContentPartPrimitiveTextElement = ElementRef<typeof Primitive.span>;\ntype PrimitiveSpanProps = ComponentPropsWithoutRef<typeof Primitive.span>;\n\nexport type ContentPartPrimitiveTextProps = Omit<\n PrimitiveSpanProps,\n \"children\" | \"asChild\"\n> & {\n smooth?: boolean;\n component?: ElementType;\n};\n\nexport const ContentPartPrimitiveText = forwardRef<\n ContentPartPrimitiveTextElement,\n ContentPartPrimitiveTextProps\n>(({ smooth = true, component: Component = \"span\", ...rest }, forwardedRef) => {\n const {\n part: { text },\n status,\n } = useSmooth(useContentPartText(), smooth);\n\n return (\n <Component data-status={status.type} {...rest} ref={forwardedRef}>\n {text}\n </Component>\n );\n});\n\nContentPartPrimitiveText.displayName = \"ContentPartPrimitive.Text\";\n","import { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport { useContentPartImage } from \"../../primitive-hooks/contentPart/useContentPartImage\";\n\ntype ContentPartPrimitiveImageElement = ElementRef<typeof Primitive.img>;\ntype PrimitiveImageProps = ComponentPropsWithoutRef<typeof Primitive.img>;\n\nexport type ContentPartPrimitiveImageProps = PrimitiveImageProps;\n\nexport const ContentPartPrimitiveImage = forwardRef<\n ContentPartPrimitiveImageElement,\n ContentPartPrimitiveImageProps\n>((props, forwardedRef) => {\n const {\n part: { image },\n } = useContentPartImage();\n return <Primitive.img src={image} {...props} ref={forwardedRef} />;\n});\n\nContentPartPrimitiveImage.displayName = \"ContentPartPrimitive.Image\";\n","import type { FC } from \"react\";\nimport { useContentPartDisplay } from \"../../primitive-hooks/contentPart/useContentPartDisplay\";\n\nexport type ContentPartPrimitiveDisplayProps = Record<string, never>;\n\nexport const ContentPartPrimitiveDisplay: FC = () => {\n const {\n part: { display },\n } = useContentPartDisplay();\n return display ?? null;\n};\n\nContentPartPrimitiveDisplay.displayName = \"ContentPartPrimitive.Display\";\n","import { FC, PropsWithChildren } from \"react\";\nimport { useContentPart } from \"../../context\";\n\nexport type ContentPartPrimitiveInProgressProps = PropsWithChildren;\n\n// TODO should this be renamed to IsRunning?\nexport const ContentPartPrimitiveInProgress: FC<\n ContentPartPrimitiveInProgressProps\n> = ({ children }) => {\n const isInProgress = useContentPart((c) => c.status.type === \"running\");\n\n return isInProgress ? children : null;\n};\n\nContentPartPrimitiveInProgress.displayName = \"ContentPartPrimitive.InProgress\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { ComponentPropsWithoutRef, FC } from \"react\";\n\ntype PrimitiveSpanProps = ComponentPropsWithoutRef<typeof Primitive.span>;\n\nexport type MessagePrimitiveInProgressProps = PrimitiveSpanProps;\n\n/**\n * @deprecated Define a custom Text renderer via ContentPartPrimitiveInProgress instead. This will be removed in 0.6.\n */\nexport const MessagePrimitiveInProgress: FC<\n MessagePrimitiveInProgressProps\n> = () => {\n return null;\n};\n\nMessagePrimitiveInProgress.displayName = \"MessagePrimitive.InProgress\";\n","\"use client\";\n\nimport { ComponentType, type FC, memo } from \"react\";\nimport { useMessage } from \"../../context\";\nimport { useMessageAttachment } from \"../../context/react/AttachmentContext\";\nimport { MessageAttachmentProvider } from \"../../context/providers/MessageAttachmentProvider\";\nimport type { MessageAttachment } from \"../../context/stores/Attachment\";\n\nexport type MessagePrimitiveAttachmentsProps = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n};\n\nconst getComponent = (\n components: MessagePrimitiveAttachmentsProps[\"components\"],\n attachment: MessageAttachment,\n) => {\n const type = attachment.type;\n switch (type) {\n case \"image\":\n return components?.Image ?? components?.Attachment;\n case \"document\":\n return components?.Document ?? components?.Attachment;\n case \"file\":\n return components?.File ?? components?.Attachment;\n default:\n const _exhaustiveCheck: never = type;\n throw new Error(`Unknown attachment type: ${_exhaustiveCheck}`);\n }\n};\n\nconst AttachmentComponent: FC<{\n components: MessagePrimitiveAttachmentsProps[\"components\"];\n}> = ({ components }) => {\n const Component = useMessageAttachment((a) =>\n getComponent(components, a.attachment),\n );\n\n if (!Component) return null;\n return <Component />;\n};\n\nconst MessageAttachmentImpl: FC<\n MessagePrimitiveAttachmentsProps & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n return (\n <MessageAttachmentProvider attachmentIndex={attachmentIndex}>\n <AttachmentComponent components={components} />\n </MessageAttachmentProvider>\n );\n};\n\nconst MessageAttachment = memo(\n MessageAttachmentImpl,\n (prev, next) =>\n prev.attachmentIndex === next.attachmentIndex &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.Document === next.components?.Document &&\n prev.components?.File === next.components?.File &&\n prev.components?.Attachment === next.components?.Attachment,\n);\n\nexport const MessagePrimitiveAttachments: FC<\n MessagePrimitiveAttachmentsProps\n> = ({ components }) => {\n const attachmentsCount = useMessage(({ message }) => {\n if (message.role !== \"user\") return 0;\n return message.attachments.length;\n });\n\n return Array.from({ length: attachmentsCount }, (_, index) => (\n <MessageAttachment\n key={index}\n attachmentIndex={index}\n components={components}\n />\n ));\n};\n\nMessagePrimitiveAttachments.displayName = \"MessagePrimitive.Attachments\";\n","\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport {\n ComposerAttachmentState,\n MessageAttachmentState,\n} from \"../stores/Attachment\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\n\nexport type AttachmentContextValue = {\n type: \"composer\" | \"message\";\n useAttachment: ReadonlyStore<\n ComposerAttachmentState | MessageAttachmentState\n >;\n};\n\ntype ComposerAttachmentContextValue = {\n type: \"composer\";\n useAttachment: ReadonlyStore<ComposerAttachmentState>;\n};\n\ntype MessageAttachmentContextValue = {\n type: \"message\";\n useAttachment: ReadonlyStore<MessageAttachmentState>;\n};\n\nexport const AttachmentContext = createContext<AttachmentContextValue | null>(\n null,\n);\n\nexport function useAttachmentContext(options?: {\n optional?: false | undefined;\n}): AttachmentContextValue;\nexport function useAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): AttachmentContextValue | null;\nexport function useAttachmentContext(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useContext(AttachmentContext);\n if (!options?.optional && !context)\n throw new Error(\n \"This component must be used within a ComposerPrimitive.Attachments or MessagePrimitive.Attachments component.\",\n );\n\n return context;\n}\n\nfunction useComposerAttachmentContext(): ComposerAttachmentContextValue;\nfunction useComposerAttachmentContext(options: {\n optional: true;\n}): ComposerAttachmentContextValue | null;\nfunction useComposerAttachmentContext(options?: { optional?: true }) {\n const context = useAttachmentContext(options);\n if (!context) return null;\n if (context.type !== \"composer\")\n throw new Error(\n \"This component must be used within a ComposerPrimitive.Attachments component.\",\n );\n return context;\n}\n\nfunction useMessageAttachmentContext(): MessageAttachmentContextValue;\nfunction useMessageAttachmentContext(options: {\n optional: true;\n}): MessageAttachmentContextValue | null;\nfunction useMessageAttachmentContext(options?: { optional?: true }) {\n const context = useAttachmentContext(options);\n if (!context) return null;\n if (context.type !== \"message\")\n throw new Error(\n \"This component must be used within a MessagePrimitive.Attachments component.\",\n );\n return context;\n}\n\nexport const { useAttachment, useAttachmentStore } = createContextStoreHook(\n useAttachmentContext,\n \"useAttachment\",\n);\n\nexport const {\n useAttachment: useComposerAttachment,\n useAttachmentStore: useComposerAttachmentStore,\n} = createContextStoreHook(useComposerAttachmentContext, \"useAttachment\");\n\nexport const {\n useAttachment: useMessageAttachment,\n useAttachmentStore: useMessageAttachmentStore,\n} = createContextStoreHook(useMessageAttachmentContext, \"useAttachment\");\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport type { MessageState } from \"../stores\";\nimport { useMessageStore } from \"../react\";\nimport { MessageAttachmentState } from \"../stores/Attachment\";\nimport {\n AttachmentContext,\n AttachmentContextValue,\n} from \"../react/AttachmentContext\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype MessageAttachmentProviderProps = PropsWithChildren<{\n attachmentIndex: number;\n}>;\n\nconst getAttachment = (\n { message }: MessageState,\n useAttachment: AttachmentContextValue[\"useAttachment\"] | undefined,\n partIndex: number,\n) => {\n if (message.role !== \"user\") return null;\n\n const attachments = message.attachments;\n const attachment = attachments[partIndex];\n if (!attachment) return null;\n\n // if the attachment is the same, don't update\n const currentState = useAttachment?.getState();\n if (currentState && currentState.attachment === attachment) return null;\n\n return Object.freeze({ attachment });\n};\n\nconst useMessageAttachmentContext = (partIndex: number) => {\n const messageStore = useMessageStore();\n const [context] = useState<AttachmentContextValue & { type: \"message\" }>(\n () => {\n const useAttachment = create<MessageAttachmentState>(\n () => getAttachment(messageStore.getState(), undefined, partIndex)!,\n );\n\n return { type: \"message\", useAttachment };\n },\n );\n\n useEffect(() => {\n const syncAttachment = (messageState: MessageState) => {\n const newState = getAttachment(\n messageState,\n context.useAttachment,\n partIndex,\n );\n if (!newState) return;\n writableStore(context.useAttachment).setState(newState, true);\n };\n\n syncAttachment(messageStore.getState());\n return messageStore.subscribe(syncAttachment);\n }, [context, messageStore, partIndex]);\n\n return context;\n};\n\nexport const MessageAttachmentProvider: FC<MessageAttachmentProviderProps> = ({\n attachmentIndex: partIndex,\n children,\n}) => {\n const context = useMessageAttachmentContext(partIndex);\n\n return (\n <AttachmentContext.Provider value={context}>\n {children}\n </AttachmentContext.Provider>\n );\n};\n","export { ComposerPrimitiveRoot as Root } from \"./ComposerRoot\";\nexport { ComposerPrimitiveInput as Input } from \"./ComposerInput\";\nexport { ComposerPrimitiveSend as Send } from \"./ComposerSend\";\nexport { ComposerPrimitiveCancel as Cancel } from \"./ComposerCancel\";\nexport { ComposerPrimitiveAddAttachment as AddAttachment } from \"./ComposerAddAttachment\";\nexport { ComposerPrimitiveAttachments as Attachments } from \"./ComposerAttachments\";\nexport { ComposerPrimitiveIf as If } from \"./ComposerIf\";\n","\"use client\";\n\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport {\n type ElementRef,\n type FormEvent,\n forwardRef,\n ComponentPropsWithoutRef,\n} from \"react\";\nimport { useComposerSend } from \"../../primitive-hooks\";\n\ntype ComposerPrimitiveRootElement = ElementRef<typeof Primitive.form>;\ntype PrimitiveFormProps = ComponentPropsWithoutRef<typeof Primitive.form>;\n\nexport type ComposerPrimitiveRootProps = PrimitiveFormProps;\n\nexport const ComposerPrimitiveRoot = forwardRef<\n ComposerPrimitiveRootElement,\n ComposerPrimitiveRootProps\n>(({ onSubmit, ...rest }, forwardedRef) => {\n const send = useComposerSend();\n\n const handleSubmit = (e: FormEvent) => {\n e.preventDefault();\n\n if (!send) return;\n send();\n };\n\n return (\n <Primitive.form\n {...rest}\n ref={forwardedRef}\n onSubmit={composeEventHandlers(onSubmit, handleSubmit)}\n />\n );\n});\n\nComposerPrimitiveRoot.displayName = \"ComposerPrimitive.Root\";\n","\"use client\";\n\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { Slot } from \"@radix-ui/react-slot\";\nimport {\n type KeyboardEvent,\n forwardRef,\n useCallback,\n useEffect,\n useRef,\n} from \"react\";\nimport TextareaAutosize, {\n type TextareaAutosizeProps,\n} from \"react-textarea-autosize\";\nimport {\n useComposer,\n useComposerStore,\n} from \"../../context/react/ComposerContext\";\nimport { useThread, useThreadStore } from \"../../context/react/ThreadContext\";\nimport { useEscapeKeydown } from \"@radix-ui/react-use-escape-keydown\";\nimport { useOnComposerFocus } from \"../../utils/hooks/useOnComposerFocus\";\n\nexport type ComposerPrimitiveInputProps = TextareaAutosizeProps & {\n asChild?: boolean | undefined;\n};\n\nexport const ComposerPrimitiveInput = forwardRef<\n HTMLTextAreaElement,\n ComposerPrimitiveInputProps\n>(\n (\n {\n autoFocus = false,\n asChild,\n disabled: disabledProp,\n onChange,\n onKeyDown,\n ...rest\n },\n forwardedRef,\n ) => {\n const threadStore = useThreadStore();\n const composerStore = useComposerStore();\n\n const value = useComposer((c) => {\n if (!c.isEditing) return \"\";\n return c.text;\n });\n\n const Component = asChild ? Slot : TextareaAutosize;\n\n const isDisabled = useThread((t) => t.isDisabled) ?? disabledProp ?? false;\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const ref = useComposedRefs(forwardedRef, textareaRef);\n\n useEscapeKeydown((e) => {\n const composer = composerStore.getState();\n if (composer.canCancel) {\n composer.cancel();\n e.preventDefault();\n }\n });\n\n const handleKeyPress = (e: KeyboardEvent) => {\n if (isDisabled) return;\n\n // ignore IME composition events\n if (e.nativeEvent.isComposing) return;\n\n if (e.key === \"Enter\" && e.shiftKey === false) {\n const { isRunning } = threadStore.getState();\n\n if (!isRunning) {\n e.preventDefault();\n\n textareaRef.current?.closest(\"form\")?.requestSubmit();\n }\n }\n };\n\n const autoFocusEnabled = autoFocus && !isDisabled;\n const focus = useCallback(() => {\n const textarea = textareaRef.current;\n if (!textarea || !autoFocusEnabled) return;\n\n textarea.focus({ preventScroll: true });\n textarea.setSelectionRange(\n textareaRef.current.value.length,\n textareaRef.current.value.length,\n );\n }, [autoFocusEnabled]);\n\n useEffect(() => focus(), [focus]);\n\n useOnComposerFocus(() => {\n if (composerStore.getState().type === \"thread\") {\n focus();\n }\n });\n\n return (\n <Component\n name=\"input\"\n value={value}\n {...rest}\n ref={ref}\n disabled={isDisabled}\n onChange={composeEventHandlers(onChange, (e) => {\n const composerState = composerStore.getState();\n if (!composerState.isEditing) return;\n return composerState.setText(e.target.value);\n })}\n onKeyDown={composeEventHandlers(onKeyDown, handleKeyPress)}\n />\n );\n },\n);\n\nComposerPrimitiveInput.displayName = \"ComposerPrimitive.Input\";\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerSend } from \"../../primitive-hooks\";\n\nexport type ComposerPrimitiveSendProps = ActionButtonProps<\n typeof useComposerSend\n>;\n\nexport const ComposerPrimitiveSend = createActionButton(\n \"ComposerPrimitive.Send\",\n useComposerSend,\n);\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerCancel } from \"../../primitive-hooks/composer/useComposerCancel\";\n\nexport type ComposerPrimitiveCancelProps = ActionButtonProps<\n typeof useComposerCancel\n>;\n\nexport const ComposerPrimitiveCancel = createActionButton(\n \"ComposerPrimitive.Cancel\",\n useComposerCancel,\n);\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerAddAttachment } from \"../../primitive-hooks/composer\";\n\nexport type ComposerPrimitiveAddAttachmentProps = ActionButtonProps<\n typeof useComposerAddAttachment\n>;\n\nexport const ComposerPrimitiveAddAttachment = createActionButton(\n \"ComposerPrimitive.AddAttachment\",\n useComposerAddAttachment,\n);\n","\"use client\";\n\nimport { ComponentType, type FC, memo } from \"react\";\nimport { useComposerAttachment } from \"../../context/react/AttachmentContext\";\nimport { ComposerAttachmentProvider } from \"../../context/providers/ComposerAttachmentProvider\";\nimport type { ThreadComposerAttachment } from \"../../context/stores/Attachment\";\nimport { useThreadComposer } from \"../../context/react/ThreadContext\";\n\nexport type ComposerPrimitiveAttachmentsProps = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n};\n\nconst getComponent = (\n components: ComposerPrimitiveAttachmentsProps[\"components\"],\n attachment: ThreadComposerAttachment,\n) => {\n const type = attachment.type;\n switch (type) {\n case \"image\":\n return components?.Image ?? components?.Attachment;\n case \"document\":\n return components?.Document ?? components?.Attachment;\n case \"file\":\n return components?.File ?? components?.Attachment;\n default:\n const _exhaustiveCheck: never = type;\n throw new Error(`Unknown attachment type: ${_exhaustiveCheck}`);\n }\n};\n\nconst AttachmentComponent: FC<{\n components: ComposerPrimitiveAttachmentsProps[\"components\"];\n}> = ({ components }) => {\n const Component = useComposerAttachment((a) =>\n getComponent(components, a.attachment),\n );\n\n if (!Component) return null;\n return <Component />;\n};\n\nconst ComposerAttachmentImpl: FC<\n ComposerPrimitiveAttachmentsProps & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n return (\n <ComposerAttachmentProvider attachmentIndex={attachmentIndex}>\n <AttachmentComponent components={components} />\n </ComposerAttachmentProvider>\n );\n};\n\nconst ComposerAttachment = memo(\n ComposerAttachmentImpl,\n (prev, next) =>\n prev.attachmentIndex === next.attachmentIndex &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.Document === next.components?.Document &&\n prev.components?.File === next.components?.File &&\n prev.components?.Attachment === next.components?.Attachment,\n);\n\nexport const ComposerPrimitiveAttachments: FC<\n ComposerPrimitiveAttachmentsProps\n> = ({ components }) => {\n const attachmentsCount = useThreadComposer((s) => s.attachments.length);\n\n return Array.from({ length: attachmentsCount }, (_, index) => (\n <ComposerAttachment\n key={index}\n attachmentIndex={index}\n components={components}\n />\n ));\n};\n\nComposerPrimitiveAttachments.displayName = \"ComposerPrimitive.Attachments\";\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport type { ThreadComposerState } from \"../stores\";\nimport { ComposerAttachmentState } from \"../stores/Attachment\";\nimport {\n AttachmentContext,\n AttachmentContextValue,\n} from \"../react/AttachmentContext\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport { useThreadComposerStore } from \"../react/ThreadContext\";\n\ntype ComposerAttachmentProviderProps = PropsWithChildren<{\n attachmentIndex: number;\n}>;\n\nconst getAttachment = (\n { attachments }: ThreadComposerState,\n useAttachment: AttachmentContextValue[\"useAttachment\"] | undefined,\n partIndex: number,\n) => {\n const attachment = attachments[partIndex];\n if (!attachment) return null;\n\n // if the attachment is the same, don't update\n const currentState = useAttachment?.getState();\n if (currentState && currentState.attachment === attachment) return null;\n\n return Object.freeze({ attachment });\n};\n\nconst useComposerAttachmentContext = (partIndex: number) => {\n const threadComposerStore = useThreadComposerStore();\n const [context] = useState<AttachmentContextValue & { type: \"composer\" }>(\n () => {\n const useAttachment = create<ComposerAttachmentState>(\n () =>\n getAttachment(threadComposerStore.getState(), undefined, partIndex)!,\n );\n\n return { type: \"composer\", useAttachment };\n },\n );\n\n useEffect(() => {\n const syncAttachment = (composer: ThreadComposerState) => {\n const newState = getAttachment(\n composer,\n context.useAttachment,\n partIndex,\n );\n if (!newState) return;\n writableStore(context.useAttachment).setState(newState, true);\n };\n\n syncAttachment(threadComposerStore.getState());\n return threadComposerStore.subscribe(syncAttachment);\n }, [context, threadComposerStore, partIndex]);\n\n return context;\n};\n\nexport const ComposerAttachmentProvider: FC<\n ComposerAttachmentProviderProps\n> = ({ attachmentIndex: partIndex, children }) => {\n const context = useComposerAttachmentContext(partIndex);\n\n return (\n <AttachmentContext.Provider value={context}>\n {children}\n </AttachmentContext.Provider>\n );\n};\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport {\n UseComposerIfProps,\n useComposerIf,\n} from \"../../primitive-hooks/composer/useComposerIf\";\n\nexport type ComposerPrimitiveIfProps = PropsWithChildren<UseComposerIfProps>;\n\nexport const ComposerPrimitiveIf: FC<ComposerPrimitiveIfProps> = ({\n children,\n ...query\n}) => {\n const result = useComposerIf(query);\n return result ? children : null;\n};\n\nComposerPrimitiveIf.displayName = \"ComposerPrimitive.If\";\n","export { ContentPartPrimitiveText as Text } from \"./ContentPartText\";\nexport { ContentPartPrimitiveImage as Image } from \"./ContentPartImage\";\nexport { ContentPartPrimitiveDisplay as Display } from \"./ContentPartDisplay\";\nexport { ContentPartPrimitiveInProgress as InProgress } from \"./ContentPartInProgress\";\n","export { ThreadPrimitiveRoot as Root } from \"./ThreadRoot\";\nexport { ThreadPrimitiveEmpty as Empty } from \"./ThreadEmpty\";\nexport { ThreadPrimitiveIf as If } from \"./ThreadIf\";\nexport { ThreadPrimitiveViewport as Viewport } from \"./ThreadViewport\";\nexport { ThreadPrimitiveMessages as Messages } from \"./ThreadMessages\";\nexport { ThreadPrimitiveScrollToBottom as ScrollToBottom } from \"./ThreadScrollToBottom\";\nexport { ThreadPrimitiveSuggestion as Suggestion } from \"./ThreadSuggestion\";\n","\"use client\";\n\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\n\ntype ThreadPrimitiveRootElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type ThreadPrimitiveRootProps = PrimitiveDivProps;\n\nexport const ThreadPrimitiveRoot = forwardRef<\n ThreadPrimitiveRootElement,\n ThreadPrimitiveRootProps\n>((props, ref) => {\n return <Primitive.div {...props} ref={ref} />;\n});\n\nThreadPrimitiveRoot.displayName = \"ThreadPrimitive.Root\";\n","\"use client\";\n\nimport type { FC, ReactNode } from \"react\";\nimport { useThreadEmpty } from \"../../primitive-hooks\";\n\nexport type ThreadPrimitiveEmptyProps = {\n children: ReactNode;\n};\n\nexport const ThreadPrimitiveEmpty: FC<ThreadPrimitiveEmptyProps> = ({\n children,\n}) => {\n const empty = useThreadEmpty();\n return empty ? children : null;\n};\n\nThreadPrimitiveEmpty.displayName = \"ThreadPrimitive.Empty\";\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport {\n UseThreadIfProps,\n useThreadIf,\n} from \"../../primitive-hooks/thread/useThreadIf\";\n\nexport type ThreadPrimitiveIfProps = PropsWithChildren<UseThreadIfProps>;\n\nexport const ThreadPrimitiveIf: FC<ThreadPrimitiveIfProps> = ({\n children,\n ...query\n}) => {\n const result = useThreadIf(query);\n return result ? children : null;\n};\n\nThreadPrimitiveIf.displayName = \"ThreadPrimitive.If\";\n","\"use client\";\n\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\nimport { type ElementRef, forwardRef, ComponentPropsWithoutRef } from \"react\";\nimport {\n UseThreadViewportAutoScrollProps,\n useThreadViewportAutoScroll,\n} from \"../../primitive-hooks/thread/useThreadViewportAutoScroll\";\n\ntype ThreadPrimitiveViewportElement = ElementRef<typeof Primitive.div>;\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport type ThreadPrimitiveViewportProps = PrimitiveDivProps &\n UseThreadViewportAutoScrollProps;\n\nexport const ThreadPrimitiveViewport = forwardRef<\n ThreadPrimitiveViewportElement,\n ThreadPrimitiveViewportProps\n>(({ autoScroll, children, ...rest }, forwardedRef) => {\n const autoScrollRef = useThreadViewportAutoScroll<HTMLDivElement>({\n autoScroll,\n });\n\n const ref = useComposedRefs(forwardedRef, autoScrollRef);\n\n return (\n <Primitive.div {...rest} ref={ref}>\n {children}\n </Primitive.div>\n );\n});\n\nThreadPrimitiveViewport.displayName = \"ThreadPrimitive.Viewport\";\n","\"use client\";\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { useRef } from \"react\";\nimport { useThreadViewportStore } from \"../../context/react/ThreadContext\";\nimport { useOnResizeContent } from \"../../utils/hooks/useOnResizeContent\";\nimport { useOnScrollToBottom } from \"../../utils/hooks/useOnScrollToBottom\";\nimport { useManagedRef } from \"../../utils/hooks/useManagedRef\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\n\nexport type UseThreadViewportAutoScrollProps = {\n autoScroll?: boolean | undefined;\n};\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll = true,\n}: UseThreadViewportAutoScrollProps) => {\n const divRef = useRef<TElement>(null);\n\n const threadViewportStore = useThreadViewportStore();\n\n const lastScrollTop = useRef<number>(0);\n\n // bug: when ScrollToBottom's button changes its disabled state, the scroll stops\n // fix: delay the state change until the scroll is done\n const isScrollingToBottomRef = useRef(false);\n\n const scrollToBottom = (behavior: ScrollBehavior) => {\n const div = divRef.current;\n if (!div || !autoScroll) return;\n\n isScrollingToBottomRef.current = true;\n div.scrollTo({ top: div.scrollHeight, behavior });\n };\n\n const handleScroll = () => {\n const div = divRef.current;\n if (!div) return;\n\n const isAtBottom = threadViewportStore.getState().isAtBottom;\n const newIsAtBottom =\n div.scrollHeight - div.scrollTop <= div.clientHeight + 1; // TODO figure out why +1 is needed\n\n if (!newIsAtBottom && lastScrollTop.current < div.scrollTop) {\n // ignore scroll down\n } else {\n if (newIsAtBottom) {\n isScrollingToBottomRef.current = false;\n }\n\n if (newIsAtBottom !== isAtBottom) {\n writableStore(threadViewportStore).setState({\n isAtBottom: newIsAtBottom,\n });\n }\n }\n\n lastScrollTop.current = div.scrollTop;\n };\n\n const resizeRef = useOnResizeContent(() => {\n if (\n isScrollingToBottomRef.current ||\n threadViewportStore.getState().isAtBottom\n ) {\n scrollToBottom(\"instant\");\n }\n\n handleScroll();\n });\n\n const scrollRef = useManagedRef<HTMLElement>((el) => {\n el.addEventListener(\"scroll\", handleScroll);\n return () => {\n el.removeEventListener(\"scroll\", handleScroll);\n };\n });\n\n const autoScrollRef = useComposedRefs<TElement>(resizeRef, scrollRef, divRef);\n\n useOnScrollToBottom(() => {\n scrollToBottom(\"auto\");\n });\n\n return autoScrollRef;\n};\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useCallback } from \"react\";\nimport { useManagedRef } from \"./useManagedRef\";\n\nexport const useOnResizeContent = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n\n const refCallback = useCallback(\n (el: HTMLElement) => {\n const resizeObserver = new ResizeObserver(() => {\n callbackRef();\n });\n\n const mutationObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n for (const node of mutation.addedNodes) {\n if (node instanceof Element) {\n resizeObserver.observe(node);\n }\n }\n\n for (const node of mutation.removedNodes) {\n if (node instanceof Element) {\n resizeObserver.unobserve(node);\n }\n }\n }\n\n callbackRef();\n });\n\n resizeObserver.observe(el);\n mutationObserver.observe(el, { childList: true });\n\n // Observe existing children\n for (const child of el.children) {\n resizeObserver.observe(child);\n }\n\n return () => {\n resizeObserver.disconnect();\n mutationObserver.disconnect();\n };\n },\n [callbackRef],\n );\n\n return useManagedRef(refCallback);\n};\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useEffect } from \"react\";\nimport { useThreadViewportStore } from \"../../context/react/ThreadContext\";\n\nexport const useOnScrollToBottom = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n const threadViewportStore = useThreadViewportStore();\n\n useEffect(() => {\n return threadViewportStore.getState().onScrollToBottom(() => {\n callbackRef();\n });\n }, [threadViewportStore, callbackRef]);\n};\n","\"use client\";\n\nimport { type ComponentType, type FC, memo } from \"react\";\nimport { useThreadMessages } from \"../../context/react/ThreadContext\";\nimport { MessageProvider } from \"../../context/providers/MessageProvider\";\nimport { useEditComposer, useMessage } from \"../../context\";\nimport { ThreadMessage as ThreadMessageType } from \"../../types\";\n\nexport type ThreadPrimitiveMessagesProps = {\n components:\n | {\n Message: ComponentType;\n EditComposer?: ComponentType | undefined;\n UserEditComposer?: ComponentType | undefined;\n AssistantEditComposer?: ComponentType | undefined;\n SystemEditComposer?: ComponentType | undefined;\n UserMessage?: ComponentType | undefined;\n AssistantMessage?: ComponentType | undefined;\n SystemMessage?: ComponentType | undefined;\n }\n | {\n Message?: ComponentType | undefined;\n EditComposer?: ComponentType | undefined;\n UserEditComposer?: ComponentType | undefined;\n AssistantEditComposer?: ComponentType | undefined;\n SystemEditComposer?: ComponentType | undefined;\n UserMessage: ComponentType;\n AssistantMessage: ComponentType;\n SystemMessage?: ComponentType | undefined;\n };\n};\n\nconst isComponentsSame = (\n prev: ThreadPrimitiveMessagesProps[\"components\"],\n next: ThreadPrimitiveMessagesProps[\"components\"],\n) => {\n return (\n prev.Message === next.Message &&\n prev.EditComposer === next.EditComposer &&\n prev.UserEditComposer === next.UserEditComposer &&\n prev.AssistantEditComposer === next.AssistantEditComposer &&\n prev.SystemEditComposer === next.SystemEditComposer &&\n prev.UserMessage === next.UserMessage &&\n prev.AssistantMessage === next.AssistantMessage &&\n prev.SystemMessage === next.SystemMessage\n );\n};\n\nconst DEFAULT_SYSTEM_MESSAGE = () => null;\n\nconst getComponent = (\n components: ThreadPrimitiveMessagesProps[\"components\"],\n role: ThreadMessageType[\"role\"],\n isEditing: boolean,\n) => {\n switch (role) {\n case \"user\":\n if (isEditing) {\n return (\n components.UserEditComposer ??\n components.EditComposer ??\n components.UserMessage ??\n (components.Message as ComponentType)\n );\n } else {\n return components.UserMessage ?? (components.Message as ComponentType);\n }\n case \"assistant\":\n if (isEditing) {\n return (\n components.AssistantEditComposer ??\n components.EditComposer ??\n components.AssistantMessage ??\n (components.Message as ComponentType)\n );\n } else {\n return (\n components.AssistantMessage ?? (components.Message as ComponentType)\n );\n }\n case \"system\":\n if (isEditing) {\n return (\n components.SystemEditComposer ??\n components.EditComposer ??\n components.SystemMessage ??\n (components.Message as ComponentType)\n );\n } else {\n return components.SystemMessage ?? DEFAULT_SYSTEM_MESSAGE;\n }\n default:\n const _exhaustiveCheck: never = role;\n throw new Error(`Unknown message role: ${_exhaustiveCheck}`);\n }\n};\n\ntype ThreadMessageComponentProps = {\n components: ThreadPrimitiveMessagesProps[\"components\"];\n};\n\nconst ThreadMessageComponent: FC<ThreadMessageComponentProps> = ({\n components,\n}) => {\n const role = useMessage((m) => m.message.role);\n const isEditing = useEditComposer((c) => c.isEditing);\n const Component = getComponent(components, role, isEditing);\n\n return <Component />;\n};\n\ntype ThreadMessageProps = {\n messageIndex: number;\n components: ThreadPrimitiveMessagesProps[\"components\"];\n};\n\nconst ThreadMessageImpl: FC<ThreadMessageProps> = ({\n messageIndex,\n components,\n}) => {\n return (\n <MessageProvider messageIndex={messageIndex}>\n <ThreadMessageComponent components={components} />\n </MessageProvider>\n );\n};\n\nconst ThreadMessage = memo(\n ThreadMessageImpl,\n (prev, next) =>\n prev.messageIndex === next.messageIndex &&\n isComponentsSame(prev.components, next.components),\n);\n\nexport const ThreadPrimitiveMessagesImpl: FC<ThreadPrimitiveMessagesProps> = ({\n components,\n}) => {\n const messagesLength = useThreadMessages((t) => t.length);\n if (messagesLength === 0) return null;\n\n return Array.from({ length: messagesLength }, (_, index) => (\n <ThreadMessage key={index} messageIndex={index} components={components} />\n ));\n};\n\nThreadPrimitiveMessagesImpl.displayName = \"ThreadPrimitive.Messages\";\n\nexport const ThreadPrimitiveMessages = memo(\n ThreadPrimitiveMessagesImpl,\n (prev, next) => isComponentsSame(prev.components, next.components),\n);\n","\"use client\";\n\nimport { type FC, type PropsWithChildren, useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport type {\n CoreUserContentPart,\n ThreadMessage,\n} from \"../../types/AssistantTypes\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { MessageContext } from \"../react/MessageContext\";\nimport type { MessageContextValue } from \"../react/MessageContext\";\nimport {\n useThreadActionsStore,\n useThreadMessagesStore,\n} from \"../react/ThreadContext\";\nimport type { MessageState } from \"../stores/Message\";\nimport { makeEditComposerStore } from \"../stores/EditComposer\";\nimport { makeMessageUtilsStore } from \"../stores/MessageUtils\";\nimport { ThreadMessagesState } from \"../stores/ThreadMessages\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype MessageProviderProps = PropsWithChildren<{\n messageIndex: number;\n}>;\n\nconst getIsLast = (messages: ThreadMessagesState, message: ThreadMessage) => {\n return messages[messages.length - 1]?.id === message.id;\n};\n\nconst getMessageState = (\n messages: ThreadMessagesState,\n getBranches: (messageId: string) => readonly string[],\n useMessage: MessageContextValue[\"useMessage\"] | undefined,\n messageIndex: number,\n) => {\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const message = messages[messageIndex];\n if (!message) return null;\n\n const isLast = getIsLast(messages, message);\n const branches = getBranches(message.id);\n\n // if the message is the same, don't update\n const currentState = useMessage?.getState();\n if (\n currentState &&\n currentState.message === message &&\n currentState.parentId === parentId &&\n currentState.branches === branches &&\n currentState.isLast === isLast\n )\n return null;\n\n return Object.freeze({\n message,\n parentId,\n branches,\n isLast,\n });\n};\n\nconst useMessageContext = (messageIndex: number) => {\n const threadMessagesStore = useThreadMessagesStore();\n const threadActionsStore = useThreadActionsStore();\n const [context] = useState<MessageContextValue>(() => {\n const useMessage = create<MessageState>(\n () =>\n getMessageState(\n threadMessagesStore.getState(),\n threadActionsStore.getState().getBranches,\n undefined,\n messageIndex,\n )!,\n );\n const useMessageUtils = makeMessageUtilsStore();\n const useEditComposer = makeEditComposerStore({\n onEdit: () => {\n const message = useMessage.getState().message;\n const text = getThreadMessageText(message);\n\n return text;\n },\n onSend: (text) => {\n const { message, parentId } = useMessage.getState();\n const previousText = getThreadMessageText(message);\n if (previousText === text) return;\n\n const nonTextParts = message.content.filter(\n (part): part is CoreUserContentPart =>\n part.type !== \"text\" && part.type !== \"ui\",\n );\n\n // TODO fix types here\n threadActionsStore.getState().append({\n parentId,\n role: message.role,\n content: [{ type: \"text\", text }, ...nonTextParts] as any,\n attachments: (message as any).attachments,\n });\n },\n });\n\n return { useMessage, useMessageUtils, useEditComposer };\n });\n\n useEffect(() => {\n const syncMessage = (thread: ThreadMessagesState) => {\n const newState = getMessageState(\n thread,\n threadActionsStore.getState().getBranches,\n context.useMessage,\n messageIndex,\n );\n if (!newState) return;\n writableStore(context.useMessage).setState(newState, true);\n };\n\n syncMessage(threadMessagesStore.getState());\n\n return threadMessagesStore.subscribe(syncMessage);\n }, [threadMessagesStore, threadActionsStore, context, messageIndex]);\n\n return context;\n};\n\nexport const MessageProvider: FC<MessageProviderProps> = ({\n messageIndex,\n children,\n}) => {\n const context = useMessageContext(messageIndex);\n\n return (\n <MessageContext.Provider value={context}>\n {children}\n </MessageContext.Provider>\n );\n};\n","import { create, UseBoundStore } from \"zustand\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\n\nexport type EditComposerState = Readonly<{\n type: \"edit\";\n\n /** @deprecated Use `text` instead. This will be removed in 0.6.0. */\n value: string;\n /** @deprecated Use `setText` instead. This will be removed in 0.6.0. */\n setValue: (value: string) => void;\n\n text: string;\n setText: (value: string) => void;\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n\n edit: () => void;\n send: () => void;\n cancel: () => void;\n}>;\n\nexport const makeEditComposerStore = ({\n onEdit,\n onSend,\n}: {\n onEdit: () => string;\n onSend: (text: string) => void;\n}): UseBoundStore<ReadonlyStore<EditComposerState>> =>\n create<EditComposerState>()((set, get) => ({\n type: \"edit\",\n\n get value() {\n return get().text;\n },\n setValue(value) {\n get().setText(value);\n },\n\n text: \"\",\n setText: (text) => {\n set({ text, isEmpty: text.trim().length === 0 });\n },\n\n canCancel: false,\n isEditing: false,\n isEmpty: true,\n\n edit: () => {\n const text = onEdit();\n set({\n isEditing: true,\n canCancel: true,\n isEmpty: text.trim().length === 0,\n text,\n });\n },\n send: () => {\n const text = get().text;\n set({ isEditing: false, canCancel: false });\n onSend(text);\n },\n cancel: () => {\n set({ isEditing: false, canCancel: false });\n },\n }));\n","import { create } from \"zustand\";\nimport { SpeechSynthesisAdapter } from \"../../runtimes/speech/SpeechAdapterTypes\";\n\nexport type MessageUtilsState = Readonly<{\n isCopied: boolean;\n setIsCopied: (value: boolean) => void;\n isHovering: boolean;\n setIsHovering: (value: boolean) => void;\n\n isSpeaking: boolean;\n stopSpeaking: () => void;\n addUtterance: (utterance: SpeechSynthesisAdapter.Utterance) => void;\n\n submittedFeedback: \"positive\" | \"negative\" | null;\n setSubmittedFeedback: (feedback: \"positive\" | \"negative\" | null) => void;\n}>;\n\nexport const makeMessageUtilsStore = () =>\n create<MessageUtilsState>((set) => {\n let utterance: SpeechSynthesisAdapter.Utterance | null = null;\n return {\n isCopied: false,\n setIsCopied: (value) => {\n set({ isCopied: value });\n },\n isHovering: false,\n setIsHovering: (value) => {\n set({ isHovering: value });\n },\n isSpeaking: false,\n stopSpeaking: () => {\n utterance?.cancel();\n },\n addUtterance: (utt) => {\n utterance = utt;\n set({ isSpeaking: true });\n utt.onEnd(() => {\n set({ isSpeaking: false });\n });\n },\n submittedFeedback: null,\n setSubmittedFeedback: (feedback) => {\n set({ submittedFeedback: feedback });\n },\n };\n });\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadScrollToBottom } from \"../../primitive-hooks/thread/useThreadScrollToBottom\";\n\nexport type ThreadPrimitiveScrollToBottomProps = ActionButtonProps<\n typeof useThreadScrollToBottom\n>;\n\nexport const ThreadPrimitiveScrollToBottom = createActionButton(\n \"ThreadPrimitive.ScrollToBottom\",\n useThreadScrollToBottom,\n);\n","\"use client\";\n\nimport {\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadSuggestion } from \"../../primitive-hooks/thread/useThreadSuggestion\";\n\nexport type ThreadPrimitiveSuggestionProps = ActionButtonProps<\n typeof useThreadSuggestion\n>;\n\nexport const ThreadPrimitiveSuggestion = createActionButton(\n \"ThreadPrimitive.Suggestion\",\n useThreadSuggestion,\n [\"prompt\", \"autoSend\", \"method\"],\n);\n","\"use client\";\n\nimport {\n ComponentType,\n FC,\n PropsWithChildren,\n ReactNode,\n createContext,\n useContext,\n} from \"react\";\n\nimport { AvatarProps } from \"./base/avatar\";\nimport { TextContentPartComponent, ToolCallContentPartProps } from \"../types\";\nimport { AssistantRuntime } from \"../runtimes\";\nimport { AssistantRuntimeProvider } from \"../context\";\nimport { AssistantToolUI } from \"../model-config\";\nimport { useAssistantRuntimeStore as useAssistantActionsStore } from \"../context/react/AssistantContext\";\n\nexport type SuggestionConfig = {\n text?: ReactNode;\n prompt: string;\n};\n\nexport type ThreadWelcomeConfig = {\n message?: string | null | undefined;\n suggestions?: SuggestionConfig[] | undefined;\n};\n\nexport type UserMessageConfig = {\n allowEdit?: boolean | undefined;\n};\n\nexport type AssistantMessageConfig = {\n allowReload?: boolean | undefined;\n allowCopy?: boolean | undefined;\n allowSpeak?: boolean | undefined;\n allowFeedbackPositive?: boolean | undefined;\n allowFeedbackNegative?: boolean | undefined;\n components?:\n | {\n Text?: TextContentPartComponent | undefined;\n ToolFallback?: ComponentType<ToolCallContentPartProps> | undefined;\n }\n | undefined;\n};\n\nexport type BranchPickerConfig = {\n allowBranchPicker?: boolean | undefined;\n};\n\nexport type ComposerConfig = {\n allowAttachments?: boolean | undefined;\n};\n\nexport type StringsConfig = {\n assistantModal?: {\n open: {\n button: {\n tooltip?: string | undefined;\n };\n };\n closed: {\n button: {\n tooltip?: string | undefined;\n };\n };\n };\n thread?: {\n scrollToBottom?: {\n tooltip?: string | undefined;\n };\n };\n userMessage?: {\n edit?: {\n tooltip?: string | undefined;\n };\n };\n assistantMessage?: {\n reload?: {\n tooltip?: string | undefined;\n };\n copy?: {\n tooltip?: string | undefined;\n };\n speak?: {\n tooltip?: string | undefined;\n stop?: {\n tooltip?: string | undefined;\n };\n };\n feedback?: {\n positive?: {\n tooltip?: string | undefined;\n };\n negative?: {\n tooltip?: string | undefined;\n };\n };\n };\n branchPicker?: {\n previous?: {\n tooltip?: string | undefined;\n };\n next?: {\n tooltip?: string | undefined;\n };\n };\n composer?: {\n send?:\n | {\n tooltip?: string | undefined;\n }\n | undefined;\n cancel?:\n | {\n tooltip?: string | undefined;\n }\n | undefined;\n addAttachment?:\n | {\n tooltip?: string | undefined;\n }\n | undefined;\n removeAttachment?: {\n tooltip?: string | undefined;\n };\n input?: {\n placeholder?: string | undefined;\n };\n };\n editComposer?: {\n send?: {\n label?: string | undefined;\n };\n cancel?: {\n label?: string | undefined;\n };\n };\n code?: {\n header?: {\n copy?: {\n tooltip?: string | undefined;\n };\n };\n };\n};\n\nconst ThreadConfigContext = createContext<ThreadConfig>({});\n\nexport type ThreadConfig = {\n runtime?: AssistantRuntime;\n\n assistantAvatar?: AvatarProps;\n\n welcome?: ThreadWelcomeConfig;\n assistantMessage?: AssistantMessageConfig;\n userMessage?: UserMessageConfig;\n\n branchPicker?: BranchPickerConfig;\n\n composer?: ComposerConfig;\n\n strings?: StringsConfig;\n\n tools?: AssistantToolUI[]; // TODO add AssistantTool support\n};\n\nexport const useThreadConfig = (): Omit<ThreadConfig, \"runtime\"> => {\n return useContext(ThreadConfigContext);\n};\n\nexport type ThreadConfigProviderProps = PropsWithChildren<{\n config?: ThreadConfig | undefined;\n}>;\n\nexport const ThreadConfigProvider: FC<ThreadConfigProviderProps> = ({\n children,\n config,\n}) => {\n const hasAssistant = !!useAssistantActionsStore({ optional: true });\n\n const configProvider =\n config && Object.keys(config ?? {}).length > 0 ? (\n <ThreadConfigContext.Provider value={config}>\n {children}\n </ThreadConfigContext.Provider>\n ) : (\n <>{children}</>\n );\n if (!config?.runtime) return configProvider;\n\n if (hasAssistant) {\n throw new Error(\n \"You provided a runtime to <Thread> while simulataneously using <AssistantRuntimeProvider>. This is not allowed.\",\n );\n }\n return (\n <AssistantRuntimeProvider runtime={config.runtime}>\n {configProvider}\n </AssistantRuntimeProvider>\n );\n};\n\nThreadConfigProvider.displayName = \"ThreadConfigProvider\";\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\nimport {\n AudioLinesIcon,\n CheckIcon,\n CopyIcon,\n RefreshCwIcon,\n StopCircleIcon,\n ThumbsDownIcon,\n ThumbsUpIcon,\n} from \"lucide-react\";\nimport { ActionBarPrimitive, MessagePrimitive } from \"../primitives\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { useThread } from \"../context\";\n\nconst useAllowCopy = (ensureCapability = false) => {\n const { assistantMessage: { allowCopy = true } = {} } = useThreadConfig();\n const copySupported = useThread((t) => t.capabilities.unstable_copy);\n return allowCopy && (!ensureCapability || copySupported);\n};\n\nconst useAllowSpeak = (ensureCapability = false) => {\n const { assistantMessage: { allowSpeak = true } = {} } = useThreadConfig();\n const speakSupported = useThread((t) => t.capabilities.speak);\n return allowSpeak && (!ensureCapability || speakSupported);\n};\n\nconst useAllowReload = (ensureCapability = false) => {\n const { assistantMessage: { allowReload = true } = {} } = useThreadConfig();\n const reloadSupported = useThread((t) => t.capabilities.reload);\n return allowReload && (!ensureCapability || reloadSupported);\n};\n\nconst useAllowFeedbackPositive = (ensureCapability = false) => {\n const { assistantMessage: { allowFeedbackPositive = true } = {} } =\n useThreadConfig();\n const feedbackSupported = useThread((t) => t.capabilities.feedback);\n return allowFeedbackPositive && (!ensureCapability || feedbackSupported);\n};\n\nconst useAllowFeedbackNegative = (ensureCapability = false) => {\n const { assistantMessage: { allowFeedbackNegative = true } = {} } =\n useThreadConfig();\n const feedbackSupported = useThread((t) => t.capabilities.feedback);\n return allowFeedbackNegative && (!ensureCapability || feedbackSupported);\n};\n\nconst AssistantActionBar: FC = () => {\n const allowCopy = useAllowCopy(true);\n const allowReload = useAllowReload(true);\n const allowSpeak = useAllowSpeak(true);\n const allowFeedbackPositive = useAllowFeedbackPositive(true);\n const allowFeedbackNegative = useAllowFeedbackNegative(true);\n if (\n !allowCopy &&\n !allowReload &&\n !allowSpeak &&\n !allowFeedbackPositive &&\n !allowFeedbackNegative\n )\n return null;\n\n return (\n <AssistantActionBarRoot\n hideWhenRunning\n autohide=\"not-last\"\n autohideFloat=\"single-branch\"\n >\n {allowSpeak && <AssistantActionBarSpeechControl />}\n {allowCopy && <AssistantActionBarCopy />}\n {allowReload && <AssistantActionBarReload />}\n {allowFeedbackPositive && <AssistantActionBarFeedbackPositive />}\n {allowFeedbackNegative && <AssistantActionBarFeedbackNegative />}\n </AssistantActionBarRoot>\n );\n};\n\nAssistantActionBar.displayName = \"AssistantActionBar\";\n\nconst AssistantActionBarRoot = withDefaults(ActionBarPrimitive.Root, {\n className: \"aui-assistant-action-bar-root\",\n});\n\nAssistantActionBarRoot.displayName = \"AssistantActionBarRoot\";\n\nconst AssistantActionBarCopy = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: { copy: { tooltip = \"Copy\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n return (\n <ActionBarPrimitive.Copy asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? (\n <>\n <MessagePrimitive.If copied>\n <CheckIcon />\n </MessagePrimitive.If>\n <MessagePrimitive.If copied={false}>\n <CopyIcon />\n </MessagePrimitive.If>\n </>\n )}\n </TooltipIconButton>\n </ActionBarPrimitive.Copy>\n );\n});\n\nAssistantActionBarCopy.displayName = \"AssistantActionBarCopy\";\n\nconst AssistantActionBarSpeechControl: FC = () => {\n return (\n <>\n <MessagePrimitive.If speaking={false}>\n <AssistantActionBarSpeak />\n </MessagePrimitive.If>\n <MessagePrimitive.If speaking>\n <AssistantActionBarStopSpeaking />\n </MessagePrimitive.If>\n </>\n );\n};\n\nconst AssistantActionBarSpeak = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: { speak: { tooltip = \"Read aloud\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowSpeak = useAllowSpeak();\n\n return (\n <ActionBarPrimitive.Speak disabled={!allowSpeak} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <AudioLinesIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.Speak>\n );\n});\n\nAssistantActionBarSpeak.displayName = \"AssistantActionBarSpeak\";\n\nconst AssistantActionBarStopSpeaking = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: {\n speak: { stop: { tooltip: stopTooltip = \"Stop\" } = {} } = {},\n } = {},\n } = {},\n } = useThreadConfig();\n const allowSpeak = useAllowSpeak();\n\n return (\n <ActionBarPrimitive.StopSpeaking disabled={!allowSpeak} asChild>\n <TooltipIconButton tooltip={stopTooltip} {...props} ref={ref}>\n {props.children ?? <StopCircleIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.StopSpeaking>\n );\n});\n\nAssistantActionBarStopSpeaking.displayName = \"AssistantActionBarStopSpeaking\";\n\nconst AssistantActionBarReload = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: { reload: { tooltip = \"Refresh\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowReload = useAllowReload();\n return (\n <ActionBarPrimitive.Reload disabled={!allowReload} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <RefreshCwIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.Reload>\n );\n});\n\nAssistantActionBarReload.displayName = \"AssistantActionBarReload\";\n\nconst AssistantActionBarFeedbackPositive = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: {\n feedback: { positive: { tooltip = \"Good response\" } = {} } = {},\n } = {},\n } = {},\n } = useThreadConfig();\n const allowFeedbackPositive = useAllowFeedbackPositive();\n return (\n <ActionBarPrimitive.FeedbackPositive\n disabled={!allowFeedbackPositive}\n className=\"aui-assistant-action-bar-feedback-positive\"\n asChild\n >\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ThumbsUpIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.FeedbackPositive>\n );\n});\n\nAssistantActionBarFeedbackPositive.displayName =\n \"AssistantActionBarFeedbackPositive\";\n\nconst AssistantActionBarFeedbackNegative = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n assistantMessage: {\n feedback: { negative: { tooltip = \"Bad response\" } = {} } = {},\n } = {},\n } = {},\n } = useThreadConfig();\n const allowFeedbackNegative = useAllowFeedbackNegative();\n return (\n <ActionBarPrimitive.FeedbackNegative\n disabled={!allowFeedbackNegative}\n className=\"aui-assistant-action-bar-feedback-negative\"\n asChild\n >\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ThumbsDownIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.FeedbackNegative>\n );\n});\n\nAssistantActionBarFeedbackNegative.displayName =\n \"AssistantActionBarFeedbackNegative\";\n\nconst exports = {\n Root: AssistantActionBarRoot,\n Reload: AssistantActionBarReload,\n Copy: AssistantActionBarCopy,\n Speak: AssistantActionBarSpeak,\n StopSpeaking: AssistantActionBarStopSpeaking,\n SpeechControl: AssistantActionBarSpeechControl,\n FeedbackPositive: AssistantActionBarFeedbackPositive,\n FeedbackNegative: AssistantActionBarFeedbackNegative,\n};\n\nexport default Object.assign(\n AssistantActionBar,\n exports,\n) as typeof AssistantActionBar & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, useMemo, type FC } from \"react\";\nimport { MessagePrimitive, MessagePrimitiveContentProps } from \"../primitives\";\nimport BranchPicker from \"./branch-picker\";\nimport { Avatar } from \"./base/avatar\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport AssistantActionBar from \"./assistant-action-bar\";\nimport ContentPart from \"./content-part\";\n\nconst AssistantMessage: FC = () => {\n return (\n <AssistantMessageRoot>\n <AssistantMessageAvatar />\n <AssistantMessageContent />\n <BranchPicker />\n <AssistantActionBar />\n </AssistantMessageRoot>\n );\n};\n\nAssistantMessage.displayName = \"AssistantMessage\";\n\nconst AssistantMessageAvatar: FC = () => {\n const { assistantAvatar: avatar = { fallback: \"A\" } } = useThreadConfig();\n return <Avatar {...avatar} />;\n};\n\nconst AssistantMessageRoot = withDefaults(MessagePrimitive.Root, {\n className: \"aui-assistant-message-root\",\n});\n\nAssistantMessageRoot.displayName = \"AssistantMessageRoot\";\n\nconst AssistantMessageContentWrapper = withDefaults(\"div\", {\n className: \"aui-assistant-message-content\",\n});\n\nexport type AssistantMessageContentProps = MessagePrimitiveContentProps &\n ComponentPropsWithoutRef<\"div\">;\n\nconst AssistantMessageContent = forwardRef<\n HTMLDivElement,\n AssistantMessageContentProps\n>(({ components: componentsProp, ...rest }, ref) => {\n const { tools, assistantMessage: { components = {} } = {} } =\n useThreadConfig();\n\n const toolsComponents = useMemo(\n () => ({\n by_name: !tools\n ? undefined\n : Object.fromEntries(\n tools.map((t) => [\n t.unstable_tool.toolName,\n t.unstable_tool.render,\n ]),\n ),\n Fallback: components.ToolFallback,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [...(tools ?? []), components.ToolFallback],\n );\n\n return (\n <AssistantMessageContentWrapper {...rest} ref={ref}>\n <MessagePrimitive.Content\n components={{\n ...componentsProp,\n Text: componentsProp?.Text ?? components.Text ?? ContentPart.Text,\n tools: toolsComponents,\n }}\n />\n </AssistantMessageContentWrapper>\n );\n});\n\nAssistantMessageContent.displayName = \"AssistantMessageContent\";\n\nconst exports = {\n Root: AssistantMessageRoot,\n Avatar: AssistantMessageAvatar,\n Content: AssistantMessageContent,\n};\n\nexport default Object.assign(\n AssistantMessage,\n exports,\n) as typeof AssistantMessage & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\nimport { ChevronLeftIcon, ChevronRightIcon } from \"lucide-react\";\n\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { BranchPickerPrimitive } from \"../primitives\";\nimport { useThread } from \"../context\";\n\nconst useAllowBranchPicker = (ensureCapability = false) => {\n const { branchPicker: { allowBranchPicker = true } = {} } = useThreadConfig();\n const branchPickerSupported = useThread((t) => t.capabilities.edit);\n return allowBranchPicker && (!ensureCapability || branchPickerSupported);\n};\n\nconst BranchPicker: FC = () => {\n const allowBranchPicker = useAllowBranchPicker();\n if (!allowBranchPicker) return null;\n return (\n <BranchPickerRoot hideWhenSingleBranch>\n <BranchPickerPrevious />\n <BranchPickerState />\n <BranchPickerNext />\n </BranchPickerRoot>\n );\n};\n\nBranchPicker.displayName = \"BranchPicker\";\n\nconst BranchPickerRoot = withDefaults(BranchPickerPrimitive.Root, {\n className: \"aui-branch-picker-root\",\n});\n\nBranchPickerRoot.displayName = \"BranchPickerRoot\";\n\nconst BranchPickerPrevious = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n branchPicker: { previous: { tooltip = \"Previous\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowBranchPicker = useAllowBranchPicker();\n return (\n <BranchPickerPrimitive.Previous disabled={!allowBranchPicker} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ChevronLeftIcon />}\n </TooltipIconButton>\n </BranchPickerPrimitive.Previous>\n );\n});\n\nBranchPickerPrevious.displayName = \"BranchPickerPrevious\";\n\nconst BranchPickerStateWrapper = withDefaults(\"span\", {\n className: \"aui-branch-picker-state\",\n});\n\nconst BranchPickerState = forwardRef<\n HTMLSpanElement,\n ComponentPropsWithoutRef<\"span\">\n>((props, ref) => {\n return (\n <BranchPickerStateWrapper {...props} ref={ref}>\n <BranchPickerPrimitive.Number /> / <BranchPickerPrimitive.Count />\n </BranchPickerStateWrapper>\n );\n});\n\nBranchPickerState.displayName = \"BranchPickerState\";\n\nconst BranchPickerNext = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { branchPicker: { next: { tooltip = \"Next\" } = {} } = {} } = {},\n } = useThreadConfig();\n const allowBranchPicker = useAllowBranchPicker();\n return (\n <BranchPickerPrimitive.Next disabled={!allowBranchPicker} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ChevronRightIcon />}\n </TooltipIconButton>\n </BranchPickerPrimitive.Next>\n );\n});\n\nBranchPickerNext.displayName = \"BranchPickerNext\";\n\nconst exports = {\n Root: BranchPickerRoot,\n Previous: BranchPickerPrevious,\n Next: BranchPickerNext,\n};\n\nexport default Object.assign(BranchPicker, exports) as typeof BranchPicker &\n typeof exports;\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport * as AvatarPrimitive from \"@radix-ui/react-avatar\";\n\nimport { withDefaults } from \"../utils/withDefaults\";\n\nexport type AvatarProps = {\n src?: string | undefined;\n alt?: string | undefined;\n fallback?: string | undefined;\n};\n\nexport const Avatar: FC<AvatarProps> = ({ src, alt, fallback }) => {\n if (src == null && fallback == null) return null;\n\n return (\n <AvatarRoot>\n {src != null && <AvatarImage src={src} alt={alt} />}\n {fallback != null && <AvatarFallback>{fallback}</AvatarFallback>}\n </AvatarRoot>\n );\n};\n\nAvatar.displayName = \"Avatar\";\n\nexport const AvatarRoot = withDefaults(AvatarPrimitive.Root, {\n className: \"aui-avatar-root\",\n});\n\nAvatarRoot.displayName = \"AvatarRoot\";\n\nexport const AvatarImage = withDefaults(AvatarPrimitive.Image, {\n className: \"aui-avatar-image\",\n});\n\nAvatarImage.displayName = \"AvatarImage\";\n\nexport const AvatarFallback = withDefaults(AvatarPrimitive.Fallback, {\n className: \"aui-avatar-fallback\",\n});\n\nAvatarFallback.displayName = \"AvatarFallback\";\n","import { FC } from \"react\";\nimport { ContentPartPrimitive } from \"../primitives\";\nimport { useSmoothStatus, withSmoothContextProvider } from \"../utils/smooth\";\nimport classNames from \"classnames\";\n\nexport const Text: FC = () => {\n const status = useSmoothStatus();\n return (\n <ContentPartPrimitive.Text\n className={classNames(\n \"aui-text\",\n status.type === \"running\" && \"aui-text-running\",\n )}\n component=\"p\"\n />\n );\n};\n\nconst exports = { Text: withSmoothContextProvider(Text) };\n\nexport default exports;\n","\"use client\";\n\nimport { type FC, forwardRef } from \"react\";\nimport { BotIcon, ChevronDownIcon } from \"lucide-react\";\n\nimport {\n AssistantModalPrimitive,\n AssistantModalPrimitiveRootProps,\n} from \"../primitives\";\nimport Thread from \"./thread\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport {\n ThreadConfig,\n ThreadConfigProvider,\n ThreadConfigProviderProps,\n useThreadConfig,\n} from \"./thread-config\";\n\nconst AssistantModal: FC<ThreadConfig> = (config) => {\n return (\n <AssistantModalRoot config={config}>\n <AssistantModalTrigger />\n <AssistantModalContent>\n <Thread />\n </AssistantModalContent>\n </AssistantModalRoot>\n );\n};\n\nAssistantModal.displayName = \"AssistantModal\";\n\nconst AssistantModalRoot: FC<\n AssistantModalPrimitiveRootProps & ThreadConfigProviderProps\n> = ({ config, ...props }) => {\n return (\n <ThreadConfigProvider config={config}>\n <AssistantModalPrimitive.Root {...props} />\n </ThreadConfigProvider>\n );\n};\n\nAssistantModalRoot.displayName = \"AssistantModalRoot\";\n\nconst AssistantModalTrigger = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n return (\n <AssistantModalAnchor>\n <AssistantModalPrimitive.Trigger asChild>\n <AssistantModalButton {...props} ref={ref} />\n </AssistantModalPrimitive.Trigger>\n </AssistantModalAnchor>\n );\n});\n\nAssistantModalTrigger.displayName = \"AssistantModalTrigger\";\n\nconst AssistantModalAnchor = withDefaults(AssistantModalPrimitive.Anchor, {\n className: \"aui-root aui-modal-anchor\",\n});\n\nAssistantModalAnchor.displayName = \"AssistantModalAnchor\";\n\nconst ModalButtonStyled = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-modal-button\",\n});\n\ntype AssistantModalButtonProps = TooltipIconButtonProps & {\n \"data-state\"?: \"open\" | \"closed\";\n};\n\nconst AssistantModalButton = forwardRef<\n HTMLButtonElement,\n Partial<AssistantModalButtonProps>\n>(({ \"data-state\": state, ...rest }, ref) => {\n const {\n strings: {\n assistantModal: {\n open: {\n button: { tooltip: openTooltip = \"Close Assistant\" } = {},\n } = {},\n closed: {\n button: { tooltip: closedTooltip = \"Open Assistant\" } = {},\n } = {},\n } = {},\n } = {},\n } = useThreadConfig();\n const tooltip = state === \"open\" ? openTooltip : closedTooltip;\n\n return (\n <ModalButtonStyled\n side=\"left\"\n tooltip={tooltip}\n data-state={state}\n {...rest}\n ref={ref}\n >\n {rest.children ?? (\n <>\n <BotIcon\n data-state={state}\n className=\"aui-modal-button-closed-icon\"\n />\n <ChevronDownIcon\n data-state={state}\n className=\"aui-modal-button-open-icon\"\n />\n </>\n )}\n </ModalButtonStyled>\n );\n});\n\nAssistantModalButton.displayName = \"AssistantModalButton\";\n\nconst AssistantModalContent = withDefaults(AssistantModalPrimitive.Content, {\n className: \"aui-root aui-modal-content\",\n sideOffset: 16,\n});\n\nAssistantModalContent.displayName = \"AssistantModalContent\";\n\nconst exports = {\n Root: AssistantModalRoot,\n Trigger: AssistantModalTrigger,\n Content: AssistantModalContent,\n Button: AssistantModalButton,\n Anchor: AssistantModalAnchor,\n};\n\nexport default Object.assign(AssistantModal, exports) as typeof AssistantModal &\n typeof exports;\n","\"use client\";\n\nimport { ComponentType, forwardRef, type FC } from \"react\";\nimport { ArrowDownIcon } from \"lucide-react\";\n\nimport { withDefaults } from \"./utils/withDefaults\";\nimport Composer from \"./composer\";\nimport ThreadWelcome from \"./thread-welcome\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport AssistantMessage from \"./assistant-message\";\nimport UserMessage from \"./user-message\";\nimport EditComposer from \"./edit-composer\";\nimport {\n ThreadConfig,\n ThreadConfigProvider,\n ThreadConfigProviderProps,\n useThreadConfig,\n} from \"./thread-config\";\nimport { ThreadPrimitive, ThreadPrimitiveRootProps } from \"../primitives\";\n\nconst Thread: FC<ThreadConfig> = (config) => {\n return (\n <ThreadRoot config={config}>\n <ThreadViewport>\n <ThreadWelcome />\n <ThreadMessages />\n <ThreadViewportFooter>\n <ThreadScrollToBottom />\n <Composer />\n </ThreadViewportFooter>\n </ThreadViewport>\n </ThreadRoot>\n );\n};\n\nexport type ThreadRootProps = ThreadPrimitiveRootProps &\n ThreadConfigProviderProps;\n\nconst ThreadRootStyled = withDefaults(ThreadPrimitive.Root, {\n className: \"aui-root aui-thread-root\",\n});\n\nconst ThreadRoot = forwardRef<HTMLDivElement, ThreadRootProps>(\n ({ config, ...props }, ref) => {\n return (\n <ThreadConfigProvider config={config}>\n <ThreadRootStyled {...props} ref={ref} />\n </ThreadConfigProvider>\n );\n },\n);\n\nThreadRoot.displayName = \"ThreadRoot\";\n\nconst ThreadViewport = withDefaults(ThreadPrimitive.Viewport, {\n className: \"aui-thread-viewport\",\n});\n\nThreadViewport.displayName = \"ThreadViewport\";\n\nconst ThreadViewportFooter = withDefaults(\"div\", {\n className: \"aui-thread-viewport-footer\",\n});\n\nThreadViewportFooter.displayName = \"ThreadViewportFooter\";\n\nconst SystemMessage = () => null;\n\nconst ThreadMessages: FC<{\n components?: {\n UserMessage?: ComponentType | undefined;\n EditComposer?: ComponentType | undefined;\n AssistantMessage?: ComponentType | undefined;\n SystemMessage?: ComponentType | undefined;\n };\n}> = ({ components, ...rest }) => {\n return (\n <ThreadPrimitive.Messages\n components={{\n UserMessage: components?.UserMessage ?? UserMessage,\n EditComposer: components?.EditComposer ?? EditComposer,\n AssistantMessage: components?.AssistantMessage ?? AssistantMessage,\n SystemMessage: components?.SystemMessage ?? SystemMessage,\n }}\n {...rest}\n />\n );\n};\n\nThreadMessages.displayName = \"ThreadMessages\";\n\nconst ThreadScrollToBottomIconButton = withDefaults(TooltipIconButton, {\n variant: \"outline\",\n className: \"aui-thread-scroll-to-bottom\",\n});\n\nconst ThreadScrollToBottom = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n thread: { scrollToBottom: { tooltip = \"Scroll to bottom\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ThreadPrimitive.ScrollToBottom asChild>\n <ThreadScrollToBottomIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <ArrowDownIcon />}\n </ThreadScrollToBottomIconButton>\n </ThreadPrimitive.ScrollToBottom>\n );\n});\n\nThreadScrollToBottom.displayName = \"ThreadScrollToBottom\";\n\nconst exports = {\n Root: ThreadRoot,\n Viewport: ThreadViewport,\n Messages: ThreadMessages,\n ScrollToBottom: ThreadScrollToBottom,\n ViewportFooter: ThreadViewportFooter,\n};\n\nexport default Object.assign(Thread, exports) as typeof Thread & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\n\nimport { PaperclipIcon, SendHorizontalIcon } from \"lucide-react\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { CircleStopIcon } from \"./base/CircleStopIcon\";\nimport { ComposerPrimitive, ThreadPrimitive } from \"../primitives\";\nimport { useThread } from \"../context/react/ThreadContext\";\nimport ComposerAttachment from \"./composer-attachment\";\nimport { ComposerPrimitiveAttachmentsProps } from \"../primitives/composer/ComposerAttachments\";\n\nconst useAllowAttachments = (ensureCapability = false) => {\n const { composer: { allowAttachments = true } = {} } = useThreadConfig();\n const attachmentsSupported = useThread((t) => t.capabilities.attachments);\n return allowAttachments && (!ensureCapability || attachmentsSupported);\n};\n\nconst Composer: FC = () => {\n const allowAttachments = useAllowAttachments(true);\n return (\n <ComposerRoot>\n {allowAttachments && <ComposerAttachments />}\n {allowAttachments && <ComposerAddAttachment />}\n <ComposerInput autoFocus />\n <ComposerAction />\n </ComposerRoot>\n );\n};\n\nComposer.displayName = \"Composer\";\n\nconst ComposerRoot = withDefaults(ComposerPrimitive.Root, {\n className: \"aui-composer-root\",\n});\n\nComposerRoot.displayName = \"ComposerRoot\";\n\nconst ComposerInputStyled = withDefaults(ComposerPrimitive.Input, {\n rows: 1,\n autoFocus: true,\n className: \"aui-composer-input\",\n});\n\nexport type ComposerInputProps = ComponentPropsWithoutRef<\n typeof ComposerInputStyled\n>;\nconst ComposerInput = forwardRef<HTMLTextAreaElement, ComposerInputProps>(\n (props, ref) => {\n const {\n strings: {\n composer: { input: { placeholder = \"Write a message...\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ComposerInputStyled placeholder={placeholder} {...props} ref={ref} />\n );\n },\n);\n\nComposerInput.displayName = \"ComposerInput\";\n\nconst ComposerAttachmentsContainer = withDefaults(\"div\", {\n className: \"aui-composer-attachments\",\n});\n\ntype ComposerAttachmentsProps = Partial<ComposerPrimitiveAttachmentsProps>;\n\nconst ComposerAttachments: FC<ComposerAttachmentsProps> = ({ components }) => {\n return (\n <ComposerAttachmentsContainer>\n <ComposerPrimitive.Attachments\n components={{\n ...components,\n Attachment: components?.Attachment ?? ComposerAttachment,\n }}\n />\n </ComposerAttachmentsContainer>\n );\n};\n\nconst ComposerAttachButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-attach\",\n});\n\nconst ComposerAddAttachment = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n composer: { addAttachment: { tooltip = \"Attach file\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n const allowAttachments = useAllowAttachments();\n return (\n <ComposerPrimitive.AddAttachment disabled={!allowAttachments} asChild>\n <ComposerAttachButton\n tooltip={tooltip}\n variant={\"ghost\"}\n {...props}\n ref={ref}\n >\n {props.children ?? <PaperclipIcon />}\n </ComposerAttachButton>\n </ComposerPrimitive.AddAttachment>\n );\n});\n\nComposerAddAttachment.displayName = \"ComposerAddAttachment\";\n\nconst useAllowCancel = () => {\n const cancelSupported = useThread((t) => t.capabilities.cancel);\n return cancelSupported;\n};\n\nconst ComposerAction: FC = () => {\n const allowCancel = useAllowCancel();\n if (!allowCancel) return <ComposerSend />;\n return (\n <>\n <ThreadPrimitive.If running={false}>\n <ComposerSend />\n </ThreadPrimitive.If>\n <ThreadPrimitive.If running>\n <ComposerCancel />\n </ThreadPrimitive.If>\n </>\n );\n};\n\nComposerAction.displayName = \"ComposerAction\";\n\nconst ComposerSendButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-send\",\n});\n\nconst ComposerSend = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { composer: { send: { tooltip = \"Send\" } = {} } = {} } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Send asChild>\n <ComposerSendButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <SendHorizontalIcon />}\n </ComposerSendButton>\n </ComposerPrimitive.Send>\n );\n});\n\nComposerSend.displayName = \"ComposerSend\";\n\nconst ComposerCancelButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-cancel\",\n});\n\nconst ComposerCancel = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { composer: { cancel: { tooltip = \"Cancel\" } = {} } = {} } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Cancel asChild>\n <ComposerCancelButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <CircleStopIcon />}\n </ComposerCancelButton>\n </ComposerPrimitive.Cancel>\n );\n});\n\nComposerCancel.displayName = \"ComposerCancel\";\n\nconst exports = {\n Root: ComposerRoot,\n Input: ComposerInput,\n Action: ComposerAction,\n Send: ComposerSend,\n Cancel: ComposerCancel,\n AddAttachment: ComposerAddAttachment,\n Attachments: ComposerAttachments,\n};\n\nexport default Object.assign(Composer, exports) as typeof Composer &\n typeof exports;\n","import { FC } from \"react\";\n\nexport const CircleStopIcon: FC = () => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 16 16\"\n fill=\"currentColor\"\n width=\"16\"\n height=\"16\"\n >\n <rect width=\"10\" height=\"10\" x=\"3\" y=\"3\" rx=\"2\" />\n </svg>\n );\n};\n\nCircleStopIcon.displayName = \"CircleStopIcon\";\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\n\nimport { CircleXIcon } from \"lucide-react\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\nimport {\n useAttachmentStore,\n useComposerAttachment,\n} from \"../context/react/AttachmentContext\";\n\nconst ComposerAttachmentRoot = withDefaults(\"div\", {\n className: \"aui-composer-attachment-root\",\n});\n\nComposerAttachmentRoot.displayName = \"ComposerAttachmentRoot\";\n\nconst ComposerAttachment: FC = () => {\n const attachment = useComposerAttachment((a) => a.attachment);\n\n return (\n <ComposerAttachmentRoot>\n .{attachment.name.split(\".\").pop()}\n <ComposerAttachmentRemove />\n </ComposerAttachmentRoot>\n );\n};\n\nComposerAttachment.displayName = \"ComposerAttachment\";\n\nconst ComposerAttachmentRemove = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: {\n composer: { removeAttachment: { tooltip = \"Remove file\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n const composerStore = useThreadComposerStore();\n const attachmentStore = useAttachmentStore();\n const handleRemoveAttachment = () => {\n composerStore\n .getState()\n .removeAttachment(attachmentStore.getState().attachment.id);\n };\n\n return (\n <TooltipIconButton\n tooltip={tooltip}\n className=\"aui-composer-attachment-remove\"\n side=\"top\"\n {...props}\n onClick={handleRemoveAttachment}\n ref={ref}\n >\n {props.children ?? <CircleXIcon />}\n </TooltipIconButton>\n );\n});\n\nComposerAttachmentRemove.displayName = \"ComposerAttachmentRemove\";\n\nconst exports = {\n Root: ComposerAttachmentRoot,\n Remove: ComposerAttachmentRemove,\n};\n\nexport default Object.assign(\n ComposerAttachment,\n exports,\n) as typeof ComposerAttachment & typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { Avatar } from \"./base/avatar\";\nimport { SuggestionConfig, useThreadConfig } from \"./thread-config\";\nimport { ThreadPrimitive } from \"../primitives\";\n\nconst ThreadWelcome: FC = () => {\n return (\n <ThreadWelcomeRoot>\n <ThreadWelcomeCenter>\n <ThreadWelcomeAvatar />\n <ThreadWelcomeMessage />\n </ThreadWelcomeCenter>\n <ThreadWelcomeSuggestions />\n </ThreadWelcomeRoot>\n );\n};\n\nThreadWelcome.displayName = \"ThreadWelcome\";\n\nconst ThreadWelcomeRootStyled = withDefaults(\"div\", {\n className: \"aui-thread-welcome-root\",\n});\n\nconst ThreadWelcomeCenter = withDefaults(\"div\", {\n className: \"aui-thread-welcome-center\",\n});\n\ntype ThreadWelcomeRootProps = ComponentPropsWithoutRef<\"div\">;\n\nconst ThreadWelcomeRoot = forwardRef<HTMLDivElement, ThreadWelcomeRootProps>(\n (props, ref) => {\n return (\n <ThreadPrimitive.Empty>\n <ThreadWelcomeRootStyled {...props} ref={ref} />\n </ThreadPrimitive.Empty>\n );\n },\n);\n\nThreadWelcomeRoot.displayName = \"ThreadWelcomeRoot\";\n\nconst ThreadWelcomeAvatar: FC = () => {\n const { assistantAvatar: avatar = { fallback: \"A\" } } = useThreadConfig();\n return <Avatar {...avatar} />;\n};\n\nconst ThreadWelcomeMessageStyled = withDefaults(\"p\", {\n className: \"aui-thread-welcome-message\",\n});\n\nexport type ThreadWelcomeMessageProps = Omit<\n ComponentPropsWithoutRef<typeof ThreadWelcomeMessageStyled>,\n \"children\"\n> & { message?: string | undefined };\n\nconst ThreadWelcomeMessage = forwardRef<\n HTMLParagraphElement,\n ThreadWelcomeMessageProps\n>(({ message: messageProp, ...rest }, ref) => {\n const { welcome: { message = \"How can I help you today?\" } = {} } =\n useThreadConfig();\n return (\n <ThreadWelcomeMessageStyled {...rest} ref={ref}>\n {messageProp ?? message}\n </ThreadWelcomeMessageStyled>\n );\n});\n\nThreadWelcomeMessage.displayName = \"ThreadWelcomeMessage\";\n\nconst ThreadWelcomeSuggestionContainer = withDefaults(\"div\", {\n className: \"aui-thread-welcome-suggestion-container\",\n});\n\nconst ThreadWelcomeSuggestionStyled = withDefaults(ThreadPrimitive.Suggestion, {\n className: \"aui-thread-welcome-suggestion\",\n});\n\nexport type ThreadWelcomeSuggestionProps = {\n suggestion: SuggestionConfig;\n};\n\nconst ThreadWelcomeSuggestion: FC<ThreadWelcomeSuggestionProps> = ({\n suggestion: { text, prompt },\n}) => {\n return (\n <ThreadWelcomeSuggestionStyled\n prompt={prompt}\n method=\"replace\"\n autoSend\n >\n <span className=\"aui-thread-welcome-suggestion-text\">{text ?? prompt}</span>\n </ThreadWelcomeSuggestionStyled>\n );\n};\n\nconst ThreadWelcomeSuggestions: FC = () => {\n const { welcome: { suggestions } = {} } = useThreadConfig();\n return (\n <ThreadWelcomeSuggestionContainer>\n {suggestions?.map((suggestion, idx) => {\n const key = `${suggestion.prompt}-${idx}`;\n return <ThreadWelcomeSuggestion key={key} suggestion={suggestion} />;\n })}\n </ThreadWelcomeSuggestionContainer>\n );\n};\n\nThreadWelcomeSuggestions.displayName = \"ThreadWelcomeSuggestions\";\n\nconst exports = {\n Root: ThreadWelcomeRoot,\n Center: ThreadWelcomeCenter,\n Avatar: ThreadWelcomeAvatar,\n Message: ThreadWelcomeMessage,\n Suggestions: ThreadWelcomeSuggestions,\n Suggestion: ThreadWelcomeSuggestion,\n};\n\nexport default Object.assign(ThreadWelcome, exports) as typeof ThreadWelcome &\n typeof exports;\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type FC } from \"react\";\n\nimport BranchPicker from \"./branch-picker\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport UserActionBar from \"./user-action-bar\";\nimport ContentPart from \"./content-part\";\nimport { MessagePrimitive, MessagePrimitiveContentProps } from \"../primitives\";\nimport UserMessageAttachment from \"./user-message-attachment\";\nimport { MessagePrimitiveAttachmentsProps } from \"../primitives/message/MessageAttachments\";\n\nconst UserMessage: FC = () => {\n return (\n <UserMessageRoot>\n <UserMessageAttachments />\n <UserActionBar />\n <UserMessageContent />\n <BranchPicker />\n </UserMessageRoot>\n );\n};\n\nUserMessage.displayName = \"UserMessage\";\n\nconst UserMessageRoot = withDefaults(MessagePrimitive.Root, {\n className: \"aui-user-message-root\",\n});\n\nUserMessageRoot.displayName = \"UserMessageRoot\";\n\nconst UserMessageContentWrapper = withDefaults(\"div\", {\n className: \"aui-user-message-content\",\n});\n\nexport type UserMessageContentProps = MessagePrimitiveContentProps &\n ComponentPropsWithoutRef<\"div\">;\n\nconst UserMessageContent = forwardRef<HTMLDivElement, UserMessageContentProps>(\n ({ components, ...props }, ref) => {\n return (\n <UserMessageContentWrapper {...props} ref={ref}>\n <MessagePrimitive.Content\n components={{\n ...components,\n Text: components?.Text ?? ContentPart.Text,\n }}\n />\n </UserMessageContentWrapper>\n );\n },\n);\n\nUserMessageContent.displayName = \"UserMessageContent\";\n\nconst UserMessageAttachmentsContainer = withDefaults(\"div\", {\n className: \"aui-user-message-attachments\",\n});\n\nexport type UserMessageAttachmentsProps =\n Partial<MessagePrimitiveAttachmentsProps>;\n\nconst UserMessageAttachments: FC<UserMessageAttachmentsProps> = ({\n components,\n}) => {\n return (\n <MessagePrimitive.If hasAttachments>\n <UserMessageAttachmentsContainer>\n <MessagePrimitive.Attachments\n components={{\n ...components,\n Attachment: components?.Attachment ?? UserMessageAttachment,\n }}\n />\n </UserMessageAttachmentsContainer>\n </MessagePrimitive.If>\n );\n};\n\nconst exports = {\n Root: UserMessageRoot,\n Content: UserMessageContent,\n Attachments: UserMessageAttachments,\n};\n\nexport default Object.assign(UserMessage, exports) as typeof UserMessage &\n typeof exports;\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\nimport { PencilIcon } from \"lucide-react\";\n\nimport {\n TooltipIconButton,\n TooltipIconButtonProps,\n} from \"./base/tooltip-icon-button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { useThread } from \"../context\";\nimport { ActionBarPrimitive } from \"../primitives\";\n\nconst useAllowEdit = (ensureCapability = false) => {\n const { userMessage: { allowEdit = true } = {} } = useThreadConfig();\n const editSupported = useThread((t) => t.capabilities.edit);\n return allowEdit && (!ensureCapability || editSupported);\n};\n\nconst UserActionBar: FC = () => {\n const allowEdit = useAllowEdit(true);\n if (!allowEdit) return null;\n return (\n <UserActionBarRoot hideWhenRunning autohide=\"not-last\">\n <UserActionBarEdit />\n </UserActionBarRoot>\n );\n};\n\nUserActionBar.displayName = \"UserActionBar\";\n\nconst UserActionBarRoot = withDefaults(ActionBarPrimitive.Root, {\n className: \"aui-user-action-bar-root\",\n});\n\nUserActionBarRoot.displayName = \"UserActionBarRoot\";\n\nconst UserActionBarEdit = forwardRef<\n HTMLButtonElement,\n Partial<TooltipIconButtonProps>\n>((props, ref) => {\n const {\n strings: { userMessage: { edit: { tooltip = \"Edit\" } = {} } = {} } = {},\n } = useThreadConfig();\n const allowEdit = useAllowEdit();\n return (\n <ActionBarPrimitive.Edit disabled={!allowEdit} asChild>\n <TooltipIconButton tooltip={tooltip} {...props} ref={ref}>\n {props.children ?? <PencilIcon />}\n </TooltipIconButton>\n </ActionBarPrimitive.Edit>\n );\n});\n\nUserActionBarEdit.displayName = \"UserActionBarEdit\";\n\nconst exports = {\n Root: UserActionBarRoot,\n Edit: UserActionBarEdit,\n};\n\nexport default Object.assign(UserActionBar, exports) as typeof UserActionBar &\n typeof exports;\n","\"use client\";\n\nimport { type FC } from \"react\";\n\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useAttachment } from \"../context/react/AttachmentContext\";\n\nconst UserMessageAttachmentRoot = withDefaults(\"div\", {\n className: \"aui-user-message-attachment-root\",\n});\n\nUserMessageAttachmentRoot.displayName = \"UserMessageAttachmentRoot\";\n\nconst UserMessageAttachment: FC = () => {\n const attachment = useAttachment((a) => a.attachment);\n\n return (\n <UserMessageAttachmentRoot>\n .{attachment.name.split(\".\").pop()}\n </UserMessageAttachmentRoot>\n );\n};\n\nUserMessageAttachment.displayName = \"UserMessageAttachment\";\n\nconst exports = {\n Root: UserMessageAttachmentRoot,\n};\n\nexport default Object.assign(\n UserMessageAttachment,\n exports,\n) as typeof UserMessageAttachment & typeof exports;\n","\"use client\";\n\nimport { forwardRef, type FC } from \"react\";\n\nimport { Button, ButtonProps } from \"./base/button\";\nimport { withDefaults } from \"./utils/withDefaults\";\nimport { useThreadConfig } from \"./thread-config\";\nimport { ComposerPrimitive } from \"../primitives\";\n\nconst EditComposer: FC = () => {\n return (\n <EditComposerRoot>\n <EditComposerInput />\n\n <EditComposerFooter>\n <EditComposerCancel />\n <EditComposerSend />\n </EditComposerFooter>\n </EditComposerRoot>\n );\n};\n\nEditComposer.displayName = \"EditComposer\";\n\nconst EditComposerRoot = withDefaults(ComposerPrimitive.Root, {\n className: \"aui-edit-composer-root\",\n});\n\nEditComposerRoot.displayName = \"EditComposerRoot\";\n\nconst EditComposerInput = withDefaults(ComposerPrimitive.Input, {\n className: \"aui-edit-composer-input\",\n});\n\nEditComposerInput.displayName = \"EditComposerInput\";\n\nconst EditComposerFooter = withDefaults(\"div\", {\n className: \"aui-edit-composer-footer\",\n});\n\nEditComposerFooter.displayName = \"EditComposerFooter\";\n\nconst EditComposerCancel = forwardRef<HTMLButtonElement, Partial<ButtonProps>>(\n (props, ref) => {\n const {\n strings: {\n editComposer: { cancel: { label = \"Cancel\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Cancel asChild>\n <Button variant=\"ghost\" {...props} ref={ref}>\n {props.children ?? label}\n </Button>\n </ComposerPrimitive.Cancel>\n );\n },\n);\n\nEditComposerCancel.displayName = \"EditComposerCancel\";\n\nconst EditComposerSend = forwardRef<HTMLButtonElement, Partial<ButtonProps>>(\n (props, ref) => {\n const {\n strings: { editComposer: { send: { label = \"Send\" } = {} } = {} } = {},\n } = useThreadConfig();\n return (\n <ComposerPrimitive.Send asChild>\n <Button {...props} ref={ref}>\n {props.children ?? label}\n </Button>\n </ComposerPrimitive.Send>\n );\n },\n);\n\nEditComposerSend.displayName = \"EditComposerSend\";\n\nconst exports = {\n Root: EditComposerRoot,\n Input: EditComposerInput,\n Footer: EditComposerFooter,\n Cancel: EditComposerCancel,\n Send: EditComposerSend,\n};\n\nexport default Object.assign(EditComposer, exports) as typeof EditComposer &\n typeof exports;\n"]}