@assistant-ui/react 0.5.67 → 0.5.68

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/react/AssistantContext.ts","../src/context/react/utils/createContextHook.ts","../src/context/react/utils/createContextStoreHook.ts","../src/context/stores/AssistantToolUIs.ts","../src/context/providers/ThreadRuntimeProvider.tsx","../src/context/react/ThreadContext.ts","../src/context/stores/ThreadViewport.tsx","../src/context/ReadonlyStore.ts","../src/context/providers/TextContentPartProvider.tsx","../src/context/react/ContentPartContext.ts","../src/api/ContentPartRuntime.ts","../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/utils/getThreadMessageText.tsx","../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/ContentPartRuntimeProvider.tsx","../src/primitives/contentPart/ContentPartText.tsx","../src/utils/smooth/useSmooth.tsx","../src/utils/smooth/SmoothContext.tsx","../src/primitives/contentPart/ContentPartImage.tsx","../src/primitives/contentPart/ContentPartDisplay.tsx","../src/primitives/contentPart/ContentPartInProgress.tsx","../src/api/ComposerRuntime.ts","../src/api/subscribable/BaseSubject.ts","../src/api/subscribable/NestedSubscriptionSubject.ts","../src/api/subscribable/shallowEqual.ts","../src/api/subscribable/ShallowMemoizeSubject.ts","../src/api/MessageRuntime.ts","../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/MessageRuntimeProvider.tsx","../src/context/stores/MessageUtils.ts","../src/primitives/thread/ThreadScrollToBottom.tsx","../src/primitives/thread/ThreadSuggestion.tsx","../src/runtimes/core/subscribeToMainThread.ts","../src/runtimes/local/useLocalRuntime.tsx","../src/runtimes/core/BaseAssistantRuntimeCore.tsx","../src/internal.ts","../src/runtimes/composer/BaseComposerRuntimeCore.tsx","../src/runtimes/composer/DefaultThreadComposerRuntimeCore.tsx","../src/utils/ProxyConfigProvider.ts","../src/utils/idUtils.tsx","../src/runtimes/edge/converters/fromCoreMessage.ts","../src/runtimes/utils/MessageRepository.tsx","../src/ui/base/tooltip-icon-button.tsx","../src/ui/base/tooltip.tsx","../src/ui/utils/withDefaults.tsx","../src/ui/base/button.tsx","../src/api/AssistantRuntime.ts","../src/api/subscribable/LazyMemoizeSubject.ts","../src/api/ThreadRuntime.ts","../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/composer/DefaultEditComposerRuntimeCore.tsx","../src/runtimes/local/LocalThreadRuntimeCore.tsx","../src/runtimes/local/LocalRuntimeCore.tsx","../src/runtimes/external-store/useExternalStoreRuntime.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/runtimes/external-store/ExternalStoreThreadRuntimeCore.tsx","../src/runtimes/external-store/ExternalStoreRuntimeCore.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/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":["actions","useThreadRuntimeStore","useThreadStore","useThreadMessagesStore","useThreadComposerStore","useThread","useAssistantRuntimeStore","useEffect","useAssistantRuntime","useEditComposer","Primitive","useContentPartStore","COMPLETE_STATUS","useMessageAttachmentContext","useEscapeKeydown","getAttachment","useComposerAttachmentContext","getComponent","AttachmentComponent","useMessageStore","useMessageUtilsStore","useEditComposerStore","messages","BranchPickerPrevious","exports","ComposerAttachment"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;ACbA,8BAAmD;ADenD;AACA;AEjBA;AFmBA;AACA;AGtBA;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;AHSA;AACA;AI1BO,SAAS,sBAAA,CACd,WAAA,EACA,UAAA,EACA;AASA,EAAA,SAAS,iBAAA,CAAkB,OAAA,EAES;AAClC,IAAA,MAAM,QAAA,EAAU,WAAA,CAAY,OAAO,CAAA;AACnC,IAAA,GAAA,CAAI,CAAC,OAAA,EAAS,OAAO,IAAA;AACrB,IAAA,OAAO,OAAA,CAAQ,UAAU,CAAA;AAAA,EAC3B;AAYA,EAAA,SAAS,YAAA,CACP,KAAA,EAM8B;AAC9B,I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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;AtKkoLD;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;AACA;AACA","file":"/home/runner/work/assistant-ui/assistant-ui/packages/react/dist/index.js","sourcesContent":[null,"\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { memo, useEffect, useMemo, useState } from \"react\";\nimport { AssistantContext } from \"../react/AssistantContext\";\nimport { makeAssistantToolUIsStore } from \"../stores/AssistantToolUIs\";\nimport { ThreadRuntimeProvider } from \"./ThreadRuntimeProvider\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\nimport { create } from \"zustand\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype AssistantRuntimeProviderProps = {\n runtime: AssistantRuntime;\n};\n\nconst useAssistantRuntimeStore = (runtime: AssistantRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useAssistantToolUIsStore = () => {\n return useMemo(() => makeAssistantToolUIsStore(), []);\n};\n\nexport const AssistantRuntimeProviderImpl: FC<\n PropsWithChildren<AssistantRuntimeProviderProps>\n> = ({ children, runtime }) => {\n const useAssistantRuntime = useAssistantRuntimeStore(runtime);\n const useToolUIs = useAssistantToolUIsStore();\n const context = useMemo(() => {\n return {\n useToolUIs,\n useAssistantRuntime,\n useAssistantActions: useAssistantRuntime,\n };\n }, [useAssistantRuntime, useToolUIs]);\n\n return (\n <AssistantContext.Provider value={context}>\n <ThreadRuntimeProvider runtime={runtime.thread}>\n {children}\n </ThreadRuntimeProvider>\n </AssistantContext.Provider>\n );\n};\n\nexport const AssistantRuntimeProvider = memo(AssistantRuntimeProviderImpl);\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { AssistantToolUIsState } from \"../stores/AssistantToolUIs\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\n\nexport type AssistantContextValue = {\n useToolUIs: UseBoundStore<ReadonlyStore<AssistantToolUIsState>>;\n useAssistantRuntime: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n\n /**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\n useAssistantActions: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n};\n\nexport const AssistantContext = createContext<AssistantContextValue | null>(\n null,\n);\n\nexport const useAssistantContext = createContextHook(\n AssistantContext,\n \"AssistantRuntimeProvider\",\n);\n\nexport function useAssistantRuntime(options?: {\n optional?: false | undefined;\n}): AssistantRuntime;\nexport function useAssistantRuntime(options?: {\n optional?: boolean | undefined;\n}): AssistantRuntime | null;\nexport function useAssistantRuntime(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useAssistantContext(options);\n if (!context) return null;\n return context.useAssistantRuntime();\n}\n\nexport const actions = createContextStoreHook(\n useAssistantContext,\n \"useAssistantActions\",\n);\n\n/**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useAssistantActionsStore = actions.useAssistantActionsStore;\n\n/**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useAssistantActions = actions.useAssistantActions;\n\n/**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useAssistantRuntimeStore = useAssistantActionsStore;\n\nexport const { useToolUIs, useToolUIsStore } = createContextStoreHook(\n useAssistantContext,\n \"useToolUIs\",\n);\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) return null;\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, useMemo, useState } from \"react\";\nimport type { ThreadContextValue } from \"../react/ThreadContext\";\nimport { ThreadContext } from \"../react/ThreadContext\";\nimport { makeThreadViewportStore } from \"../stores/ThreadViewport\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport { ReactThreadState, ThreadRuntime } from \"../../api/ThreadRuntime\";\nimport { create } from \"zustand\";\nimport { ComposerRuntime } from \"../../api\";\n\ntype ThreadProviderProps = {\n runtime: ThreadRuntime;\n};\n\nconst useThreadRuntimeStore = (runtime: ThreadRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useThreadStore = (runtime: ThreadRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useThreadMessagesStore = (runtime: ThreadRuntime) => {\n const [store] = useState(() => create(() => runtime.messages));\n\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.messages, true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useThreadComposerStore = (\n runtime: ComposerRuntime & { type: \"thread\" },\n) => {\n const [store] = useState(() => create(() => runtime.getState()));\n\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const ThreadRuntimeProvider: FC<\n PropsWithChildren<ThreadProviderProps>\n> = ({ children, runtime }) => {\n const useThreadRuntime = useThreadRuntimeStore(runtime);\n const useThread = useThreadStore(runtime);\n const useThreadMessages = useThreadMessagesStore(runtime);\n const useThreadComposer = useThreadComposerStore(runtime.composer as any); // TODO\n\n const context = useMemo<ThreadContextValue>(() => {\n const useViewport = makeThreadViewportStore();\n\n return {\n useThread,\n useThreadRuntime,\n useThreadMessages,\n useThreadActions: useThreadRuntime,\n useComposer: useThreadComposer,\n useViewport,\n };\n }, [useThread, useThreadRuntime, useThreadMessages, useThreadComposer]);\n\n // subscribe to thread updates\n const Synchronizer = context.useThread(\n (t) => (t as ReactThreadState).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 { ThreadViewportState } from \"../stores/ThreadViewport\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { UseBoundStore } from \"zustand\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { ThreadRuntime } from \"../../api\";\nimport { ThreadState } from \"../../api/ThreadRuntime\";\nimport { ThreadMessage } from \"../../types\";\nimport { ThreadComposerState } from \"../../api/ComposerRuntime\";\n\nexport type ThreadContextValue = {\n useThread: UseBoundStore<ReadonlyStore<ThreadState>>;\n /**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\n useThreadActions: UseBoundStore<ReadonlyStore<ThreadRuntime>>;\n useThreadRuntime: UseBoundStore<ReadonlyStore<ThreadRuntime>>;\n useThreadMessages: UseBoundStore<ReadonlyStore<readonly ThreadMessage[]>>;\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 function useThreadRuntime(options?: {\n optional?: false | undefined;\n}): ThreadRuntime;\nexport function useThreadRuntime(options?: {\n optional?: boolean | undefined;\n}): ThreadRuntime | null;\nexport function useThreadRuntime(options?: { optional?: boolean | undefined }) {\n const context = useThreadContext(options);\n if (!context) return null;\n return context.useThreadRuntime();\n}\n\nexport const actions = createContextStoreHook(\n useThreadContext,\n \"useThreadActions\",\n);\n\n/**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useThreadActionsStore = actions.useThreadActionsStore;\n\n/**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useThreadActions = actions.useThreadActions;\n\n/**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useThreadRuntimeStore = useThreadActionsStore;\n\nexport const { useThread, useThreadStore } = createContextStoreHook(\n useThreadContext,\n \"useThread\",\n);\n\nconst messages = createContextStoreHook(useThreadContext, \"useThreadMessages\");\n\n/**\n * @deprecated Use `useThread().messages` instead. This will be removed in 0.6.0.\n */\nexport const useThreadMessages = messages.useThreadMessages;\n\n/**\n * @deprecated Use `useThreadRuntime().getState().messages` instead. This will be removed in 0.6.0.\n */\nexport const useThreadMessagesStore = messages.useThreadMessagesStore;\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","\"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 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 type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport {\n ContentPartContext,\n ContentPartContextValue,\n} from \"../react/ContentPartContext\";\nimport { ContentPartStatus, TextContentPart } from \"../../types/AssistantTypes\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport {\n ContentPartRuntime,\n ContentPartState,\n} from \"../../api/ContentPartRuntime\";\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 useContentPartRuntime = create(\n // TODO\n () => new ContentPartRuntime(null as any, null as any, null as any),\n );\n const useContentPart = create<ContentPartState>(() => ({\n status: isRunning ? RUNNING_STATUS : COMPLETE_STATUS,\n part: { type: \"text\", text },\n type: \"text\",\n text,\n }));\n\n return { useContentPartRuntime, useContentPart };\n });\n\n useEffect(() => {\n const state = context.useContentPart.getState();\n const textUpdated = (state as TextContentPart).text !== text;\n const targetTextPart = textUpdated\n ? { type: \"text\" as const, text }\n : state;\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 { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { UseBoundStore } from \"zustand\";\nimport { ContentPartRuntime } from \"../../api\";\nimport { ContentPartState } from \"../../api/ContentPartRuntime\";\n\nexport type ContentPartContextValue = {\n useContentPartRuntime: UseBoundStore<ReadonlyStore<ContentPartRuntime>>;\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 function useContentPartRuntime(options?: {\n optional?: false | undefined;\n}): ContentPartRuntime;\nexport function useContentPartRuntime(options?: {\n optional?: boolean | undefined;\n}): ContentPartRuntime | null;\nexport function useContentPartRuntime(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useContentPartContext(options);\n if (!context) return null;\n return context.useContentPartRuntime();\n}\n\nexport const { useContentPart, useContentPartStore } = createContextStoreHook(\n useContentPartContext,\n \"useContentPart\",\n);\n","import {\n ThreadAssistantContentPart,\n ThreadUserContentPart,\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../types/AssistantTypes\";\nimport { ThreadRuntimeCoreBinding } from \"./ThreadRuntime\";\nimport { MessageStateBinding } from \"./MessageRuntime\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nexport type ContentPartState = (\n | ThreadUserContentPart\n | ThreadAssistantContentPart\n) & {\n /**\n * @deprecated You can directly access content part fields in the state. Replace `.part.type` with `.type` etc. This will be removed in 0.6.0.\n */\n part: ThreadUserContentPart | ThreadAssistantContentPart;\n status: ContentPartStatus | ToolCallContentPartStatus;\n};\n\ntype ContentPartSnapshotBinding = SubscribableWithState<ContentPartState>;\n\nexport class ContentPartRuntime {\n constructor(\n private contentBinding: ContentPartSnapshotBinding,\n private messageApi: MessageStateBinding,\n private threadApi: ThreadRuntimeCoreBinding,\n ) {}\n\n public getState() {\n return this.contentBinding.getState();\n }\n\n public addToolResult(result: any) {\n const message = this.messageApi.getState();\n if (!message) throw new Error(\"Message is not available\");\n\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Content part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\"Tried to add tool result to non-tool content part\");\n\n const toolName = state.toolName;\n const toolCallId = state.toolCallId;\n\n this.threadApi.getState().addToolResult({\n messageId: message.id,\n toolName,\n toolCallId,\n result,\n });\n }\n\n public subscribe(callback: () => void) {\n return this.contentBinding.subscribe(callback);\n }\n}\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { MessageUtilsState } from \"../stores/MessageUtils\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\nimport { MessageRuntime } from \"../../api\";\nimport { MessageState } from \"../../api/MessageRuntime\";\nimport { EditComposerState } from \"../../api/ComposerRuntime\";\n\nexport type MessageContextValue = {\n useMessageRuntime: UseBoundStore<ReadonlyStore<MessageRuntime>>;\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\nexport function useMessageRuntime(options?: {\n optional?: false | undefined;\n}): MessageRuntime;\nexport function useMessageRuntime(options?: {\n optional?: boolean | undefined;\n}): MessageRuntime | null;\nexport function useMessageRuntime(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useMessageContext(options);\n if (!context) return null;\n return context.useMessageRuntime();\n}\n\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, useMessageRuntime } from \"./MessageContext\";\nimport { useThreadContext, useThreadRuntime } from \"./ThreadContext\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { ComposerRuntime, ComposerState } from \"../../api/ComposerRuntime\";\n\nexport type ComposerContextValue = {\n useComposer: ReadonlyStore<ComposerState>;\n type: \"edit\" | \"new\";\n};\n\nexport const useComposerContext = (): ComposerContextValue => {\n const { useComposer: useThreadComposer } = useThreadContext();\n const { useEditComposer } = useMessageContext({ optional: true }) ?? {};\n return useMemo(\n () => ({\n useComposer: useEditComposer ?? useThreadComposer,\n type: useEditComposer ? (\"edit\" as const) : (\"new\" as const),\n }),\n [useEditComposer, useThreadComposer],\n );\n};\n\nexport const { useComposer, useComposerStore } = createContextStoreHook(\n useComposerContext,\n \"useComposer\",\n);\n\nexport function useComposerRuntime(options?: {\n optional?: false | undefined;\n}): ComposerRuntime;\nexport function useComposerRuntime(options?: {\n optional?: boolean | undefined;\n}): ComposerRuntime | null;\nexport function useComposerRuntime(options?: {\n optional?: boolean | undefined;\n}) {\n const messageRuntime = useMessageRuntime({ optional: true });\n const threadRuntime = useThreadRuntime(options);\n return messageRuntime\n ? messageRuntime.composer\n : (threadRuntime?.composer ?? null);\n}\n","import { useCallback } from \"react\";\nimport { useThreadViewportStore } from \"../context\";\nimport {\n useThreadComposerStore,\n useThreadRuntime,\n} from \"../context/react/ThreadContext\";\nimport { CreateAppendMessage } from \"../api/ThreadRuntime\";\n\nexport const useAppendMessage = () => {\n const threadRuntime = useThreadRuntime();\n const threadViewportStore = useThreadViewportStore();\n const threadComposerStore = useThreadComposerStore();\n\n const append = useCallback(\n (message: CreateAppendMessage) => {\n threadRuntime.append(message);\n\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n },\n [threadRuntime, threadViewportStore, threadComposerStore],\n );\n\n return append;\n};\n","import { useCallback } from \"react\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\nimport { useAssistantRuntime } from \"../context\";\n\n/**\n * @deprecated Use `useRuntimeActions().switchToNewThread()` instead. This will be removed in 0.6.0.\n */\nexport const useSwitchToNewThread = () => {\n const assistantRuntime = useAssistantRuntime();\n const threadComposerStore = useThreadComposerStore();\n const switchToNewThread = useCallback(() => {\n assistantRuntime.switchToNewThread();\n threadComposerStore.getState().focus();\n }, [assistantRuntime, threadComposerStore]);\n\n return switchToNewThread;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport {\n useAssistantRuntime,\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 assistantRuntime = useAssistantRuntime();\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 = assistantRuntime.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 }, [assistantRuntime, 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 { useAssistantRuntime } from \"../context\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const assistantRuntime = useAssistantRuntime();\n useEffect(() => {\n const config = {\n system: instruction,\n };\n return assistantRuntime.registerModelConfigProvider({\n getModelConfig: () => config,\n });\n }, [assistantRuntime, 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 StoreOrRuntime,\n} from \"./createCombinedStore\";\n\nexport const useCombinedStore = <T extends Array<unknown>, R>(\n stores: { [K in keyof T]: StoreOrRuntime<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\";\n\nexport type StoreOrRuntime<T> = {\n getState: () => T;\n subscribe: (callback: () => void) => Unsubscribe;\n};\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]: StoreOrRuntime<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 type {\n AppendMessage,\n TextContentPart,\n ThreadMessage,\n} from \"../types/AssistantTypes\";\n\nexport const getThreadMessageText = (\n message: ThreadMessage | AppendMessage,\n) => {\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 { useCallback } from \"react\";\nimport {\n useComposer,\n useComposerRuntime,\n} from \"../../context/react/ComposerContext\";\n\nexport const useActionBarEdit = () => {\n const composerRuntime = useComposerRuntime();\n const disabled = useComposer((c) => c.isEditing);\n\n const callback = useCallback(() => {\n composerRuntime.beginEdit();\n }, [composerRuntime]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport {\n useMessageRuntime,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport {\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 messageRuntime = useMessageRuntime();\n const threadComposerStore = useThreadComposerStore();\n const threadViewportStore = useThreadViewportStore();\n\n const disabled = useCombinedStore(\n [threadStore, messageStore],\n (t, m) => t.isRunning || t.isDisabled || m.role !== \"assistant\",\n );\n\n const callback = useCallback(() => {\n messageRuntime.reload();\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [messageRuntime, threadComposerStore, threadViewportStore]);\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 useMessageRuntime,\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context\";\n\nexport const useActionBarSpeak = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const messageRunime = useMessageRuntime();\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 utt = messageRunime.speak();\n messageUtilsStore.getState().addUtterance(utt);\n }, [messageRunime, 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 { useMessageRuntime, useMessageUtilsStore } from \"../../context\";\n\nexport const useActionBarFeedbackPositive = () => {\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({\n type: \"positive\",\n });\n messageUtilsStore.getState().setSubmittedFeedback(\"positive\");\n }, [messageUtilsStore, messageRuntime]);\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageRuntime, useMessageUtilsStore } from \"../../context\";\n\nexport const useActionBarFeedbackNegative = () => {\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({\n type: \"negative\",\n });\n messageUtilsStore.getState().setSubmittedFeedback(\"negative\");\n }, [messageUtilsStore, messageRuntime]);\n\n return callback;\n};\n","\"use client\";\nimport { useMessage } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerCount = () => {\n const branchCount = useMessage((s) => s.branchCount);\n return branchCount;\n};\n","import { useCallback } from \"react\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport { useEditComposerStore, useMessageStore } from \"../../context\";\nimport { useMessageRuntime } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerNext = () => {\n const messageRuntime = useMessageRuntime();\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) => c.isEditing || m.branchNumber >= m.branchCount,\n );\n\n const callback = useCallback(() => {\n messageRuntime.switchToBranch({ position: \"next\" });\n }, [messageRuntime]);\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 branchNumber = useMessage((s) => s.branchNumber);\n return branchNumber;\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposerStore,\n useMessageRuntime,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useBranchPickerPrevious = () => {\n const messageRuntime = useMessageRuntime();\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) => c.isEditing || m.branchNumber <= 1,\n );\n\n const callback = useCallback(() => {\n messageRuntime.switchToBranch({ position: \"previous\" });\n }, [messageRuntime]);\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 { ContentPartState } from \"../../api/ContentPartRuntime\";\nimport { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { UIContentPart } from \"../../types\";\n\nexport const useContentPartDisplay = () => {\n const display = useContentPart((c) => {\n if (c.type !== \"ui\")\n throw new Error(\n \"This component can only be used inside ui content parts.\",\n );\n\n return c as ContentPartState & UIContentPart;\n });\n\n return display;\n};\n","import { ContentPartState } from \"../../api/ContentPartRuntime\";\nimport { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { ImageContentPart } from \"../../types\";\n\nexport const useContentPartImage = () => {\n const image = useContentPart((c) => {\n if (c.type !== \"image\")\n throw new Error(\n \"ContentPartImage can only be used inside image content parts.\",\n );\n\n return c as ContentPartState & ImageContentPart;\n });\n\n return image;\n};\n","import { ContentPartState } from \"../../api/ContentPartRuntime\";\nimport { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { TextContentPart } from \"../../types\";\n\nexport const useContentPartText = () => {\n const text = useContentPart((c) => {\n if (c.type !== \"text\")\n throw new Error(\n \"ContentPartText can only be used inside text content parts.\",\n );\n\n return c as ContentPartState & TextContentPart;\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 { role, attachments, branchCount, isLast },\n { isCopied, isHovering, isSpeaking, submittedFeedback },\n ) => {\n if (props.hasBranches === true && branchCount < 2) return false;\n\n if (props.user && role !== \"user\") return false;\n if (props.assistant && role !== \"assistant\") return false;\n if (props.system && 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 (role !== \"user\" || !attachments.length)\n )\n return false;\n if (\n props.hasAttachments === false &&\n role === \"user\" &&\n !!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 { useThread } from \"../../context\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\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 return useThread((thread) => {\n if (props.empty === true && thread.messages.length !== 0) return false;\n if (props.empty === false && thread.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","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, useMemo } from \"react\";\nimport { useContentPart, useThreadRuntime, useToolUIs } from \"../../context\";\nimport {\n useMessage,\n useMessageRuntime,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport { ContentPartRuntimeProvider } from \"../../context/providers/ContentPartRuntimeProvider\";\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\";\nimport { EMPTY_CONTENT } from \"../../api/MessageRuntime\";\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.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 threadRuntime = useThreadRuntime();\n\n const part = useContentPart();\n\n const type = part.type;\n switch (type) {\n case \"text\":\n if (part.status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n if (part.part === EMPTY_CONTENT && !!Empty) {\n return <Empty status={part.status} />;\n }\n\n return <Text {...part} part={part} />;\n\n case \"image\":\n if (part.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={part} />;\n\n case \"ui\":\n if (part.status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n return <UI {...part} part={part} />;\n\n case \"tool-call\": {\n const Tool = by_name[part.toolName] || Fallback;\n const addResult = (result: any) =>\n threadRuntime.addToolResult({\n messageId: messageStore.getState().id,\n toolName: part.toolName,\n toolCallId: part.toolCallId,\n result,\n });\n return (\n <ToolUIDisplay {...part} part={part} UI={Tool} addResult={addResult} />\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 const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.unstable_getContentPartByIndex(partIndex),\n [messageRuntime, partIndex],\n );\n\n return (\n <ContentPartRuntimeProvider runtime={runtime}>\n <MessageContentPartComponent components={components} />\n </ContentPartRuntimeProvider>\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.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 { writableStore } from \"../ReadonlyStore\";\nimport { ContentPartRuntime } from \"../../api\";\n\ntype ContentPartProviderProps = PropsWithChildren<{\n runtime: ContentPartRuntime;\n}>;\n\nconst useContentPartRuntimeStore = (runtime: ContentPartRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const useContentPartStore = (runtime: ContentPartRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const ContentPartRuntimeProvider: FC<ContentPartProviderProps> = ({\n runtime,\n children,\n}) => {\n const useContentPartRuntime = useContentPartRuntimeStore(runtime);\n const useContentPart = useContentPartStore(runtime);\n const [context] = useState<ContentPartContextValue>(() => {\n return { useContentPartRuntime, useContentPart };\n });\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 { text, status } = 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","\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useMessage } from \"../../context\";\nimport { ContentPartStatus, TextContentPart } from \"../../types/AssistantTypes\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useSmoothStatusStore } from \"./SmoothContext\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\nimport { ContentPartState } from \"../../api/ContentPartRuntime\";\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: ContentPartState & TextContentPart,\n smooth: boolean = false,\n): ContentPartState & TextContentPart => {\n const { text } = state;\n const id = useMessage({\n optional: true,\n selector: (m: { id: string }) => m.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.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.text ? SMOOTH_STATUS : state.status,\n );\n }\n }, [smoothStatusStore, text, displayedText, state.status, state.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 type: \"text\",\n text: displayedText,\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 ComponentType,\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 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","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 { image } = 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 { display } = 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","import { ThreadComposerAttachment } from \"../context/stores/Attachment\";\nimport { ComposerRuntimeCore } from \"../runtimes/core/ComposerRuntimeCore\";\nimport { Unsubscribe } from \"../types\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nexport type ThreadComposerRuntimeCoreBinding = SubscribableWithState<\n ComposerRuntimeCore | undefined\n>;\n\ntype LegacyEditComposerState = Readonly<{\n type: \"edit\" | \"thread\";\n\n /** @deprecated Use `text` instead. This will be removed in 0.6.0. */\n value: string;\n /** @deprecated Use `useComposerRuntime().setText()` instead. This will be removed in 0.6.0. */\n setValue: (value: string) => void;\n\n text: string;\n /**\n * @deprecated Use `useComposerRuntime().setText()` instead. This will be removed in 0.6.0.\n */\n setText: (value: string) => void;\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n\n /**\n * @deprecated Use useComposerRuntime().beginEdit() instead. This will be removed in 0.6.0.\n */\n edit: () => void;\n /**\n * @deprecated Use `useComposerRuntime().send()` instead. This will be removed in 0.6.0.\n */\n send: () => void;\n /**\n * @deprecated Use `useComposerRuntime().cancel()` instead. This will be removed in 0.6.0.\n */\n cancel: () => void;\n}>;\n\ntype LegacyThreadComposerState = Readonly<{\n type: \"thread\" | \"edit\";\n\n /** @deprecated Use `text` instead. This will be removed in 0.6.0. */\n value: string;\n /** @deprecated Use `useComposerRuntime().setText` instead. This will be removed in 0.6.0. */\n setValue: (value: string) => void;\n\n attachmentAccept: string;\n attachments: readonly ThreadComposerAttachment[];\n\n /** @deprecated Use `useComposerRuntime().addAttachment` instead. This will be removed in 0.6.0. */\n addAttachment: (file: File) => void;\n /** @deprecated Use `useComposerRuntime().removeAttachment` instead. This will be removed in 0.6.0. */\n removeAttachment: (attachmentId: string) => void;\n\n text: string;\n /** @deprecated Use `useComposerRuntime().setText` instead. This will be removed in 0.6.0. */\n setText: (value: string) => void;\n\n /** @deprecated Use `useComposerRuntime().reset` instead. This will be removed in 0.6.0. */\n reset: () => void;\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n\n /**\n * @deprecated Use `useComposerRuntime().send` instead. This will be removed in 0.6.0.\n **/\n send: () => void;\n /** @deprecated Use `useComposerRuntime().cancel` instead. This will be removed in 0.6.0. */\n cancel: () => void;\n\n // TODO replace with events\n /** @deprecated This feature is being removed in 0.6.0. Submit feedback if you need it. */\n focus: () => void;\n /** @deprecated This feature is being removed in 0.6.0. Submit feedback if you need it. */\n onFocus: (listener: () => void) => Unsubscribe;\n}>;\n\nexport type ComposerState = LegacyThreadComposerState &\n LegacyEditComposerState &\n Readonly<{\n type: \"thread\" | \"edit\";\n\n text: string;\n\n attachmentAccept: string;\n attachments: readonly ThreadComposerAttachment[];\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n }>;\n\n/** @deprecated Use `ComposerState` instead. */\nexport type ThreadComposerState = ComposerState;\n/** @deprecated Use `ComposerState` instead. */\nexport type EditComposerState = ComposerState;\n\nconst METHOD_NOT_SUPPORTED = () => {\n throw new Error(\"Composer is not available\");\n};\nconst EMPTY_ARRAY = Object.freeze([]);\nconst getThreadComposerState = (\n type: \"edit\" | \"thread\",\n runtime: ComposerRuntimeCore | undefined,\n beginEdit: () => void,\n focus?: () => void,\n onFocus?: (listener: () => void) => Unsubscribe,\n): ComposerState => {\n return Object.freeze({\n type,\n\n isEditing: runtime?.isEditing ?? false,\n canCancel: runtime?.canCancel ?? false,\n isEmpty: runtime?.isEmpty ?? true,\n text: runtime?.text ?? \"\",\n attachments: runtime?.attachments ?? EMPTY_ARRAY,\n attachmentAccept: runtime?.attachmentAccept ?? \"*\",\n\n value: runtime?.text ?? \"\",\n setValue: runtime?.setText.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n setText: runtime?.setText.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n edit: beginEdit,\n send: runtime?.send.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n cancel: runtime?.cancel.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n focus: focus ?? METHOD_NOT_SUPPORTED,\n onFocus: onFocus ?? METHOD_NOT_SUPPORTED,\n reset: runtime?.reset.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n\n addAttachment: runtime?.addAttachment.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n removeAttachment:\n runtime?.removeAttachment.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n });\n};\n\nexport class ComposerRuntime implements ComposerRuntimeCore {\n public get type() {\n return this._beginEdit ? \"edit\" : \"thread\";\n }\n\n constructor(\n private _core: ThreadComposerRuntimeCoreBinding,\n private _beginEdit?: () => void,\n ) {}\n\n /**\n * @deprecated Use `getState().isEditing` instead. This will be removed in 0.6.0.\n */\n public get isEditing() {\n return this.getState().isEditing;\n }\n\n /**\n * @deprecated Use `getState().isEmpty` instead. This will be removed in 0.6.0.\n */\n public get isEmpty() {\n return this.getState().isEmpty;\n }\n\n /**\n * @deprecated Use `getState().canCancel` instead. This will be removed in 0.6.0.\n */\n public get canCancel() {\n return this.getState().canCancel;\n }\n\n /**\n * @deprecated Use `getState().text` instead. This will be removed in 0.6.0.\n */\n public get text() {\n return this.getState().text;\n }\n\n /**\n * @deprecated Use `getState().attachmentAccept` instead. This will be removed in 0.6.0.\n */\n public get attachmentAccept() {\n return this.getState().attachmentAccept;\n }\n\n // TODO should this instead return getAttachmentByIndex([idx]) instead?\n /**\n * @deprecated Use `getState().attachments` instead. This will be removed in 0.6.0.\n */\n public get attachments() {\n return this.getState().attachments;\n }\n\n /**\n * @deprecated Use `getState().text` instead. This will be removed in 0.6.0.\n */\n public get value() {\n return this.text;\n }\n\n public getState() {\n return getThreadComposerState(\n this.type,\n this._core.getState(),\n this._beginEdit?.bind(this) ?? METHOD_NOT_SUPPORTED,\n this.focus.bind(this),\n this.onFocus.bind(this),\n );\n }\n\n public setText(text: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setText(text);\n }\n\n public setValue(text: string) {\n this.setText(text);\n }\n\n public addAttachment(file: File) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.addAttachment(file);\n }\n\n // /**\n // * @deprecated Use `getAttachmentById(id).removeAttachment` instead. This will be removed in 0.6.0.\n // */\n public removeAttachment(attachmentId: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.removeAttachment(attachmentId);\n }\n\n /**\n * @deprecated This method will be removed in 0.6.0. Submit feedback if you need this functionality.\n */\n public reset() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.reset();\n }\n\n public send() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.send();\n }\n\n public cancel() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.cancel();\n }\n\n public beginEdit() {\n this._beginEdit?.();\n }\n\n /**\n * @deprecated Use `beginEdit()` instead. This will be removed in 0.6.0.\n */\n public edit() {\n this.beginEdit();\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n private _focusListeners = new Set<() => void>();\n\n private focus() {\n this._focusListeners.forEach((callback) => callback());\n }\n\n private onFocus(callback: () => void) {\n this._focusListeners.add(callback);\n return () => this._focusListeners.delete(callback);\n }\n}\n","import { Unsubscribe } from \"../../types/Unsubscribe\";\n\nexport abstract class BaseSubject {\n private _subscriptions = new Set<() => void>();\n private _connection: Unsubscribe | undefined;\n\n protected get isConnected() {\n return !!this._connection;\n }\n\n protected abstract _connect(): Unsubscribe;\n\n protected notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n private _updateConnection() {\n if (this._subscriptions.size > 0) {\n if (this._connection) return;\n this._connection = this._connect();\n } else {\n this._connection?.();\n this._connection = undefined;\n }\n }\n\n public subscribe(callback: () => void) {\n this._subscriptions.add(callback);\n this._updateConnection();\n\n return () => {\n this._subscriptions.delete(callback);\n this._updateConnection();\n };\n }\n}\n","import { Unsubscribe } from \"../../types\";\nimport { BaseSubject } from \"./BaseSubject\";\nimport {\n NestedSubscribable,\n Subscribable,\n SubscribableWithState,\n} from \"./Subscribable\";\n\nexport class NestedSubscriptionSubject<TState extends Subscribable | undefined>\n extends BaseSubject\n implements SubscribableWithState<TState>, NestedSubscribable<TState>\n{\n constructor(private binding: NestedSubscribable<TState>) {\n super();\n }\n\n public getState() {\n return this.binding.getState();\n }\n\n protected _connect(): Unsubscribe {\n const callback = () => {\n this.notifySubscribers();\n };\n\n let lastState = this.binding.getState();\n let innerUnsubscribe = lastState?.subscribe(callback);\n const onRuntimeUpdate = () => {\n const newState = this.binding.getState();\n if (newState === lastState) return;\n lastState = newState;\n\n innerUnsubscribe?.();\n innerUnsubscribe = this.binding.getState()?.subscribe(callback);\n\n callback();\n };\n\n const outerUnsubscribe = this.binding.subscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n","export function shallowEqual<T extends object>(\n objA: T | undefined,\n objB: T | undefined,\n) {\n if (objA === undefined && objB === undefined) return true;\n if (objA === undefined) return false;\n if (objB === undefined) return false;\n\n for (const key of Object.keys(objA)) {\n const valueA = objA[key as keyof T];\n const valueB = objB[key as keyof T];\n if (!Object.is(valueA, valueB)) return false;\n }\n\n return true;\n}\n","import { shallowEqual } from \"./shallowEqual\";\nimport { BaseSubject } from \"./BaseSubject\";\nimport { SubscribableWithState } from \"./Subscribable\";\n\nexport class ShallowMemoizeSubject<T extends object>\n extends BaseSubject\n implements SubscribableWithState<T>\n{\n constructor(private binding: SubscribableWithState<T | undefined>) {\n super();\n const state = binding.getState();\n if (state === undefined)\n throw new Error(\"Entry not available in the store\");\n this._previousState = state;\n }\n\n private _previousState: T;\n public getState = () => {\n if (!this.isConnected) this._syncState();\n return this._previousState;\n };\n\n private _syncState() {\n const state = this.binding.getState();\n if (state === undefined) return false;\n if (shallowEqual(state, this._previousState)) return false;\n this._previousState = state;\n return true;\n }\n\n protected _connect() {\n const callback = () => {\n if (this._syncState()) {\n this.notifySubscribers();\n }\n };\n\n return this.binding.subscribe(callback);\n }\n}\n","import {\n ThreadMessage,\n AppendMessage,\n ThreadAssistantContentPart,\n ThreadUserContentPart,\n} from \"../types\";\nimport {\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../types/AssistantTypes\";\nimport { ComposerRuntime } from \"./ComposerRuntime\";\nimport { ContentPartRuntime, ContentPartState } from \"./ContentPartRuntime\";\nimport { ThreadRuntimeCoreBinding } from \"./ThreadRuntime\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nconst COMPLETE_STATUS: ContentPartStatus = {\n type: \"complete\",\n};\n\nexport const 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 partIndex: number,\n): ContentPartState | undefined => {\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 undefined;\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 return Object.freeze({ ...part, part, status });\n};\n\nexport type MessageState = ThreadMessage & {\n /**\n * @deprecated You can directly access message fields in the state. Replace `.message.content` with `.content` etc. This will be removed in 0.6.0.\n */\n message: ThreadMessage;\n parentId: string | null;\n isLast: boolean;\n /**\n * @deprecated Use `branchNumber` and `branchCount` instead. This will be removed in 0.6.0.\n */\n branches: readonly string[];\n\n branchNumber: number;\n branchCount: number;\n};\n\nexport type MessageStateBinding = SubscribableWithState<MessageState>;\n\nexport class MessageRuntime {\n constructor(\n private _core: MessageStateBinding,\n private _threadBinding: ThreadRuntimeCoreBinding,\n ) {}\n\n public composer = new ComposerRuntime(\n new NestedSubscriptionSubject({\n getState: () =>\n this._threadBinding\n .getState()\n .getEditComposer(this._core.getState().id),\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n () => this._threadBinding.getState().beginEdit(this._core.getState().id),\n ) as ComposerRuntime & { type: \"edit\" };\n\n public getState() {\n return this._core.getState();\n }\n\n // TODO improve type\n public unstable_edit(message: Omit<AppendMessage, \"parentId\">) {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n this._threadBinding.getState().append({\n ...(message as AppendMessage),\n parentId: state.parentId,\n });\n }\n\n public reload() {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n if (state.role !== \"assistant\")\n throw new Error(\"Can only reload assistant messages\");\n\n this._threadBinding.getState().startRun(state.parentId);\n }\n\n public speak() {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n return this._threadBinding.getState().speak(state.id);\n }\n\n public submitFeedback({ type }: { type: \"positive\" | \"negative\" }) {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n this._threadBinding.getState().submitFeedback({\n messageId: state.id,\n type,\n });\n }\n\n public switchToBranch({\n position,\n branchId,\n }: {\n position?: \"previous\" | \"next\" | undefined;\n branchId?: string | undefined;\n }) {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n if (branchId && position) {\n throw new Error(\"May not specify both branchId and position\");\n } else if (!branchId && !position) {\n throw new Error(\"Must specify either branchId or position\");\n }\n\n const thread = this._threadBinding.getState();\n const branches = thread.getBranches(state.id);\n let targetBranch = branchId;\n if (position === \"previous\") {\n targetBranch = branches[state.branchNumber - 2];\n } else if (position === \"next\") {\n targetBranch = branches[state.branchNumber];\n }\n if (!targetBranch) throw new Error(\"Branch not found\");\n\n this._threadBinding.getState().switchToBranch(targetBranch);\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n public unstable_getContentPartByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n return new ContentPartRuntime(\n new ShallowMemoizeSubject({\n getState: () => {\n return getContentPartState(this.getState(), idx);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n this._threadBinding,\n );\n }\n}\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 { useMessageStore } from \"../react\";\nimport { MessageAttachmentState } from \"../stores/Attachment\";\nimport {\n AttachmentContext,\n AttachmentContextValue,\n} from \"../react/AttachmentContext\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport { MessageState } from \"../../api\";\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 submitOnEnter?: boolean | undefined;\n cancelOnEscape?: 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 submitOnEnter = true,\n cancelOnEscape = true,\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 if (!cancelOnEscape) return;\n \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 || !submitOnEnter) 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 { ComposerAttachmentState } from \"../stores/Attachment\";\nimport {\n AttachmentContext,\n AttachmentContextValue,\n} from \"../react/AttachmentContext\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport { useThreadComposerStore } from \"../react/ThreadContext\";\nimport { ComposerState } from \"../../api/ComposerRuntime\";\n\ntype ComposerAttachmentProviderProps = PropsWithChildren<{\n attachmentIndex: number;\n}>;\n\nconst getAttachment = (\n { attachments }: ComposerState,\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: ComposerState) => {\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, useMemo } from \"react\";\nimport { useThread, useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { MessageRuntimeProvider } from \"../../context/providers/MessageRuntimeProvider\";\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.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 const threadRuntime = useThreadRuntime();\n const runtime = useMemo(\n () => threadRuntime.unstable_getMesssageByIndex(messageIndex),\n [threadRuntime, messageIndex],\n );\n\n return (\n <MessageRuntimeProvider runtime={runtime}>\n <ThreadMessageComponent components={components} />\n </MessageRuntimeProvider>\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 = useThread((t) => t.messages.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 { MessageContext } from \"../react/MessageContext\";\nimport type { MessageContextValue } from \"../react/MessageContext\";\nimport { makeMessageUtilsStore } from \"../stores/MessageUtils\";\nimport { ReadonlyStore, writableStore } from \"../ReadonlyStore\";\nimport { MessageRuntime } from \"../../api\";\n\ntype MessageProviderProps = PropsWithChildren<{\n runtime: MessageRuntime;\n}>;\n\nconst useMessageRuntimeStore = (runtime: MessageRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useMessageStore = (runtime: MessageRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useMessageUtilsStore = () => {\n const [store] = useState(() => makeMessageUtilsStore());\n return store;\n};\n\nconst useEditComposerStore = (\n useMessageRuntime: ReadonlyStore<MessageRuntime>,\n) => {\n const runtime = useMessageRuntime.getState().composer;\n const [store] = useState(() => create(() => runtime.getState()));\n\n useEffect(() => {\n const updateState = () => writableStore(store).setState(runtime.getState());\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const MessageRuntimeProvider: FC<MessageProviderProps> = ({\n runtime,\n children,\n}) => {\n const useMessageRuntime = useMessageRuntimeStore(runtime);\n const useMessage = useMessageStore(runtime);\n const useMessageUtils = useMessageUtilsStore();\n const useEditComposer = useEditComposerStore(useMessageRuntime);\n const [context] = useState<MessageContextValue>(() => {\n return { useMessageRuntime, useMessage, useMessageUtils, useEditComposer };\n });\n\n return (\n <MessageContext.Provider value={context}>\n {children}\n </MessageContext.Provider>\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","import { Unsubscribe } from \"../../types\";\nimport { AssistantRuntimeCore } from \"./AssistantRuntimeCore\";\n\n/**\n * @deprecated Use `runtime.thread.subscribe` instead. This will be removed in 0.6.0.\n */\nexport const subscribeToMainThread = (\n runtime: AssistantRuntimeCore,\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, useMemo, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntimeCore } from \"./LocalRuntimeCore\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\nimport { ThreadRuntime } from \"../../api/ThreadRuntime\";\n\nexport class LocalRuntime extends AssistantRuntime {\n constructor(private core: LocalRuntimeCore) {\n super(core, ThreadRuntime);\n }\n\n public reset(options?: Parameters<LocalRuntimeCore[\"reset\"]>[0]) {\n this.core.reset(options);\n }\n}\n\nexport const useLocalRuntime = (\n adapter: ChatModelAdapter,\n options: LocalRuntimeOptions = {},\n) => {\n const [runtime] = useState(() => new LocalRuntimeCore(adapter, options));\n\n useInsertionEffect(() => {\n runtime.thread.adapter = adapter;\n runtime.thread.options = options;\n });\n\n return useMemo(() => new LocalRuntime(runtime), [runtime]);\n};\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport type { AssistantRuntimeCore } from \"./AssistantRuntimeCore\";\nimport { ReactThreadRuntimeCore } from \"./ReactThreadRuntimeCore\";\n\nexport abstract class BaseAssistantRuntimeCore<\n TThreadRuntime extends ReactThreadRuntimeCore,\n> implements AssistantRuntimeCore\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 type { ReactThreadRuntimeCore } from \"./runtimes/core/ReactThreadRuntimeCore\";\nexport { DefaultThreadComposerRuntimeCore } from \"./runtimes/composer/DefaultThreadComposerRuntimeCore\";\nexport { ProxyConfigProvider } from \"./utils/ProxyConfigProvider\";\nexport { MessageRepository } from \"./runtimes/utils/MessageRepository\";\nexport { BaseAssistantRuntimeCore } from \"./runtimes/core/BaseAssistantRuntimeCore\";\nexport * from \"./utils/smooth\";\nexport { TooltipIconButton } from \"./ui/base/tooltip-icon-button\";\nexport { generateId } from \"./utils/idUtils\";\nexport { AssistantRuntime } from \"./api/AssistantRuntime\";\nexport {\n ThreadRuntime,\n type ThreadRuntimeCoreBinding,\n} from \"./api/ThreadRuntime\";\n","import { ThreadComposerAttachment } from \"../../context/stores/Attachment\";\nimport { AppendMessage, Unsubscribe } from \"../../types\";\nimport { AttachmentAdapter } from \"../attachment\";\nimport { ComposerRuntimeCore } from \"../core/ComposerRuntimeCore\";\n\nexport abstract class BaseComposerRuntimeCore implements ComposerRuntimeCore {\n public readonly isEditing = true;\n\n public attachmentAccept: string = \"*\";\n\n private _attachments: readonly ThreadComposerAttachment[] = [];\n protected set attachments(value: readonly ThreadComposerAttachment[]) {\n this._attachments = value;\n this.notifySubscribers();\n }\n public get attachments() {\n return this._attachments;\n }\n\n public abstract get canCancel(): boolean;\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\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 const message: Omit<AppendMessage, \"parentId\"> = {\n role: \"user\",\n content: this.text ? [{ type: \"text\", text: this.text }] : [],\n attachments,\n };\n this.reset();\n\n this.handleSend(message);\n }\n public abstract handleSend(message: Omit<AppendMessage, \"parentId\">): void;\n public abstract cancel(): void;\n\n protected _attachmentAdapter?: AttachmentAdapter | undefined;\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 this.notifySubscribers();\n }\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 _subscriptions = new Set<() => void>();\n protected 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","import { AppendMessage } from \"../../types\";\nimport { ThreadRuntimeCore } from \"../core/ThreadRuntimeCore\";\nimport { BaseComposerRuntimeCore } from \"./BaseComposerRuntimeCore\";\n\nexport class DefaultThreadComposerRuntimeCore extends BaseComposerRuntimeCore {\n private _canCancel = false;\n public get canCancel() {\n return this._canCancel;\n }\n\n constructor(private runtime: Omit<ThreadRuntimeCore, \"composer\">) {\n super();\n this.connect();\n }\n\n public connect() {\n return this.runtime.subscribe(() => {\n if (this.canCancel !== this.runtime.capabilities.cancel) {\n this._canCancel = this.runtime.capabilities.cancel;\n this.notifySubscribers();\n }\n });\n }\n\n public async handleSend(message: Omit<AppendMessage, \"parentId\">) {\n this.runtime.append({\n ...(message as AppendMessage),\n parentId: this.runtime.messages.at(-1)?.id ?? null,\n });\n }\n\n public async cancel() {\n this.runtime.cancelRun();\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 { 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 { AssistantRuntimeCore } from \"../runtimes/core/AssistantRuntimeCore\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ModelConfigProvider } from \"../types/ModelConfigTypes\";\nimport { ThreadRuntime, ThreadRuntimeCoreBinding } from \"./ThreadRuntime\";\n\nexport class AssistantRuntime<\n TThreadRuntime extends ThreadRuntime = ThreadRuntime,\n> implements AssistantRuntimeCore\n{\n constructor(\n private _core: AssistantRuntimeCore,\n CustomThreadRuntime: new (\n binding: ThreadRuntimeCoreBinding,\n ) => TThreadRuntime,\n ) {\n this.thread = new CustomThreadRuntime(\n new NestedSubscriptionSubject({\n getState: () => this._core.thread,\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n );\n }\n\n public readonly thread;\n\n public switchToNewThread() {\n return this._core.switchToNewThread();\n }\n\n public switchToThread(threadId: string): void;\n /**\n * @deprecated Use `switchToNewThread` instead. This will be removed in 0.6.0.\n */\n public switchToThread(threadId: string | null): void;\n public switchToThread(threadId: string | null) {\n return this._core.switchToThread(threadId);\n }\n\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._core.registerModelConfigProvider(provider);\n }\n\n // TODO events for thread switching\n /**\n * @deprecated Thread is now static and never gets updated. This will be removed in 0.6.0.\n */\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n}\n","import { BaseSubject } from \"./BaseSubject\";\nimport { SubscribableWithState } from \"./Subscribable\";\n\nexport class LazyMemoizeSubject<T extends object>\n extends BaseSubject\n implements SubscribableWithState<T>\n{\n constructor(private binding: SubscribableWithState<T | undefined>) {\n super();\n const state = binding.getState();\n if (state === undefined)\n throw new Error(\"Entry not available in the store\");\n this._previousState = state;\n }\n\n private _previousStateDirty = true;\n private _previousState: T;\n public getState = () => {\n if (!this.isConnected || this._previousStateDirty) {\n const newState = this.binding.getState();\n if (newState !== undefined) {\n this._previousState = newState;\n }\n this._previousStateDirty = false;\n }\n return this._previousState;\n };\n\n protected _connect() {\n const callback = () => {\n this._previousStateDirty = true;\n this.notifySubscribers();\n };\n\n return this.binding.subscribe(callback);\n }\n}\n","import { ComponentType } from \"react\";\nimport { ReactThreadRuntimeCore } from \"../runtimes/core/ReactThreadRuntimeCore\";\nimport {\n AddToolResultOptions,\n RuntimeCapabilities,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n} from \"../runtimes/core/ThreadRuntimeCore\";\nimport { ExportedMessageRepository } from \"../runtimes/utils/MessageRepository\";\nimport { AppendMessage, ThreadMessage } from \"../types\";\nimport { MessageRuntime, MessageState } from \"./MessageRuntime\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\nimport { ComposerRuntime } from \"./ComposerRuntime\";\nimport { LazyMemoizeSubject } from \"./subscribable/LazyMemoizeSubject\";\n\nexport type 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 messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n parentId: messages.at(-1)?.id ?? null,\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n };\n }\n\n if (message.role && message.parentId && message.attachments) {\n return message as AppendMessage;\n }\n\n return {\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<ThreadRuntimeCore>;\n\nexport type ThreadState = Readonly<{\n threadId: string;\n isDisabled: boolean;\n isRunning: boolean;\n capabilities: RuntimeCapabilities;\n messages: readonly ThreadMessage[];\n}>;\n\nexport type ReactThreadState = ThreadState & {\n readonly unstable_synchronizer?: ComponentType | undefined;\n};\n\nexport const getThreadState = (runtime: ThreadRuntimeCore): 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 messages: runtime.messages,\n unstable_synchronizer: (runtime as ReactThreadRuntimeCore)\n .unstable_synchronizer,\n });\n};\n\nexport class ThreadRuntime implements ThreadRuntimeCore {\n // public path = \"assistant.threads[main]\"; // TODO\n\n /**\n * @deprecated Use `getState().threadId` instead. This will be removed in 0.6.0.\n */\n public get threadId() {\n return this.getState().threadId;\n }\n\n /**\n * @deprecated Use `getState().isDisabled` instead. This will be removed in 0.6.0.\n */\n public get isDisabled() {\n return this.getState().isDisabled;\n }\n\n /**\n * @deprecated Use `getState().isRunning` instead. This will be removed in 0.6.0.\n */\n public get isRunning() {\n return this.getState().isRunning;\n }\n\n /**\n * @deprecated Use `getState().capabilities` instead. This will be removed in 0.6.0.\n */\n public get capabilities() {\n return this.getState().capabilities;\n }\n\n /**\n * @deprecated Use `getState().messages` instead. This will be removed in 0.6.0.\n */\n public get messages() {\n return this._threadBinding.getState().messages;\n }\n\n public unstable_getCore() {\n return this._threadBinding.getState();\n }\n\n private _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n constructor(threadBinding: ThreadRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n getState: () => getThreadState(threadBinding.getState()),\n subscribe: (callback) => threadBinding.subscribe(callback),\n });\n\n this._threadBinding = {\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n }\n\n public readonly composer = new ComposerRuntime(\n new NestedSubscriptionSubject({\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n }\n\n public subscribe(callback: () => void) {\n return this._threadBinding.subscribe(callback);\n }\n\n // /**\n // * @derprecated Use `getMesssageById(id).getState().branchNumber` / `getMesssageById(id).getState().branchCount` instead. This will be removed in 0.6.0.\n // */\n public getBranches(messageId: string) {\n return this._threadBinding.getState().getBranches(messageId);\n }\n\n public getModelConfig() {\n return this._threadBinding.getState().getModelConfig();\n }\n\n // TODO sometimes you want to continue when there is no child message\n public startRun(parentId: string | null) {\n return this._threadBinding.getState().startRun(parentId);\n }\n\n // TODO\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n // /**\n // * @deprecated Use `getMesssageById(id).getContentPartByToolCallId(toolCallId).addToolResult({ result })` instead. This will be removed in 0.6.0.\n // */\n public addToolResult(options: AddToolResultOptions) {\n this._threadBinding.getState().addToolResult(options);\n }\n\n // TODO\n public switchToBranch(branchId: string) {\n return this._threadBinding.getState().switchToBranch(branchId);\n }\n\n // /**\n // * @deprecated Use `getMesssageById(id).speak()` instead. This will be removed in 0.6.0.\n // */\n public speak(messageId: string) {\n return this._threadBinding.getState().speak(messageId);\n }\n\n // /**\n // * @deprecated Use `getMesssageById(id).submitFeedback({ type })` instead. This will be removed in 0.6.0.\n // */\n public submitFeedback(options: SubmitFeedbackOptions) {\n return this._threadBinding.getState().submitFeedback(options);\n }\n\n /**\n * @deprecated This is a temporary API. This will be removed in 0.6.0.\n */\n public getEditComposer(messageId: string) {\n return this._threadBinding.getState().getEditComposer(messageId);\n }\n\n /**\n * @deprecated This is a temporary API. This will be removed in 0.6.0.\n */\n public beginEdit(messageId: string) {\n return this._threadBinding.getState().beginEdit(messageId);\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public unstable_getMesssageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return new MessageRuntime(\n new ShallowMemoizeSubject({\n getState: () => {\n const messages = this.messages;\n const message = messages[idx];\n if (!message) return undefined;\n\n const branches = this._threadBinding\n .getState()\n .getBranches(message.id);\n\n return {\n ...message,\n\n message,\n isLast: idx === messages.length - 1,\n parentId: messages[idx - 1]?.id ?? null,\n\n branches,\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n}\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 { AppendMessage, ThreadMessage } from \"../../types\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { ThreadRuntimeCore } from \"../core/ThreadRuntimeCore\";\nimport { BaseComposerRuntimeCore } from \"./BaseComposerRuntimeCore\";\n\nexport class DefaultEditComposerRuntimeCore extends BaseComposerRuntimeCore {\n public get canCancel() {\n return true;\n }\n\n private _nonTextParts;\n private _previousText;\n private _parentId;\n constructor(\n private runtime: Omit<ThreadRuntimeCore, \"composer\">,\n private endEditCallback: () => void,\n { parentId, message }: { parentId: string | null; message: ThreadMessage },\n ) {\n super();\n this._parentId = parentId;\n this._previousText = getThreadMessageText(message);\n this.setText(this._previousText);\n\n this._nonTextParts = message.content.filter(\n (part) => part.type !== \"text\" && part.type !== \"ui\",\n );\n\n // TODO differentiate between \"sent\" and \"pending\" attachments instead of Composer/Message Attachments\n // this.attachments = message.attachments ?? [];\n }\n\n public async handleSend(message: Omit<AppendMessage, \"parentId\">) {\n const text = getThreadMessageText(message as AppendMessage);\n if (text !== this._previousText) {\n this.runtime.append({\n ...(message as AppendMessage),\n content: [...message.content, ...this._nonTextParts] as any,\n parentId: this._parentId,\n });\n }\n\n this.endEditCallback();\n this.notifySubscribers();\n }\n\n public async cancel() {\n this.endEditCallback();\n this.notifySubscribers();\n }\n}\n","import { 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 { DefaultThreadComposerRuntimeCore } from \"../composer/DefaultThreadComposerRuntimeCore\";\nimport { shouldContinue } from \"./shouldContinue\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { SpeechSynthesisAdapter } from \"../speech\";\nimport {\n AddToolResultOptions,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n} from \"../core/ThreadRuntimeCore\";\nimport { DefaultEditComposerRuntimeCore } from \"../composer/DefaultEditComposerRuntimeCore\";\n\nexport class LocalThreadRuntimeCore implements ThreadRuntimeCore {\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 DefaultThreadComposerRuntimeCore(this);\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 private _editComposers = new Map<string, DefaultEditComposerRuntimeCore>();\n public getEditComposer(messageId: string) {\n return this._editComposers.get(messageId);\n }\n public beginEdit(messageId: string) {\n if (this._editComposers.has(messageId))\n throw new Error(\"Edit already in progress\");\n\n this._editComposers.set(\n messageId,\n new DefaultEditComposerRuntimeCore(\n this,\n () => this._editComposers.delete(messageId),\n this.repository.getMessage(messageId),\n ),\n );\n 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 { BaseAssistantRuntimeCore } from \"../core/BaseAssistantRuntimeCore\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { ProxyConfigProvider } from \"../../internal\";\nimport { LocalThreadRuntimeCore } from \"./LocalThreadRuntimeCore\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { fromCoreMessages } from \"../edge/converters/fromCoreMessage\";\n\nexport class LocalRuntimeCore extends BaseAssistantRuntimeCore<LocalThreadRuntimeCore> {\n private readonly _proxyConfigProvider: ProxyConfigProvider;\n\n constructor(adapter: ChatModelAdapter, options: LocalRuntimeOptions) {\n const proxyConfigProvider = new ProxyConfigProvider();\n super(new LocalThreadRuntimeCore(proxyConfigProvider, adapter, options));\n this._proxyConfigProvider = proxyConfigProvider;\n }\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n\n public switchToNewThread() {\n const { initialMessages, ...options } = this.thread.options;\n\n this.thread = new LocalThreadRuntimeCore(\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 { useEffect, useMemo, useState } from \"react\";\nimport { ExternalStoreRuntimeCore } from \"./ExternalStoreRuntimeCore\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\nimport { ThreadRuntime } from \"../../api/ThreadRuntime\";\n\nexport const useExternalStoreRuntime = <T,>(store: ExternalStoreAdapter<T>) => {\n const [runtime] = useState(() => new ExternalStoreRuntimeCore(store));\n\n useEffect(() => {\n runtime.thread.store = store;\n });\n\n return useMemo(() => new AssistantRuntime(runtime, ThreadRuntime), [runtime]);\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 { AddToolResultOptions } from \"../core\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/MessageRepository\";\nimport {\n AppendMessage,\n ModelConfigProvider,\n ThreadMessage,\n Unsubscribe,\n} from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport {\n getExternalStoreMessage,\n symbolInnerMessage,\n} from \"./getExternalStoreMessage\";\nimport { ThreadMessageConverter } from \"./ThreadMessageConverter\";\nimport { getAutoStatus, isAutoStatus } from \"./auto-status\";\nimport { fromThreadMessageLike } from \"./ThreadMessageLike\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { generateId } from \"../../internal\";\nimport { DefaultThreadComposerRuntimeCore } from \"../composer/DefaultThreadComposerRuntimeCore\";\nimport {\n RuntimeCapabilities,\n SubmitFeedbackOptions,\n} from \"../core/ThreadRuntimeCore\";\nimport { ReactThreadRuntimeCore } from \"../core/ReactThreadRuntimeCore\";\nimport { DefaultEditComposerRuntimeCore } from \"../composer/DefaultEditComposerRuntimeCore\";\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore implements ReactThreadRuntimeCore {\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 DefaultThreadComposerRuntimeCore(this);\n private _editComposers = new Map<string, DefaultEditComposerRuntimeCore>();\n public getEditComposer(messageId: string) {\n return this._editComposers.get(messageId);\n }\n public beginEdit(messageId: string) {\n if (this._editComposers.has(messageId))\n throw new Error(\"Edit already in progress\");\n\n this._editComposers.set(\n messageId,\n new DefaultEditComposerRuntimeCore(\n this,\n () => this._editComposers.delete(messageId),\n this.repository.getMessage(messageId),\n ),\n );\n this.notifySubscribers();\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 public import(repository: ExportedMessageRepository) {\n this.repository.import(repository);\n }\n\n public export(): ExportedMessageRepository {\n return this.repository.export();\n }\n}\n","import { BaseAssistantRuntimeCore, ProxyConfigProvider } from \"../../internal\";\nimport { ModelConfigProvider } from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { ExternalStoreThreadRuntimeCore } from \"./ExternalStoreThreadRuntimeCore\";\n\nexport class ExternalStoreRuntimeCore extends BaseAssistantRuntimeCore<ExternalStoreThreadRuntimeCore> {\n private readonly _proxyConfigProvider;\n\n constructor(store: ExternalStoreAdapter<any>) {\n const provider = new ProxyConfigProvider();\n super(new ExternalStoreThreadRuntimeCore(provider, store));\n this._proxyConfigProvider = provider;\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.thread.store.onSwitchToNewThread)\n throw new Error(\"Runtime does not support switching to new threads.\");\n\n this.thread = new ExternalStoreThreadRuntimeCore(\n this._proxyConfigProvider,\n {\n ...this.thread.store,\n messages: [],\n },\n );\n await this.thread.store.onSwitchToNewThread!();\n }\n\n public async switchToThread(threadId: string | null) {\n if (threadId !== null) {\n if (!this.thread.store.onSwitchToThread)\n throw new Error(\"Runtime does not support switching threads.\");\n\n this.thread = new ExternalStoreThreadRuntimeCore(\n this._proxyConfigProvider,\n {\n ...this.thread.store,\n messages: [], // ignore messages until rerender\n },\n );\n this.thread.store.onSwitchToThread!(threadId);\n } else {\n this.switchToNewThread();\n }\n }\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 role = output.role;\n switch (role) {\n case \"system\":\n case \"user\":\n return output;\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(...output.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","\"use client\";\n\nimport {\n ComponentType,\n FC,\n PropsWithChildren,\n ReactNode,\n createContext,\n useContext,\n} from \"react\";\n\nimport { AssistantRuntime } from \"../api/AssistantRuntime\";\nimport { AvatarProps } from \"./base/avatar\";\nimport { TextContentPartComponent, ToolCallContentPartProps } from \"../types\";\nimport { AssistantRuntimeProvider } from \"../context\";\nimport { AssistantToolUI } from \"../model-config\";\nimport { useAssistantRuntime } 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 = !!useAssistantRuntime({ 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"]}
1
+ {"version":3,"sources":["/home/runner/work/assistant-ui/assistant-ui/packages/react/dist/index.js","../src/context/providers/AssistantRuntimeProvider.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/ThreadRuntimeProvider.tsx","../src/context/react/ThreadContext.ts","../src/context/stores/ThreadViewport.tsx","../src/context/ReadonlyStore.ts","../src/context/providers/TextContentPartProvider.tsx","../src/context/react/ContentPartContext.ts","../src/api/ContentPartRuntime.ts","../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/utils/getThreadMessageText.tsx","../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/ContentPartRuntimeProvider.tsx","../src/primitives/contentPart/ContentPartText.tsx","../src/utils/smooth/useSmooth.tsx","../src/utils/smooth/SmoothContext.tsx","../src/primitives/contentPart/ContentPartImage.tsx","../src/primitives/contentPart/ContentPartDisplay.tsx","../src/primitives/contentPart/ContentPartInProgress.tsx","../src/api/AttachmentRuntime.ts","../src/api/subscribable/BaseSubject.ts","../src/api/subscribable/SKIP_UPDATE.ts","../src/api/subscribable/LazyMemoizeSubject.ts","../src/api/subscribable/shallowEqual.ts","../src/api/subscribable/ShallowMemoizeSubject.ts","../src/api/ComposerRuntime.ts","../src/api/subscribable/NestedSubscriptionSubject.ts","../src/api/MessageRuntime.ts","../src/primitives/message/MessageInProgress.tsx","../src/primitives/message/MessageAttachments.tsx","../src/context/react/AttachmentContext.ts","../src/context/providers/AttachmentRuntimeProvider.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/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/MessageRuntimeProvider.tsx","../src/context/stores/MessageUtils.ts","../src/primitives/thread/ThreadScrollToBottom.tsx","../src/primitives/thread/ThreadSuggestion.tsx","../src/runtimes/core/subscribeToMainThread.ts","../src/runtimes/local/useLocalRuntime.tsx","../src/runtimes/core/BaseAssistantRuntimeCore.tsx","../src/internal.ts","../src/runtimes/composer/BaseComposerRuntimeCore.tsx","../src/runtimes/composer/DefaultThreadComposerRuntimeCore.tsx","../src/utils/ProxyConfigProvider.ts","../src/utils/idUtils.tsx","../src/runtimes/edge/converters/fromCoreMessage.ts","../src/runtimes/utils/MessageRepository.tsx","../src/ui/base/tooltip-icon-button.tsx","../src/ui/base/tooltip.tsx","../src/ui/utils/withDefaults.tsx","../src/ui/base/button.tsx","../src/api/AssistantRuntime.ts","../src/api/ThreadRuntime.ts","../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/composer/DefaultEditComposerRuntimeCore.tsx","../src/runtimes/local/LocalThreadRuntimeCore.tsx","../src/runtimes/local/LocalRuntimeCore.tsx","../src/runtimes/external-store/useExternalStoreRuntime.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/runtimes/external-store/ExternalStoreThreadRuntimeCore.tsx","../src/runtimes/external-store/ExternalStoreRuntimeCore.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/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":["actions","useThreadRuntimeStore","useThreadStore","useThreadMessagesStore","useThreadComposerStore","useThread","useAssistantRuntimeStore","useEffect","useAssistantRuntime","useEditComposer","Primitive","useContentPartStore","COMPLETE_STATUS","useAttachmentRuntime","useEscapeKeydown","getComponent","AttachmentComponent","useMessageStore","useMessageUtilsStore","useEditComposerStore","messages","BranchPickerPrevious","exports","ComposerAttachment"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDA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AEMA;AACJ,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAEO;AvKmxLD;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;AACA;AACA","file":"/home/runner/work/assistant-ui/assistant-ui/packages/react/dist/index.js","sourcesContent":[null,"\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { memo, useEffect, useMemo, useState } from \"react\";\nimport { AssistantContext } from \"../react/AssistantContext\";\nimport { makeAssistantToolUIsStore } from \"../stores/AssistantToolUIs\";\nimport { ThreadRuntimeProvider } from \"./ThreadRuntimeProvider\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\nimport { create } from \"zustand\";\nimport { writableStore } from \"../ReadonlyStore\";\n\ntype AssistantRuntimeProviderProps = {\n runtime: AssistantRuntime;\n};\n\nconst useAssistantRuntimeStore = (runtime: AssistantRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useAssistantToolUIsStore = () => {\n return useMemo(() => makeAssistantToolUIsStore(), []);\n};\n\nexport const AssistantRuntimeProviderImpl: FC<\n PropsWithChildren<AssistantRuntimeProviderProps>\n> = ({ children, runtime }) => {\n const useAssistantRuntime = useAssistantRuntimeStore(runtime);\n const useToolUIs = useAssistantToolUIsStore();\n const context = useMemo(() => {\n return {\n useToolUIs,\n useAssistantRuntime,\n useAssistantActions: useAssistantRuntime,\n };\n }, [useAssistantRuntime, useToolUIs]);\n\n return (\n <AssistantContext.Provider value={context}>\n <ThreadRuntimeProvider runtime={runtime.thread}>\n {children}\n </ThreadRuntimeProvider>\n </AssistantContext.Provider>\n );\n};\n\nexport const AssistantRuntimeProvider = memo(AssistantRuntimeProviderImpl);\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { AssistantToolUIsState } from \"../stores/AssistantToolUIs\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\n\nexport type AssistantContextValue = {\n useToolUIs: UseBoundStore<ReadonlyStore<AssistantToolUIsState>>;\n useAssistantRuntime: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n\n /**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\n useAssistantActions: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n};\n\nexport const AssistantContext = createContext<AssistantContextValue | null>(\n null,\n);\n\nexport const useAssistantContext = createContextHook(\n AssistantContext,\n \"AssistantRuntimeProvider\",\n);\n\nexport function useAssistantRuntime(options?: {\n optional?: false | undefined;\n}): AssistantRuntime;\nexport function useAssistantRuntime(options?: {\n optional?: boolean | undefined;\n}): AssistantRuntime | null;\nexport function useAssistantRuntime(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useAssistantContext(options);\n if (!context) return null;\n return context.useAssistantRuntime();\n}\n\nexport const actions = createContextStoreHook(\n useAssistantContext,\n \"useAssistantActions\",\n);\n\n/**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useAssistantActionsStore = actions.useAssistantActionsStore;\n\n/**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useAssistantActions = actions.useAssistantActions;\n\n/**\n * @deprecated Use `useAssistantRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useAssistantRuntimeStore = useAssistantActionsStore;\n\nexport const { useToolUIs, useToolUIsStore } = createContextStoreHook(\n useAssistantContext,\n \"useToolUIs\",\n);\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) return null;\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, useMemo, useState } from \"react\";\nimport type { ThreadContextValue } from \"../react/ThreadContext\";\nimport { ThreadContext } from \"../react/ThreadContext\";\nimport { makeThreadViewportStore } from \"../stores/ThreadViewport\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport { ThreadRuntime } from \"../../api/ThreadRuntime\";\nimport { create } from \"zustand\";\nimport { ThreadComposerRuntime } from \"../../api\";\n\ntype ThreadProviderProps = {\n runtime: ThreadRuntime;\n};\n\nconst useThreadRuntimeStore = (runtime: ThreadRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useThreadStore = (runtime: ThreadRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useThreadMessagesStore = (runtime: ThreadRuntime) => {\n const [store] = useState(() => create(() => runtime.messages));\n\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.messages, true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useThreadComposerStore = (runtime: ThreadComposerRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const ThreadRuntimeProvider: FC<\n PropsWithChildren<ThreadProviderProps>\n> = ({ children, runtime }) => {\n const useThreadRuntime = useThreadRuntimeStore(runtime);\n const useThread = useThreadStore(runtime);\n const useThreadMessages = useThreadMessagesStore(runtime);\n const useThreadComposer = useThreadComposerStore(runtime.composer);\n\n const context = useMemo<ThreadContextValue>(() => {\n const useViewport = makeThreadViewportStore();\n\n return {\n useThread,\n useThreadRuntime,\n useThreadMessages,\n useThreadActions: useThreadRuntime,\n useComposer: useThreadComposer,\n useViewport,\n };\n }, [useThread, useThreadRuntime, useThreadMessages, useThreadComposer]);\n\n return (\n <ThreadContext.Provider value={context}>{children}</ThreadContext.Provider>\n );\n};\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport type { ThreadViewportState } from \"../stores/ThreadViewport\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { UseBoundStore } from \"zustand\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { ThreadRuntime } from \"../../api\";\nimport { ThreadState } from \"../../api/ThreadRuntime\";\nimport { ThreadMessage } from \"../../types\";\nimport { ThreadComposerState } from \"../../api/ComposerRuntime\";\n\nexport type ThreadContextValue = {\n useThread: UseBoundStore<ReadonlyStore<ThreadState>>;\n /**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\n useThreadActions: UseBoundStore<ReadonlyStore<ThreadRuntime>>;\n useThreadRuntime: UseBoundStore<ReadonlyStore<ThreadRuntime>>;\n useThreadMessages: UseBoundStore<ReadonlyStore<readonly ThreadMessage[]>>;\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 function useThreadRuntime(options?: {\n optional?: false | undefined;\n}): ThreadRuntime;\nexport function useThreadRuntime(options?: {\n optional?: boolean | undefined;\n}): ThreadRuntime | null;\nexport function useThreadRuntime(options?: { optional?: boolean | undefined }) {\n const context = useThreadContext(options);\n if (!context) return null;\n return context.useThreadRuntime();\n}\n\nexport const actions = createContextStoreHook(\n useThreadContext,\n \"useThreadActions\",\n);\n\n/**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useThreadActionsStore = actions.useThreadActionsStore;\n\n/**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useThreadActions = actions.useThreadActions;\n\n/**\n * @deprecated Use `useThreadRuntime` instead. This will be removed in 0.6.0.\n */\nexport const useThreadRuntimeStore = useThreadActionsStore;\n\nexport const { useThread, useThreadStore } = createContextStoreHook(\n useThreadContext,\n \"useThread\",\n);\n\nconst messages = createContextStoreHook(useThreadContext, \"useThreadMessages\");\n\n/**\n * @deprecated Use `useThread().messages` instead. This will be removed in 0.6.0.\n */\nexport const useThreadMessages = messages.useThreadMessages;\n\n/**\n * @deprecated Use `useThreadRuntime().getState().messages` instead. This will be removed in 0.6.0.\n */\nexport const useThreadMessagesStore = messages.useThreadMessagesStore;\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","\"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 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 type { FC, PropsWithChildren } from \"react\";\nimport { useEffect, useState } from \"react\";\nimport { create } from \"zustand\";\nimport {\n ContentPartContext,\n ContentPartContextValue,\n} from \"../react/ContentPartContext\";\nimport { ContentPartStatus, TextContentPart } from \"../../types/AssistantTypes\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport {\n ContentPartRuntime,\n ContentPartState,\n} from \"../../api/ContentPartRuntime\";\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 useContentPartRuntime = create(\n // TODO\n () => new ContentPartRuntime(null as any, null as any, null as any),\n );\n const useContentPart = create<ContentPartState>(() => ({\n status: isRunning ? RUNNING_STATUS : COMPLETE_STATUS,\n part: { type: \"text\", text },\n type: \"text\",\n text,\n }));\n\n return { useContentPartRuntime, useContentPart };\n });\n\n useEffect(() => {\n const state = context.useContentPart.getState();\n const textUpdated = (state as TextContentPart).text !== text;\n const targetTextPart = textUpdated\n ? { type: \"text\" as const, text }\n : state;\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 { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { UseBoundStore } from \"zustand\";\nimport { ContentPartRuntime } from \"../../api\";\nimport { ContentPartState } from \"../../api/ContentPartRuntime\";\n\nexport type ContentPartContextValue = {\n useContentPartRuntime: UseBoundStore<ReadonlyStore<ContentPartRuntime>>;\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 function useContentPartRuntime(options?: {\n optional?: false | undefined;\n}): ContentPartRuntime;\nexport function useContentPartRuntime(options?: {\n optional?: boolean | undefined;\n}): ContentPartRuntime | null;\nexport function useContentPartRuntime(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useContentPartContext(options);\n if (!context) return null;\n return context.useContentPartRuntime();\n}\n\nexport const { useContentPart, useContentPartStore } = createContextStoreHook(\n useContentPartContext,\n \"useContentPart\",\n);\n","import {\n ThreadAssistantContentPart,\n ThreadUserContentPart,\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../types/AssistantTypes\";\nimport { ThreadRuntimeCoreBinding } from \"./ThreadRuntime\";\nimport { MessageStateBinding } from \"./MessageRuntime\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nexport type ContentPartState = (\n | ThreadUserContentPart\n | ThreadAssistantContentPart\n) & {\n /**\n * @deprecated You can directly access content part fields in the state. Replace `.part.type` with `.type` etc. This will be removed in 0.6.0.\n */\n part: ThreadUserContentPart | ThreadAssistantContentPart;\n status: ContentPartStatus | ToolCallContentPartStatus;\n};\n\ntype ContentPartSnapshotBinding = SubscribableWithState<ContentPartState>;\n\nexport class ContentPartRuntime {\n constructor(\n private contentBinding: ContentPartSnapshotBinding,\n private messageApi: MessageStateBinding,\n private threadApi: ThreadRuntimeCoreBinding,\n ) {}\n\n public getState() {\n return this.contentBinding.getState();\n }\n\n public addToolResult(result: any) {\n const message = this.messageApi.getState();\n if (!message) throw new Error(\"Message is not available\");\n\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Content part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\"Tried to add tool result to non-tool content part\");\n\n const toolName = state.toolName;\n const toolCallId = state.toolCallId;\n\n this.threadApi.getState().addToolResult({\n messageId: message.id,\n toolName,\n toolCallId,\n result,\n });\n }\n\n public subscribe(callback: () => void) {\n return this.contentBinding.subscribe(callback);\n }\n}\n","\"use client\";\n\nimport { createContext } from \"react\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { MessageUtilsState } from \"../stores/MessageUtils\";\nimport { createContextHook } from \"./utils/createContextHook\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { UseBoundStore } from \"zustand\";\nimport { MessageRuntime } from \"../../api\";\nimport { MessageState } from \"../../api/MessageRuntime\";\nimport { EditComposerState } from \"../../api/ComposerRuntime\";\n\nexport type MessageContextValue = {\n useMessageRuntime: UseBoundStore<ReadonlyStore<MessageRuntime>>;\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\nexport function useMessageRuntime(options?: {\n optional?: false | undefined;\n}): MessageRuntime;\nexport function useMessageRuntime(options?: {\n optional?: boolean | undefined;\n}): MessageRuntime | null;\nexport function useMessageRuntime(options?: {\n optional?: boolean | undefined;\n}) {\n const context = useMessageContext(options);\n if (!context) return null;\n return context.useMessageRuntime();\n}\n\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, useMessageRuntime } from \"./MessageContext\";\nimport { useThreadContext, useThreadRuntime } from \"./ThreadContext\";\nimport { ReadonlyStore } from \"../ReadonlyStore\";\nimport { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport { ComposerRuntime, ComposerState } from \"../../api/ComposerRuntime\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type ComposerContextValue = {\n useComposer: UseBoundStore<ReadonlyStore<ComposerState>>;\n type: \"edit\" | \"new\";\n};\n\nexport const useComposerContext = (): ComposerContextValue => {\n const { useComposer: useThreadComposer } = useThreadContext();\n const { useEditComposer } = useMessageContext({ optional: true }) ?? {};\n return useMemo(\n () => ({\n useComposer: useEditComposer ?? useThreadComposer,\n type: useEditComposer ? (\"edit\" as const) : (\"new\" as const),\n }),\n [useEditComposer, useThreadComposer],\n );\n};\n\nexport const { useComposer, useComposerStore } = createContextStoreHook(\n useComposerContext,\n \"useComposer\",\n);\n\nexport function useComposerRuntime(options?: {\n optional?: false | undefined;\n}): ComposerRuntime;\nexport function useComposerRuntime(options?: {\n optional?: boolean | undefined;\n}): ComposerRuntime | null;\nexport function useComposerRuntime(options?: {\n optional?: boolean | undefined;\n}): ComposerRuntime | null {\n const messageRuntime = useMessageRuntime({ optional: true });\n const threadRuntime = useThreadRuntime(options);\n return messageRuntime\n ? messageRuntime.composer\n : (threadRuntime?.composer ?? null);\n}\n","import { useCallback } from \"react\";\nimport { useThreadViewportStore } from \"../context\";\nimport {\n useThreadComposerStore,\n useThreadRuntime,\n} from \"../context/react/ThreadContext\";\nimport { CreateAppendMessage } from \"../api/ThreadRuntime\";\n\nexport const useAppendMessage = () => {\n const threadRuntime = useThreadRuntime();\n const threadViewportStore = useThreadViewportStore();\n const threadComposerStore = useThreadComposerStore();\n\n const append = useCallback(\n (message: CreateAppendMessage) => {\n threadRuntime.append(message);\n\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n },\n [threadRuntime, threadViewportStore, threadComposerStore],\n );\n\n return append;\n};\n","import { useCallback } from \"react\";\nimport { useThreadComposerStore } from \"../context/react/ThreadContext\";\nimport { useAssistantRuntime } from \"../context\";\n\n/**\n * @deprecated Use `useRuntimeActions().switchToNewThread()` instead. This will be removed in 0.6.0.\n */\nexport const useSwitchToNewThread = () => {\n const assistantRuntime = useAssistantRuntime();\n const threadComposerStore = useThreadComposerStore();\n const switchToNewThread = useCallback(() => {\n assistantRuntime.switchToNewThread();\n threadComposerStore.getState().focus();\n }, [assistantRuntime, threadComposerStore]);\n\n return switchToNewThread;\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport {\n useAssistantRuntime,\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 assistantRuntime = useAssistantRuntime();\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 = assistantRuntime.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 }, [assistantRuntime, 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 { useAssistantRuntime } from \"../context\";\n\nexport const useAssistantInstructions = (instruction: string) => {\n const assistantRuntime = useAssistantRuntime();\n useEffect(() => {\n const config = {\n system: instruction,\n };\n return assistantRuntime.registerModelConfigProvider({\n getModelConfig: () => config,\n });\n }, [assistantRuntime, 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 StoreOrRuntime,\n} from \"./createCombinedStore\";\n\nexport const useCombinedStore = <T extends Array<unknown>, R>(\n stores: { [K in keyof T]: StoreOrRuntime<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\";\n\nexport type StoreOrRuntime<T> = {\n getState: () => T;\n subscribe: (callback: () => void) => Unsubscribe;\n};\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]: StoreOrRuntime<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 type {\n AppendMessage,\n TextContentPart,\n ThreadMessage,\n} from \"../types/AssistantTypes\";\n\nexport const getThreadMessageText = (\n message: ThreadMessage | AppendMessage,\n) => {\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 { useCallback } from \"react\";\nimport { useEditComposer, useMessageRuntime } from \"../../context\";\n\nexport const useActionBarEdit = () => {\n const messageRuntime = useMessageRuntime();\n const disabled = useEditComposer((c) => c.isEditing);\n\n const callback = useCallback(() => {\n messageRuntime.composer.beginEdit();\n }, [messageRuntime]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport {\n useMessageRuntime,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport {\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 messageRuntime = useMessageRuntime();\n const threadComposerStore = useThreadComposerStore();\n const threadViewportStore = useThreadViewportStore();\n\n const disabled = useCombinedStore(\n [threadStore, messageStore],\n (t, m) => t.isRunning || t.isDisabled || m.role !== \"assistant\",\n );\n\n const callback = useCallback(() => {\n messageRuntime.reload();\n threadViewportStore.getState().scrollToBottom();\n threadComposerStore.getState().focus();\n }, [messageRuntime, threadComposerStore, threadViewportStore]);\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 useMessageRuntime,\n useMessageStore,\n useMessageUtilsStore,\n} from \"../../context\";\n\nexport const useActionBarSpeak = () => {\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const messageRunime = useMessageRuntime();\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 utt = messageRunime.speak();\n messageUtilsStore.getState().addUtterance(utt);\n }, [messageRunime, 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 { useMessageRuntime, useMessageUtilsStore } from \"../../context\";\n\nexport const useActionBarFeedbackPositive = () => {\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({\n type: \"positive\",\n });\n messageUtilsStore.getState().setSubmittedFeedback(\"positive\");\n }, [messageUtilsStore, messageRuntime]);\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageRuntime, useMessageUtilsStore } from \"../../context\";\n\nexport const useActionBarFeedbackNegative = () => {\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({\n type: \"negative\",\n });\n messageUtilsStore.getState().setSubmittedFeedback(\"negative\");\n }, [messageUtilsStore, messageRuntime]);\n\n return callback;\n};\n","\"use client\";\nimport { useMessage } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerCount = () => {\n const branchCount = useMessage((s) => s.branchCount);\n return branchCount;\n};\n","import { useCallback } from \"react\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport { useEditComposerStore, useMessageStore } from \"../../context\";\nimport { useMessageRuntime } from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerNext = () => {\n const messageRuntime = useMessageRuntime();\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) => c.isEditing || m.branchNumber >= m.branchCount,\n );\n\n const callback = useCallback(() => {\n messageRuntime.switchToBranch({ position: \"next\" });\n }, [messageRuntime]);\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 branchNumber = useMessage((s) => s.branchNumber);\n return branchNumber;\n};\n","import { useCallback } from \"react\";\nimport {\n useEditComposerStore,\n useMessageRuntime,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useBranchPickerPrevious = () => {\n const messageRuntime = useMessageRuntime();\n const messageStore = useMessageStore();\n const editComposerStore = useEditComposerStore();\n const disabled = useCombinedStore(\n [messageStore, editComposerStore],\n (m, c) => c.isEditing || m.branchNumber <= 1,\n );\n\n const callback = useCallback(() => {\n messageRuntime.switchToBranch({ position: \"previous\" });\n }, [messageRuntime]);\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 { ContentPartState } from \"../../api/ContentPartRuntime\";\nimport { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { UIContentPart } from \"../../types\";\n\nexport const useContentPartDisplay = () => {\n const display = useContentPart((c) => {\n if (c.type !== \"ui\")\n throw new Error(\n \"This component can only be used inside ui content parts.\",\n );\n\n return c as ContentPartState & UIContentPart;\n });\n\n return display;\n};\n","import { ContentPartState } from \"../../api/ContentPartRuntime\";\nimport { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { ImageContentPart } from \"../../types\";\n\nexport const useContentPartImage = () => {\n const image = useContentPart((c) => {\n if (c.type !== \"image\")\n throw new Error(\n \"ContentPartImage can only be used inside image content parts.\",\n );\n\n return c as ContentPartState & ImageContentPart;\n });\n\n return image;\n};\n","import { ContentPartState } from \"../../api/ContentPartRuntime\";\nimport { useContentPart } from \"../../context/react/ContentPartContext\";\nimport { TextContentPart } from \"../../types\";\n\nexport const useContentPartText = () => {\n const text = useContentPart((c) => {\n if (c.type !== \"text\")\n throw new Error(\n \"ContentPartText can only be used inside text content parts.\",\n );\n\n return c as ContentPartState & TextContentPart;\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 { role, attachments, branchCount, isLast },\n { isCopied, isHovering, isSpeaking, submittedFeedback },\n ) => {\n if (props.hasBranches === true && branchCount < 2) return false;\n\n if (props.user && role !== \"user\") return false;\n if (props.assistant && role !== \"assistant\") return false;\n if (props.system && 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 (role !== \"user\" || !attachments.length)\n )\n return false;\n if (\n props.hasAttachments === false &&\n role === \"user\" &&\n !!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 { useThread } from \"../../context\";\nimport type { RequireAtLeastOne } from \"../../utils/RequireAtLeastOne\";\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 return useThread((thread) => {\n if (props.empty === true && thread.messages.length !== 0) return false;\n if (props.empty === false && thread.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","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, useMemo } from \"react\";\nimport { useContentPart, useThreadRuntime, useToolUIs } from \"../../context\";\nimport {\n useMessage,\n useMessageRuntime,\n useMessageStore,\n} from \"../../context/react/MessageContext\";\nimport { ContentPartRuntimeProvider } from \"../../context/providers/ContentPartRuntimeProvider\";\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\";\nimport { EMPTY_CONTENT } from \"../../api/MessageRuntime\";\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.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 threadRuntime = useThreadRuntime();\n\n const part = useContentPart();\n\n const type = part.type;\n switch (type) {\n case \"text\":\n if (part.status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n if (part.part === EMPTY_CONTENT && !!Empty) {\n return <Empty status={part.status} />;\n }\n\n return <Text {...part} part={part} />;\n\n case \"image\":\n if (part.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={part} />;\n\n case \"ui\":\n if (part.status.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n return <UI {...part} part={part} />;\n\n case \"tool-call\": {\n const Tool = by_name[part.toolName] || Fallback;\n const addResult = (result: any) =>\n threadRuntime.addToolResult({\n messageId: messageStore.getState().id,\n toolName: part.toolName,\n toolCallId: part.toolCallId,\n result,\n });\n return (\n <ToolUIDisplay {...part} part={part} UI={Tool} addResult={addResult} />\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 const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.unstable_getContentPartByIndex(partIndex),\n [messageRuntime, partIndex],\n );\n\n return (\n <ContentPartRuntimeProvider runtime={runtime}>\n <MessageContentPartComponent components={components} />\n </ContentPartRuntimeProvider>\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.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 { writableStore } from \"../ReadonlyStore\";\nimport { ContentPartRuntime } from \"../../api\";\n\ntype ContentPartProviderProps = PropsWithChildren<{\n runtime: ContentPartRuntime;\n}>;\n\nconst useContentPartRuntimeStore = (runtime: ContentPartRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const useContentPartStore = (runtime: ContentPartRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const ContentPartRuntimeProvider: FC<ContentPartProviderProps> = ({\n runtime,\n children,\n}) => {\n const useContentPartRuntime = useContentPartRuntimeStore(runtime);\n const useContentPart = useContentPartStore(runtime);\n const [context] = useState<ContentPartContextValue>(() => {\n return { useContentPartRuntime, useContentPart };\n });\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 { text, status } = 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","\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useMessage } from \"../../context\";\nimport { ContentPartStatus, TextContentPart } from \"../../types/AssistantTypes\";\nimport { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useSmoothStatusStore } from \"./SmoothContext\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\nimport { ContentPartState } from \"../../api/ContentPartRuntime\";\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: ContentPartState & TextContentPart,\n smooth: boolean = false,\n): ContentPartState & TextContentPart => {\n const { text } = state;\n const id = useMessage({\n optional: true,\n selector: (m: { id: string }) => m.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.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.text ? SMOOTH_STATUS : state.status,\n );\n }\n }, [smoothStatusStore, text, displayedText, state.status, state.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 type: \"text\",\n text: displayedText,\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 ComponentType,\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 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","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 { image } = 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 { display } = 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","import { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nimport { ComposerRuntimeCoreBinding } from \"./ComposerRuntime\";\nimport { Attachment, CompleteAttachment, PendingAttachment } from \"../types\";\n\ntype MessageAttachmentState = CompleteAttachment & {\n source: \"message\";\n /**\n * @deprecated You can directly access content part fields in the state. Replace `.attachment.type` with `.type` etc. This will be removed in 0.6.0.\n */\n attachment: CompleteAttachment;\n};\n\ntype ThreadComposerAttachmentState = PendingAttachment & {\n source: \"thread-composer\";\n /**\n * @deprecated You can directly access content part fields in the state. Replace `.attachment.type` with `.type` etc. This will be removed in 0.6.0.\n */\n attachment: PendingAttachment;\n};\n\ntype EditComposerAttachmentState = Attachment & {\n source: \"edit-composer\";\n /**\n * @deprecated You can directly access content part fields in the state. Replace `.attachment.type` with `.type` etc. This will be removed in 0.6.0.\n */\n attachment: Attachment;\n};\n\nexport type AttachmentState =\n | ThreadComposerAttachmentState\n | EditComposerAttachmentState\n | MessageAttachmentState;\n\ntype AttachmentSnapshotBinding<Source extends AttachmentRuntimeSource> =\n SubscribableWithState<AttachmentState & { source: Source }>;\n\ntype AttachmentRuntimeSource = AttachmentState[\"source\"];\n\nexport abstract class AttachmentRuntime<\n Source extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> {\n public abstract get source(): Source;\n\n constructor(private _core: AttachmentSnapshotBinding<Source>) {}\n\n public getState(): AttachmentState & { source: Source } {\n return this._core.getState();\n }\n\n public abstract remove(): Promise<void>;\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n}\n\nabstract class ComposerAttachmentRuntime<\n Source extends \"thread-composer\" | \"edit-composer\",\n> extends AttachmentRuntime<Source> {\n constructor(\n core: AttachmentSnapshotBinding<Source>,\n private _composerApi: ComposerRuntimeCoreBinding,\n ) {\n super(core);\n }\n\n public remove() {\n const core = this._composerApi.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.removeAttachment(this.getState().id);\n }\n}\n\nexport class ThreadComposerAttachmentRuntime extends ComposerAttachmentRuntime<\"thread-composer\"> {\n public get source(): \"thread-composer\" {\n return \"thread-composer\";\n }\n}\n\nexport class EditComposerAttachmentRuntime extends ComposerAttachmentRuntime<\"edit-composer\"> {\n public get source(): \"edit-composer\" {\n return \"edit-composer\";\n }\n}\n\nexport class MessageAttachmentRuntime extends AttachmentRuntime<\"message\"> {\n public get source(): \"message\" {\n return \"message\";\n }\n\n constructor(core: AttachmentSnapshotBinding<\"message\">) {\n super(core);\n }\n\n public remove(): never {\n throw new Error(\"Message attachments cannot be removed\");\n }\n}\n","import { Unsubscribe } from \"../../types/Unsubscribe\";\n\nexport abstract class BaseSubject {\n private _subscriptions = new Set<() => void>();\n private _connection: Unsubscribe | undefined;\n\n protected get isConnected() {\n return !!this._connection;\n }\n\n protected abstract _connect(): Unsubscribe;\n\n protected notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n private _updateConnection() {\n if (this._subscriptions.size > 0) {\n if (this._connection) return;\n this._connection = this._connect();\n } else {\n this._connection?.();\n this._connection = undefined;\n }\n }\n\n public subscribe(callback: () => void) {\n this._subscriptions.add(callback);\n this._updateConnection();\n\n return () => {\n this._subscriptions.delete(callback);\n this._updateConnection();\n };\n }\n}\n","export const SKIP_UPDATE = Symbol(\"skip-update\");\nexport type SKIP_UPDATE = typeof SKIP_UPDATE;\n","import { BaseSubject } from \"./BaseSubject\";\nimport { SKIP_UPDATE } from \"./SKIP_UPDATE\";\nimport { SubscribableWithState } from \"./Subscribable\";\n\nexport class LazyMemoizeSubject<T extends object>\n extends BaseSubject\n implements SubscribableWithState<T>\n{\n constructor(private binding: SubscribableWithState<T | SKIP_UPDATE>) {\n super();\n }\n\n private _previousStateDirty = true;\n private _previousState: T | undefined;\n public getState = () => {\n if (!this.isConnected || this._previousStateDirty) {\n const newState = this.binding.getState();\n if (newState !== SKIP_UPDATE) {\n this._previousState = newState;\n }\n this._previousStateDirty = false;\n }\n if (this._previousState === undefined)\n throw new Error(\"Entry not available in the store\");\n return this._previousState;\n };\n\n protected _connect() {\n const callback = () => {\n this._previousStateDirty = true;\n this.notifySubscribers();\n };\n\n return this.binding.subscribe(callback);\n }\n}\n","export function shallowEqual<T extends object>(\n objA: T | undefined,\n objB: T | undefined,\n) {\n if (objA === undefined && objB === undefined) return true;\n if (objA === undefined) return false;\n if (objB === undefined) return false;\n\n for (const key of Object.keys(objA)) {\n const valueA = objA[key as keyof T];\n const valueB = objB[key as keyof T];\n if (!Object.is(valueA, valueB)) return false;\n }\n\n return true;\n}\n","import { shallowEqual } from \"./shallowEqual\";\nimport { BaseSubject } from \"./BaseSubject\";\nimport { SubscribableWithState } from \"./Subscribable\";\nimport { SKIP_UPDATE } from \"./SKIP_UPDATE\";\n\nexport class ShallowMemoizeSubject<T extends object>\n extends BaseSubject\n implements SubscribableWithState<T>\n{\n constructor(private binding: SubscribableWithState<T | SKIP_UPDATE>) {\n super();\n const state = binding.getState();\n if (state === SKIP_UPDATE)\n throw new Error(\"Entry not available in the store\");\n this._previousState = state;\n }\n\n private _previousState: T;\n public getState = () => {\n if (!this.isConnected) this._syncState();\n return this._previousState;\n };\n\n private _syncState() {\n const state = this.binding.getState();\n if (state === SKIP_UPDATE) return false;\n if (shallowEqual(state, this._previousState)) return false;\n this._previousState = state;\n return true;\n }\n\n protected _connect() {\n const callback = () => {\n if (this._syncState()) {\n this.notifySubscribers();\n }\n };\n\n return this.binding.subscribe(callback);\n }\n}\n","import { Attachment, PendingAttachment } from \"../types/AttachmentTypes\";\nimport {\n ComposerRuntimeCore,\n ThreadComposerRuntimeCore,\n} from \"../runtimes/core/ComposerRuntimeCore\";\nimport { Unsubscribe } from \"../types\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\nimport { LazyMemoizeSubject } from \"./subscribable/LazyMemoizeSubject\";\nimport {\n AttachmentRuntime,\n AttachmentState,\n EditComposerAttachmentRuntime,\n ThreadComposerAttachmentRuntime,\n} from \"./AttachmentRuntime\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport { SKIP_UPDATE } from \"./subscribable/SKIP_UPDATE\";\n\nexport type ThreadComposerRuntimeCoreBinding = SubscribableWithState<\n ThreadComposerRuntimeCore | undefined\n>;\n\nexport type ComposerRuntimeCoreBinding = SubscribableWithState<\n ComposerRuntimeCore | undefined\n>;\n\ntype LegacyEditComposerState = Readonly<{\n type: \"edit\";\n\n /** @deprecated Use `text` instead. This will be removed in 0.6.0. */\n value: string;\n /** @deprecated Use `useComposerRuntime().setText()` instead. This will be removed in 0.6.0. */\n setValue: (value: string) => void;\n\n text: string;\n /**\n * @deprecated Use `useComposerRuntime().setText()` instead. This will be removed in 0.6.0.\n */\n setText: (value: string) => void;\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n\n /**\n * @deprecated Use useComposerRuntime().beginEdit() instead. This will be removed in 0.6.0.\n */\n edit: () => void;\n /**\n * @deprecated Use `useComposerRuntime().send()` instead. This will be removed in 0.6.0.\n */\n send: () => void;\n /**\n * @deprecated Use `useComposerRuntime().cancel()` instead. This will be removed in 0.6.0.\n */\n cancel: () => void;\n}>;\n\ntype LegacyThreadComposerState = Readonly<{\n type: \"thread\";\n\n /** @deprecated Use `text` instead. This will be removed in 0.6.0. */\n value: string;\n /** @deprecated Use `useComposerRuntime().setText` instead. This will be removed in 0.6.0. */\n setValue: (value: string) => void;\n\n attachmentAccept: string;\n attachments: readonly Attachment[];\n\n /** @deprecated Use `useComposerRuntime().addAttachment` instead. This will be removed in 0.6.0. */\n addAttachment: (file: File) => void;\n /** @deprecated Use `useComposerRuntime().removeAttachment` instead. This will be removed in 0.6.0. */\n removeAttachment: (attachmentId: string) => void;\n\n text: string;\n /** @deprecated Use `useComposerRuntime().setText` instead. This will be removed in 0.6.0. */\n setText: (value: string) => void;\n\n /** @deprecated Use `useComposerRuntime().reset` instead. This will be removed in 0.6.0. */\n reset: () => void;\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n\n /**\n * @deprecated Use `useComposerRuntime().send` instead. This will be removed in 0.6.0.\n **/\n send: () => void;\n /** @deprecated Use `useComposerRuntime().cancel` instead. This will be removed in 0.6.0. */\n cancel: () => void;\n\n // TODO replace with events\n /** @deprecated This feature is being removed in 0.6.0. Submit feedback if you need it. */\n focus: () => void;\n /** @deprecated This feature is being removed in 0.6.0. Submit feedback if you need it. */\n onFocus: (listener: () => void) => Unsubscribe;\n}>;\n\ntype BaseComposerState = {\n text: string;\n attachmentAccept: string;\n attachments: readonly Attachment[];\n\n canCancel: boolean;\n isEditing: boolean;\n isEmpty: boolean;\n};\n\nexport type ThreadComposerState = LegacyThreadComposerState &\n BaseComposerState & {\n type: \"thread\";\n\n attachments: readonly PendingAttachment[];\n };\n\nexport type EditComposerState = LegacyEditComposerState &\n BaseComposerState & {\n type: \"edit\";\n };\n\nexport type ComposerState = ThreadComposerState | EditComposerState;\n\nconst METHOD_NOT_SUPPORTED = () => {\n throw new Error(\"Composer is not available\");\n};\nconst EMPTY_ARRAY = Object.freeze([]);\nconst getThreadComposerState = (\n runtime: ThreadComposerRuntimeCore | undefined,\n focus: () => void,\n onFocus: (listener: () => void) => Unsubscribe,\n): ThreadComposerState => {\n return Object.freeze({\n type: \"thread\",\n\n isEditing: runtime?.isEditing ?? false,\n canCancel: runtime?.canCancel ?? false,\n isEmpty: runtime?.isEmpty ?? true,\n text: runtime?.text ?? \"\",\n attachments: runtime?.attachments ?? EMPTY_ARRAY,\n attachmentAccept: runtime?.attachmentAccept ?? \"*\",\n\n value: runtime?.text ?? \"\",\n setValue: runtime?.setText.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n setText: runtime?.setText.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n // edit: beginEdit,\n send: runtime?.send.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n cancel: runtime?.cancel.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n focus: focus,\n onFocus: onFocus,\n reset: runtime?.reset.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n\n addAttachment: runtime?.addAttachment.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n removeAttachment:\n runtime?.removeAttachment.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n });\n};\n\nconst getEditComposerState = (\n runtime: ComposerRuntimeCore | undefined,\n beginEdit: () => void,\n): EditComposerState => {\n return Object.freeze({\n type: \"edit\",\n\n isEditing: runtime?.isEditing ?? false,\n canCancel: runtime?.canCancel ?? false,\n isEmpty: runtime?.isEmpty ?? true,\n text: runtime?.text ?? \"\",\n attachments: runtime?.attachments ?? EMPTY_ARRAY,\n attachmentAccept: runtime?.attachmentAccept ?? \"*\",\n\n value: runtime?.text ?? \"\",\n setValue: runtime?.setText.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n setText: runtime?.setText.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n edit: beginEdit,\n send: runtime?.send.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n cancel: runtime?.cancel.bind(runtime) ?? METHOD_NOT_SUPPORTED,\n });\n};\n\nexport abstract class ComposerRuntime implements ComposerRuntimeCore {\n public abstract get type(): \"edit\" | \"thread\";\n\n constructor(protected _core: ComposerRuntimeCoreBinding) {}\n\n /**\n * @deprecated Use `getState().isEditing` instead. This will be removed in 0.6.0.\n */\n public get isEditing() {\n return this.getState().isEditing;\n }\n\n /**\n * @deprecated Use `getState().isEmpty` instead. This will be removed in 0.6.0.\n */\n public get isEmpty() {\n return this.getState().isEmpty;\n }\n\n /**\n * @deprecated Use `getState().canCancel` instead. This will be removed in 0.6.0.\n */\n public get canCancel() {\n return this.getState().canCancel;\n }\n\n /**\n * @deprecated Use `getState().text` instead. This will be removed in 0.6.0.\n */\n public get text() {\n return this.getState().text;\n }\n\n /**\n * @deprecated Use `getState().attachmentAccept` instead. This will be removed in 0.6.0.\n */\n public get attachmentAccept() {\n return this.getState().attachmentAccept;\n }\n\n /**\n * @deprecated Use `getState().attachments` instead. This will be removed in 0.6.0.\n */\n public get attachments() {\n return this.getState().attachments;\n }\n\n /**\n * @deprecated Use `getState().text` instead. This will be removed in 0.6.0.\n */\n public get value() {\n return this.text;\n }\n\n public abstract getState(): ComposerState;\n\n public setText(text: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setText(text);\n }\n\n public setValue(text: string) {\n this.setText(text);\n }\n\n public addAttachment(file: File) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.addAttachment(file);\n }\n\n // /**\n // * @deprecated Use `getAttachmentById(id).removeAttachment` instead. This will be removed in 0.6.0.\n // */\n public removeAttachment(attachmentId: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.removeAttachment(attachmentId);\n }\n\n /**\n * @deprecated This method will be removed in 0.6.0. Submit feedback if you need this functionality.\n */\n public reset() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.reset();\n }\n\n public send() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.send();\n }\n\n public cancel() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.cancel();\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n public abstract unstable_getAttachmentByIndex(idx: number): AttachmentRuntime;\n}\n\nexport class ThreadComposerRuntime\n extends ComposerRuntime\n implements ThreadComposerState\n{\n public get type() {\n return \"thread\" as const;\n }\n\n private _getState;\n\n constructor(core: ThreadComposerRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n getState: () =>\n getThreadComposerState(\n core.getState(),\n this.focus.bind(this),\n this.onFocus.bind(this),\n ),\n subscribe: (callback) => core.subscribe(callback),\n });\n super({\n getState: () => core.getState(),\n subscribe: (callback) => stateBinding.subscribe(callback),\n });\n this._getState = stateBinding.getState.bind(stateBinding);\n }\n\n public override get attachments() {\n return this.getState()?.attachments ?? EMPTY_ARRAY;\n }\n\n public override getState(): ThreadComposerState {\n return this._getState();\n }\n\n // TODO replace with events\n private _focusListeners = new Set<() => void>();\n\n public focus() {\n this._focusListeners.forEach((callback) => callback());\n }\n\n public onFocus(callback: () => void) {\n this._focusListeners.add(callback);\n return () => this._focusListeners.delete(callback);\n }\n\n public unstable_getAttachmentByIndex(idx: number) {\n return new ThreadComposerAttachmentRuntime(\n new ShallowMemoizeSubject({\n getState: () => {\n const attachments = this.getState().attachments;\n const attachment = attachments[idx];\n if (!attachment) return SKIP_UPDATE;\n\n return {\n ...attachment,\n attachment: attachment,\n source: \"thread-composer\",\n } satisfies AttachmentState & { source: \"thread-composer\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n\nexport class EditComposerRuntime\n extends ComposerRuntime\n implements EditComposerState\n{\n public get type() {\n return \"edit\" as const;\n }\n\n private _getState;\n constructor(\n core: ComposerRuntimeCoreBinding,\n private _beginEdit: () => void,\n ) {\n const stateBinding = new LazyMemoizeSubject({\n getState: () => getEditComposerState(core.getState(), this._beginEdit),\n subscribe: (callback) => core.subscribe(callback),\n });\n\n super({\n getState: () => core.getState(),\n subscribe: (callback) => stateBinding.subscribe(callback),\n });\n\n this._getState = stateBinding.getState.bind(stateBinding);\n }\n\n public override getState(): EditComposerState {\n return this._getState();\n }\n\n public beginEdit() {\n this._beginEdit();\n }\n\n /**\n * @deprecated Use `beginEdit()` instead. This will be removed in 0.6.0.\n */\n public edit() {\n this.beginEdit();\n }\n\n public unstable_getAttachmentByIndex(idx: number) {\n return new EditComposerAttachmentRuntime(\n new ShallowMemoizeSubject({\n getState: () => {\n const attachments = this.getState().attachments;\n const attachment = attachments[idx];\n if (!attachment) return SKIP_UPDATE;\n\n return {\n ...attachment,\n attachment: attachment,\n source: \"edit-composer\",\n } satisfies AttachmentState & { source: \"edit-composer\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n","import { Unsubscribe } from \"../../types\";\nimport { BaseSubject } from \"./BaseSubject\";\nimport {\n NestedSubscribable,\n Subscribable,\n SubscribableWithState,\n} from \"./Subscribable\";\n\nexport class NestedSubscriptionSubject<TState extends Subscribable | undefined>\n extends BaseSubject\n implements SubscribableWithState<TState>, NestedSubscribable<TState>\n{\n constructor(private binding: NestedSubscribable<TState>) {\n super();\n }\n\n public getState() {\n return this.binding.getState();\n }\n\n protected _connect(): Unsubscribe {\n const callback = () => {\n this.notifySubscribers();\n };\n\n let lastState = this.binding.getState();\n let innerUnsubscribe = lastState?.subscribe(callback);\n const onRuntimeUpdate = () => {\n const newState = this.binding.getState();\n if (newState === lastState) return;\n lastState = newState;\n\n innerUnsubscribe?.();\n innerUnsubscribe = this.binding.getState()?.subscribe(callback);\n\n callback();\n };\n\n const outerUnsubscribe = this.binding.subscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n","import {\n ThreadMessage,\n AppendMessage,\n ThreadAssistantContentPart,\n ThreadUserContentPart,\n} from \"../types\";\nimport {\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../types/AssistantTypes\";\nimport { AttachmentState, MessageAttachmentRuntime } from \"./AttachmentRuntime\";\nimport { EditComposerRuntime } from \"./ComposerRuntime\";\nimport { ContentPartRuntime, ContentPartState } from \"./ContentPartRuntime\";\nimport { ThreadRuntimeCoreBinding } from \"./ThreadRuntime\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { SKIP_UPDATE } from \"./subscribable/SKIP_UPDATE\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nconst COMPLETE_STATUS: ContentPartStatus = {\n type: \"complete\",\n};\n\nexport const 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 partIndex: number,\n): ContentPartState | SKIP_UPDATE => {\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 SKIP_UPDATE;\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 return Object.freeze({ ...part, part, status });\n};\n\nexport type MessageState = ThreadMessage & {\n /**\n * @deprecated You can directly access message fields in the state. Replace `.message.content` with `.content` etc. This will be removed in 0.6.0.\n */\n message: ThreadMessage;\n parentId: string | null;\n isLast: boolean;\n /**\n * @deprecated Use `branchNumber` and `branchCount` instead. This will be removed in 0.6.0.\n */\n branches: readonly string[];\n\n branchNumber: number;\n branchCount: number;\n};\n\nexport type MessageStateBinding = SubscribableWithState<MessageState>;\n\nexport class MessageRuntime {\n constructor(\n private _core: MessageStateBinding,\n private _threadBinding: ThreadRuntimeCoreBinding,\n ) {}\n\n public composer = new EditComposerRuntime(\n new NestedSubscriptionSubject({\n getState: () =>\n this._threadBinding\n .getState()\n .getEditComposer(this._core.getState().id),\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n () => this._threadBinding.getState().beginEdit(this._core.getState().id),\n );\n\n public getState() {\n return this._core.getState();\n }\n\n // TODO improve type\n public unstable_edit(message: Omit<AppendMessage, \"parentId\">) {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n this._threadBinding.getState().append({\n ...(message as AppendMessage),\n parentId: state.parentId,\n });\n }\n\n public reload() {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n if (state.role !== \"assistant\")\n throw new Error(\"Can only reload assistant messages\");\n\n this._threadBinding.getState().startRun(state.parentId);\n }\n\n public speak() {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n return this._threadBinding.getState().speak(state.id);\n }\n\n public submitFeedback({ type }: { type: \"positive\" | \"negative\" }) {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n this._threadBinding.getState().submitFeedback({\n messageId: state.id,\n type,\n });\n }\n\n public switchToBranch({\n position,\n branchId,\n }: {\n position?: \"previous\" | \"next\" | undefined;\n branchId?: string | undefined;\n }) {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n if (branchId && position) {\n throw new Error(\"May not specify both branchId and position\");\n } else if (!branchId && !position) {\n throw new Error(\"Must specify either branchId or position\");\n }\n\n const thread = this._threadBinding.getState();\n const branches = thread.getBranches(state.id);\n let targetBranch = branchId;\n if (position === \"previous\") {\n targetBranch = branches[state.branchNumber - 2];\n } else if (position === \"next\") {\n targetBranch = branches[state.branchNumber];\n }\n if (!targetBranch) throw new Error(\"Branch not found\");\n\n this._threadBinding.getState().switchToBranch(targetBranch);\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n public unstable_getContentPartByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n return new ContentPartRuntime(\n new ShallowMemoizeSubject({\n getState: () => {\n return getContentPartState(this.getState(), idx);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n this._threadBinding,\n );\n }\n\n public unstable_getAttachmentByIndex(idx: number) {\n return new MessageAttachmentRuntime(\n new ShallowMemoizeSubject({\n getState: () => {\n const attachments = this.getState().attachments;\n const attachment = attachments?.[idx];\n if (!attachment) return SKIP_UPDATE;\n\n return {\n ...attachment,\n attachment: attachment,\n source: \"message\",\n } satisfies AttachmentState & { source: \"message\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n );\n }\n}\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, useMemo } from \"react\";\nimport { useMessage, useMessageRuntime } from \"../../context\";\nimport { useMessageAttachment } from \"../../context/react/AttachmentContext\";\nimport { AttachmentRuntimeProvider } from \"../../context/providers/AttachmentRuntimeProvider\";\nimport { CompleteAttachment } from \"../../types\";\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: CompleteAttachment,\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 const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.unstable_getAttachmentByIndex(attachmentIndex),\n [messageRuntime, attachmentIndex],\n );\n\n return (\n <AttachmentRuntimeProvider runtime={runtime}>\n <AttachmentComponent components={components} />\n </AttachmentRuntimeProvider>\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 { createContextStoreHook } from \"./utils/createContextStoreHook\";\nimport {\n AttachmentRuntime,\n AttachmentState,\n} from \"../../api/AttachmentRuntime\";\nimport { UseBoundStore } from \"zustand\";\n\nexport type AttachmentContextValue = {\n source: \"thread-composer\" | \"edit-composer\" | \"message\";\n useAttachment: UseBoundStore<ReadonlyStore<AttachmentState>>;\n useAttachmentRuntime: UseBoundStore<ReadonlyStore<AttachmentRuntime>>;\n};\n\ntype ThreadComposerAttachmentContextValue = {\n source: \"thread-composer\";\n useAttachment: UseBoundStore<\n ReadonlyStore<AttachmentState & { source: \"thread-composer\" }>\n >;\n useAttachmentRuntime: UseBoundStore<\n ReadonlyStore<AttachmentRuntime & { type: \"thread-composer\" }>\n >;\n};\ntype EditComposerAttachmentContextValue = {\n source: \"edit-composer\";\n useAttachment: UseBoundStore<\n ReadonlyStore<AttachmentState & { source: \"edit-composer\" }>\n >;\n useAttachmentRuntime: UseBoundStore<\n ReadonlyStore<AttachmentRuntime & { type: \"edit-composer\" }>\n >;\n};\n\ntype MessageAttachmentContextValue = {\n source: \"message\";\n useAttachment: UseBoundStore<\n ReadonlyStore<AttachmentState & { source: \"message\" }>\n >;\n useAttachmentRuntime: UseBoundStore<\n ReadonlyStore<AttachmentRuntime & { type: \"message\" }>\n >;\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 useThreadComposerAttachmentContext(options?: {\n optional?: false | undefined;\n}): ThreadComposerAttachmentContextValue;\nfunction useThreadComposerAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): ThreadComposerAttachmentContextValue | null;\nfunction useThreadComposerAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): ThreadComposerAttachmentContextValue | null {\n const context = useAttachmentContext(options);\n if (!context) return null;\n if (context.source !== \"thread-composer\")\n throw new Error(\n \"This component must be used within a thread's ComposerPrimitive.Attachments component.\",\n );\n return context as ThreadComposerAttachmentContextValue;\n}\n\nfunction useEditComposerAttachmentContext(options?: {\n optional?: false | undefined;\n}): EditComposerAttachmentContextValue;\nfunction useEditComposerAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): EditComposerAttachmentContextValue | null;\nfunction useEditComposerAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): EditComposerAttachmentContextValue | null {\n const context = useAttachmentContext(options);\n if (!context) return null;\n if (context.source !== \"edit-composer\")\n throw new Error(\n \"This component must be used within a messages's ComposerPrimitive.Attachments component.\",\n );\n return context as EditComposerAttachmentContextValue;\n}\n\nfunction useMessageAttachmentContext(options?: {\n optional?: false | undefined;\n}): MessageAttachmentContextValue;\nfunction useMessageAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): MessageAttachmentContextValue | null;\nfunction useMessageAttachmentContext(options?: {\n optional?: boolean | undefined;\n}): MessageAttachmentContextValue | null {\n const context = useAttachmentContext(options);\n if (!context) return null;\n if (context.source !== \"message\")\n throw new Error(\n \"This component must be used within a MessagePrimitive.Attachments component.\",\n );\n return context as MessageAttachmentContextValue;\n}\n\nexport function useAttachmentRuntime(options?: {\n optional?: false | undefined;\n}): AttachmentRuntime;\nexport function useAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null;\nexport function useAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null {\n const attachmentRuntime = useAttachmentContext(options);\n if (!attachmentRuntime) return null;\n return attachmentRuntime.useAttachmentRuntime();\n}\n\nexport function useThreadComposerAttachmentRuntime(options?: {\n optional?: false | undefined;\n}): AttachmentRuntime;\nexport function useThreadComposerAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null;\nexport function useThreadComposerAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null {\n const attachmentRuntime = useThreadComposerAttachmentContext(options);\n if (!attachmentRuntime) return null;\n return attachmentRuntime.useAttachmentRuntime();\n}\n\nexport function useEditComposerAttachmentRuntime(options?: {\n optional?: false | undefined;\n}): AttachmentRuntime;\nexport function useEditComposerAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null;\nexport function useEditComposerAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null {\n const attachmentRuntime = useEditComposerAttachmentContext(options);\n if (!attachmentRuntime) return null;\n return attachmentRuntime.useAttachmentRuntime();\n}\n\nexport function useMessageAttachmentRuntime(options?: {\n optional?: false | undefined;\n}): AttachmentRuntime;\nexport function useMessageAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null;\nexport function useMessageAttachmentRuntime(options?: {\n optional?: boolean | undefined;\n}): AttachmentRuntime | null {\n const attachmentRuntime = useMessageAttachmentContext(options);\n if (!attachmentRuntime) return null;\n return attachmentRuntime.useAttachmentRuntime();\n}\n\nexport const { useAttachment } = createContextStoreHook(\n useAttachmentContext,\n \"useAttachment\",\n);\n\nexport const { useAttachment: useThreadComposerAttachment } =\n createContextStoreHook(useThreadComposerAttachmentContext, \"useAttachment\");\n\nexport const { useAttachment: useEditComposerAttachment } =\n createContextStoreHook(useEditComposerAttachmentContext, \"useAttachment\");\n\nexport const { useAttachment: useMessageAttachment } = createContextStoreHook(\n useMessageAttachmentContext,\n \"useAttachment\",\n);\n","\"use client\";\n\nimport {\n type FC,\n type PropsWithChildren,\n useEffect,\n useMemo,\n useState,\n} from \"react\";\nimport { create } from \"zustand\";\nimport { AttachmentContext } from \"../react/AttachmentContext\";\nimport { writableStore } from \"../ReadonlyStore\";\nimport { AttachmentRuntime } from \"../../api/AttachmentRuntime\";\n\ntype AttachmentRuntimeProviderProps = PropsWithChildren<{\n runtime: AttachmentRuntime;\n}>;\n\nconst useAttachmentRuntimeStore = (runtime: AttachmentRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\nconst useAttachmentStore = (runtime: AttachmentRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const AttachmentRuntimeProvider: FC<AttachmentRuntimeProviderProps> = ({\n runtime,\n children,\n}) => {\n const useAttachmentRuntime = useAttachmentRuntimeStore(runtime);\n const useAttachment = useAttachmentStore(runtime);\n const source = useAttachment((s) => s.source);\n const context = useMemo(() => {\n return {\n source,\n useAttachmentRuntime,\n useAttachment,\n };\n }, [useAttachmentRuntime, useAttachment]);\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 submitOnEnter?: boolean | undefined;\n cancelOnEscape?: 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 submitOnEnter = true,\n cancelOnEscape = true,\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 if (!cancelOnEscape) return;\n \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 || !submitOnEnter) 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, useMemo } from \"react\";\nimport { Attachment } from \"../../types\";\nimport { useComposer, useComposerRuntime } from \"../../context\";\nimport { useThreadComposerAttachment } from \"../../context/react/AttachmentContext\";\nimport { AttachmentRuntimeProvider } from \"../../context/providers/AttachmentRuntimeProvider\";\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: Attachment,\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 = useThreadComposerAttachment((a) =>\n getComponent(components, a),\n );\n\n if (!Component) return null;\n return <Component />;\n};\n\nconst ComposerAttachmentImpl: FC<\n ComposerPrimitiveAttachmentsProps & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n const composerRuntime = useComposerRuntime();\n const runtime = useMemo(\n () => composerRuntime.unstable_getAttachmentByIndex(attachmentIndex),\n [composerRuntime, attachmentIndex],\n );\n\n return (\n <AttachmentRuntimeProvider runtime={runtime}>\n <AttachmentComponent components={components} />\n </AttachmentRuntimeProvider>\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 = useComposer((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, 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, useMemo } from \"react\";\nimport { useThread, useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { MessageRuntimeProvider } from \"../../context/providers/MessageRuntimeProvider\";\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.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 const threadRuntime = useThreadRuntime();\n const runtime = useMemo(\n () => threadRuntime.unstable_getMesssageByIndex(messageIndex),\n [threadRuntime, messageIndex],\n );\n\n return (\n <MessageRuntimeProvider runtime={runtime}>\n <ThreadMessageComponent components={components} />\n </MessageRuntimeProvider>\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 = useThread((t) => t.messages.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 { MessageContext } from \"../react/MessageContext\";\nimport type { MessageContextValue } from \"../react/MessageContext\";\nimport { makeMessageUtilsStore } from \"../stores/MessageUtils\";\nimport { ReadonlyStore, writableStore } from \"../ReadonlyStore\";\nimport { MessageRuntime } from \"../../api\";\n\ntype MessageProviderProps = PropsWithChildren<{\n runtime: MessageRuntime;\n}>;\n\nconst useMessageRuntimeStore = (runtime: MessageRuntime) => {\n const [store] = useState(() => create(() => runtime));\n\n useEffect(() => {\n writableStore(store).setState(runtime, true);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useMessageStore = (runtime: MessageRuntime) => {\n const [store] = useState(() => create(() => runtime.getState()));\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.getState(), true);\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nconst useMessageUtilsStore = () => {\n const [store] = useState(() => makeMessageUtilsStore());\n return store;\n};\n\nconst useEditComposerStore = (\n useMessageRuntime: ReadonlyStore<MessageRuntime>,\n) => {\n const runtime = useMessageRuntime.getState().composer;\n const [store] = useState(() => create(() => runtime.getState()));\n\n useEffect(() => {\n const updateState = () => writableStore(store).setState(runtime.getState());\n updateState();\n return runtime.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const MessageRuntimeProvider: FC<MessageProviderProps> = ({\n runtime,\n children,\n}) => {\n const useMessageRuntime = useMessageRuntimeStore(runtime);\n const useMessage = useMessageStore(runtime);\n const useMessageUtils = useMessageUtilsStore();\n const useEditComposer = useEditComposerStore(useMessageRuntime);\n const [context] = useState<MessageContextValue>(() => {\n return { useMessageRuntime, useMessage, useMessageUtils, useEditComposer };\n });\n\n return (\n <MessageContext.Provider value={context}>\n {children}\n </MessageContext.Provider>\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","import { Unsubscribe } from \"../../types\";\nimport { AssistantRuntimeCore } from \"./AssistantRuntimeCore\";\n\n/**\n * @deprecated Use `runtime.thread.subscribe` instead. This will be removed in 0.6.0.\n */\nexport const subscribeToMainThread = (\n runtime: AssistantRuntimeCore,\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, useMemo, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntimeCore } from \"./LocalRuntimeCore\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\nimport { ThreadRuntime } from \"../../api/ThreadRuntime\";\n\nexport class LocalRuntime extends AssistantRuntime {\n constructor(private core: LocalRuntimeCore) {\n super(core, ThreadRuntime);\n }\n\n public reset(options?: Parameters<LocalRuntimeCore[\"reset\"]>[0]) {\n this.core.reset(options);\n }\n}\n\nexport const useLocalRuntime = (\n adapter: ChatModelAdapter,\n options: LocalRuntimeOptions = {},\n) => {\n const [runtime] = useState(() => new LocalRuntimeCore(adapter, options));\n\n useInsertionEffect(() => {\n runtime.thread.adapter = adapter;\n runtime.thread.options = options;\n });\n\n return useMemo(() => new LocalRuntime(runtime), [runtime]);\n};\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport type { AssistantRuntimeCore } from \"./AssistantRuntimeCore\";\nimport { ThreadRuntimeCore } from \"./ThreadRuntimeCore\";\n\nexport abstract class BaseAssistantRuntimeCore<\n TThreadRuntime extends ThreadRuntimeCore,\n> implements AssistantRuntimeCore\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 type { ThreadRuntimeCore } from \"./runtimes/core/ThreadRuntimeCore\";\nexport { DefaultThreadComposerRuntimeCore } from \"./runtimes/composer/DefaultThreadComposerRuntimeCore\";\nexport { ProxyConfigProvider } from \"./utils/ProxyConfigProvider\";\nexport { MessageRepository } from \"./runtimes/utils/MessageRepository\";\nexport { BaseAssistantRuntimeCore } from \"./runtimes/core/BaseAssistantRuntimeCore\";\nexport { TooltipIconButton } from \"./ui/base/tooltip-icon-button\";\nexport { generateId } from \"./utils/idUtils\";\nexport { AssistantRuntime } from \"./api/AssistantRuntime\";\nexport {\n ThreadRuntime,\n type ThreadRuntimeCoreBinding,\n} from \"./api/ThreadRuntime\";\n\nexport * from \"./utils/smooth\";\n","import {\n Attachment,\n CompleteAttachment,\n PendingAttachment,\n} from \"../../types/AttachmentTypes\";\nimport { AppendMessage, Unsubscribe } from \"../../types\";\nimport { AttachmentAdapter } from \"../attachment\";\nimport { ComposerRuntimeCore } from \"../core/ComposerRuntimeCore\";\n\nconst isAttachmentComplete = (a: Attachment): a is CompleteAttachment =>\n a.status.type === \"complete\";\n\nexport abstract class BaseComposerRuntimeCore implements ComposerRuntimeCore {\n public readonly isEditing = true;\n\n public attachmentAccept: string = \"*\";\n\n private _attachments: readonly Attachment[] = [];\n protected set attachments(value: readonly Attachment[]) {\n this._attachments = value;\n this.notifySubscribers();\n }\n public get attachments() {\n return this._attachments;\n }\n\n public abstract get canCancel(): boolean;\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\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(async (a) => {\n if (isAttachmentComplete(a)) return a;\n const result = await this._attachmentAdapter!.send(a);\n // TODO remove after 0.6.0\n if (result.status?.type !== \"complete\") {\n result.status = { type: \"complete\" };\n }\n return result as CompleteAttachment;\n }),\n )\n : [];\n\n const message: Omit<AppendMessage, \"parentId\"> = {\n role: \"user\",\n content: this.text ? [{ type: \"text\", text: this.text }] : [],\n attachments,\n };\n this.reset();\n\n this.handleSend(message);\n }\n public abstract handleSend(message: Omit<AppendMessage, \"parentId\">): void;\n public abstract cancel(): void;\n\n protected _attachmentAdapter?: AttachmentAdapter | undefined;\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 this.notifySubscribers();\n }\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 // TODO remove after 0.6.0\n if (attachment.status === undefined) {\n attachment.status = { type: \"requires-action\", reason: \"composer-send\" };\n }\n\n this._attachments = [...this._attachments, attachment as PendingAttachment];\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 _subscriptions = new Set<() => void>();\n protected 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","import { AppendMessage, PendingAttachment } from \"../../types\";\nimport { ThreadComposerRuntimeCore } from \"../core/ComposerRuntimeCore\";\nimport { ThreadRuntimeCore } from \"../core/ThreadRuntimeCore\";\nimport { BaseComposerRuntimeCore } from \"./BaseComposerRuntimeCore\";\n\nexport class DefaultThreadComposerRuntimeCore\n extends BaseComposerRuntimeCore\n implements ThreadComposerRuntimeCore\n{\n private _canCancel = false;\n public get canCancel() {\n return this._canCancel;\n }\n\n public override get attachments(): readonly PendingAttachment[] {\n return super.attachments as readonly PendingAttachment[];\n }\n\n constructor(private runtime: Omit<ThreadRuntimeCore, \"composer\">) {\n super();\n this.connect();\n }\n\n public connect() {\n return this.runtime.subscribe(() => {\n if (this.canCancel !== this.runtime.capabilities.cancel) {\n this._canCancel = this.runtime.capabilities.cancel;\n this.notifySubscribers();\n }\n });\n }\n\n public async handleSend(message: Omit<AppendMessage, \"parentId\">) {\n this.runtime.append({\n ...(message as AppendMessage),\n parentId: this.runtime.messages.at(-1)?.id ?? null,\n });\n }\n\n public async cancel() {\n this.runtime.cancelRun();\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 { generateId } from \"../../../internal\";\nimport {\n ThreadMessage,\n CoreMessage,\n ToolCallContentPart,\n MessageStatus,\n CompleteAttachment,\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 CompleteAttachment[],\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 { 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 { AssistantRuntimeCore } from \"../runtimes/core/AssistantRuntimeCore\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ModelConfigProvider } from \"../types/ModelConfigTypes\";\nimport { ThreadRuntime, ThreadRuntimeCoreBinding } from \"./ThreadRuntime\";\n\nexport class AssistantRuntime<\n TThreadRuntime extends ThreadRuntime = ThreadRuntime,\n> implements AssistantRuntimeCore\n{\n constructor(\n private _core: AssistantRuntimeCore,\n CustomThreadRuntime: new (\n binding: ThreadRuntimeCoreBinding,\n ) => TThreadRuntime,\n ) {\n this.thread = new CustomThreadRuntime(\n new NestedSubscriptionSubject({\n getState: () => this._core.thread,\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n );\n }\n\n public readonly thread;\n\n public switchToNewThread() {\n return this._core.switchToNewThread();\n }\n\n public switchToThread(threadId: string): void;\n /**\n * @deprecated Use `switchToNewThread` instead. This will be removed in 0.6.0.\n */\n public switchToThread(threadId: string | null): void;\n public switchToThread(threadId: string | null) {\n return this._core.switchToThread(threadId);\n }\n\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._core.registerModelConfigProvider(provider);\n }\n\n // TODO events for thread switching\n /**\n * @deprecated Thread is now static and never gets updated. This will be removed in 0.6.0.\n */\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n}\n","import {\n AddToolResultOptions,\n RuntimeCapabilities,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n} from \"../runtimes/core/ThreadRuntimeCore\";\nimport { ExportedMessageRepository } from \"../runtimes/utils/MessageRepository\";\nimport { AppendMessage, ThreadMessage } from \"../types\";\nimport { MessageRuntime, MessageState } from \"./MessageRuntime\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport { SubscribableWithState } from \"./subscribable/Subscribable\";\nimport { ThreadComposerRuntime } from \"./ComposerRuntime\";\nimport { LazyMemoizeSubject } from \"./subscribable/LazyMemoizeSubject\";\nimport { SKIP_UPDATE } from \"./subscribable/SKIP_UPDATE\";\n\nexport type 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 messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n parentId: messages.at(-1)?.id ?? null,\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n };\n }\n\n if (message.role && message.parentId && message.attachments) {\n return message as AppendMessage;\n }\n\n return {\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<ThreadRuntimeCore>;\n\nexport type ThreadState = Readonly<{\n threadId: string;\n isDisabled: boolean;\n isRunning: boolean;\n capabilities: RuntimeCapabilities;\n messages: readonly ThreadMessage[];\n}>;\n\nexport const getThreadState = (runtime: ThreadRuntimeCore): 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 messages: runtime.messages,\n });\n};\n\nexport class ThreadRuntime implements ThreadRuntimeCore {\n // public path = \"assistant.threads[main]\"; // TODO\n\n /**\n * @deprecated Use `getState().threadId` instead. This will be removed in 0.6.0.\n */\n public get threadId() {\n return this.getState().threadId;\n }\n\n /**\n * @deprecated Use `getState().isDisabled` instead. This will be removed in 0.6.0.\n */\n public get isDisabled() {\n return this.getState().isDisabled;\n }\n\n /**\n * @deprecated Use `getState().isRunning` instead. This will be removed in 0.6.0.\n */\n public get isRunning() {\n return this.getState().isRunning;\n }\n\n /**\n * @deprecated Use `getState().capabilities` instead. This will be removed in 0.6.0.\n */\n public get capabilities() {\n return this.getState().capabilities;\n }\n\n /**\n * @deprecated Use `getState().messages` instead. This will be removed in 0.6.0.\n */\n public get messages() {\n return this._threadBinding.getState().messages;\n }\n\n public unstable_getCore() {\n return this._threadBinding.getState();\n }\n\n private _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n constructor(threadBinding: ThreadRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n getState: () => getThreadState(threadBinding.getState()),\n subscribe: (callback) => threadBinding.subscribe(callback),\n });\n\n this._threadBinding = {\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n }\n\n public readonly composer = new ThreadComposerRuntime(\n new NestedSubscriptionSubject({\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n }\n\n public subscribe(callback: () => void) {\n return this._threadBinding.subscribe(callback);\n }\n\n // /**\n // * @derprecated Use `getMesssageById(id).getState().branchNumber` / `getMesssageById(id).getState().branchCount` instead. This will be removed in 0.6.0.\n // */\n public getBranches(messageId: string) {\n return this._threadBinding.getState().getBranches(messageId);\n }\n\n public getModelConfig() {\n return this._threadBinding.getState().getModelConfig();\n }\n\n // TODO sometimes you want to continue when there is no child message\n public startRun(parentId: string | null) {\n return this._threadBinding.getState().startRun(parentId);\n }\n\n // TODO\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n // /**\n // * @deprecated Use `getMesssageById(id).getContentPartByToolCallId(toolCallId).addToolResult({ result })` instead. This will be removed in 0.6.0.\n // */\n public addToolResult(options: AddToolResultOptions) {\n this._threadBinding.getState().addToolResult(options);\n }\n\n // TODO\n public switchToBranch(branchId: string) {\n return this._threadBinding.getState().switchToBranch(branchId);\n }\n\n // /**\n // * @deprecated Use `getMesssageById(id).speak()` instead. This will be removed in 0.6.0.\n // */\n public speak(messageId: string) {\n return this._threadBinding.getState().speak(messageId);\n }\n\n // /**\n // * @deprecated Use `getMesssageById(id).submitFeedback({ type })` instead. This will be removed in 0.6.0.\n // */\n public submitFeedback(options: SubmitFeedbackOptions) {\n return this._threadBinding.getState().submitFeedback(options);\n }\n\n /**\n * @deprecated Use `getMesssageById(id).unstable_getMessageByIndex(idx).composer` instead. This will be removed in 0.6.0.\n */\n public getEditComposer(messageId: string) {\n return this._threadBinding.getState().getEditComposer(messageId);\n }\n\n /**\n * @deprecated Use `getMesssageById(id).unstable_getMessageByIndex(idx).composer.beginEdit()` instead. This will be removed in 0.6.0.\n */\n public beginEdit(messageId: string) {\n return this._threadBinding.getState().beginEdit(messageId);\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public unstable_getMesssageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return new MessageRuntime(\n new ShallowMemoizeSubject({\n getState: () => {\n const messages = this.getState().messages;\n const message = messages[idx];\n if (!message) return SKIP_UPDATE;\n\n const branches = this._threadBinding\n .getState()\n .getBranches(message.id);\n\n return {\n ...message,\n\n message,\n isLast: idx === messages.length - 1,\n parentId: messages[idx - 1]?.id ?? null,\n\n branches,\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n}\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 case \"file\": {\n // TODO\n throw new Error(\"File content parts are not 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 { AppendMessage, ThreadMessage } from \"../../types\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { ThreadRuntimeCore } from \"../core/ThreadRuntimeCore\";\nimport { BaseComposerRuntimeCore } from \"./BaseComposerRuntimeCore\";\n\nexport class DefaultEditComposerRuntimeCore extends BaseComposerRuntimeCore {\n public get canCancel() {\n return true;\n }\n\n private _nonTextParts;\n private _previousText;\n private _parentId;\n constructor(\n private runtime: Omit<ThreadRuntimeCore, \"composer\">,\n private endEditCallback: () => void,\n { parentId, message }: { parentId: string | null; message: ThreadMessage },\n ) {\n super();\n this._parentId = parentId;\n this._previousText = getThreadMessageText(message);\n this.setText(this._previousText);\n\n this._nonTextParts = message.content.filter(\n (part) => part.type !== \"text\" && part.type !== \"ui\",\n );\n\n // TODO differentiate between \"sent\" and \"pending\" attachments instead of Composer/Message Attachments\n // this.attachments = message.attachments ?? [];\n }\n\n public async handleSend(message: Omit<AppendMessage, \"parentId\">) {\n const text = getThreadMessageText(message as AppendMessage);\n if (text !== this._previousText) {\n this.runtime.append({\n ...(message as AppendMessage),\n content: [...message.content, ...this._nonTextParts] as any,\n parentId: this._parentId,\n });\n }\n\n this.endEditCallback();\n this.notifySubscribers();\n }\n\n public async cancel() {\n this.endEditCallback();\n this.notifySubscribers();\n }\n}\n","import { 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 { DefaultThreadComposerRuntimeCore } from \"../composer/DefaultThreadComposerRuntimeCore\";\nimport { shouldContinue } from \"./shouldContinue\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { SpeechSynthesisAdapter } from \"../speech\";\nimport {\n AddToolResultOptions,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n} from \"../core/ThreadRuntimeCore\";\nimport { DefaultEditComposerRuntimeCore } from \"../composer/DefaultEditComposerRuntimeCore\";\n\nexport class LocalThreadRuntimeCore implements ThreadRuntimeCore {\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 DefaultThreadComposerRuntimeCore(this);\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 private _editComposers = new Map<string, DefaultEditComposerRuntimeCore>();\n public getEditComposer(messageId: string) {\n return this._editComposers.get(messageId);\n }\n public beginEdit(messageId: string) {\n if (this._editComposers.has(messageId))\n throw new Error(\"Edit already in progress\");\n\n this._editComposers.set(\n messageId,\n new DefaultEditComposerRuntimeCore(\n this,\n () => this._editComposers.delete(messageId),\n this.repository.getMessage(messageId),\n ),\n );\n 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 { BaseAssistantRuntimeCore } from \"../core/BaseAssistantRuntimeCore\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { ProxyConfigProvider } from \"../../internal\";\nimport { LocalThreadRuntimeCore } from \"./LocalThreadRuntimeCore\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport { fromCoreMessages } from \"../edge/converters/fromCoreMessage\";\n\nexport class LocalRuntimeCore extends BaseAssistantRuntimeCore<LocalThreadRuntimeCore> {\n private readonly _proxyConfigProvider: ProxyConfigProvider;\n\n constructor(adapter: ChatModelAdapter, options: LocalRuntimeOptions) {\n const proxyConfigProvider = new ProxyConfigProvider();\n super(new LocalThreadRuntimeCore(proxyConfigProvider, adapter, options));\n this._proxyConfigProvider = proxyConfigProvider;\n }\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n\n public switchToNewThread() {\n const { initialMessages, ...options } = this.thread.options;\n\n this.thread = new LocalThreadRuntimeCore(\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 { useEffect, useMemo, useState } from \"react\";\nimport { ExternalStoreRuntimeCore } from \"./ExternalStoreRuntimeCore\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { AssistantRuntime } from \"../../api/AssistantRuntime\";\nimport { ThreadRuntime } from \"../../api/ThreadRuntime\";\n\nexport const useExternalStoreRuntime = <T,>(store: ExternalStoreAdapter<T>) => {\n const [runtime] = useState(() => new ExternalStoreRuntimeCore(store));\n\n useEffect(() => {\n runtime.thread.store = store;\n });\n\n return useMemo(() => new AssistantRuntime(runtime, ThreadRuntime), [runtime]);\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 {\n MessageStatus,\n TextContentPart,\n ImageContentPart,\n ToolCallContentPart,\n UIContentPart,\n ThreadMessage,\n ThreadAssistantContentPart,\n ThreadAssistantMessage,\n ThreadUserContentPart,\n ThreadUserMessage,\n ThreadSystemMessage,\n CompleteAttachment,\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?: CompleteAttachment[] | 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 { AddToolResultOptions } from \"../core\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/MessageRepository\";\nimport {\n AppendMessage,\n ModelConfigProvider,\n ThreadMessage,\n Unsubscribe,\n} from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport {\n getExternalStoreMessage,\n symbolInnerMessage,\n} from \"./getExternalStoreMessage\";\nimport { ThreadMessageConverter } from \"./ThreadMessageConverter\";\nimport { getAutoStatus, isAutoStatus } from \"./auto-status\";\nimport { fromThreadMessageLike } from \"./ThreadMessageLike\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\nimport { generateId } from \"../../internal\";\nimport { DefaultThreadComposerRuntimeCore } from \"../composer/DefaultThreadComposerRuntimeCore\";\nimport {\n RuntimeCapabilities,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n} from \"../core/ThreadRuntimeCore\";\nimport { DefaultEditComposerRuntimeCore } from \"../composer/DefaultEditComposerRuntimeCore\";\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore implements ThreadRuntimeCore {\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 DefaultThreadComposerRuntimeCore(this);\n private _editComposers = new Map<string, DefaultEditComposerRuntimeCore>();\n public getEditComposer(messageId: string) {\n return this._editComposers.get(messageId);\n }\n public beginEdit(messageId: string) {\n if (this._editComposers.has(messageId))\n throw new Error(\"Edit already in progress\");\n\n this._editComposers.set(\n messageId,\n new DefaultEditComposerRuntimeCore(\n this,\n () => this._editComposers.delete(messageId),\n this.repository.getMessage(messageId),\n ),\n );\n this.notifySubscribers();\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 public import(repository: ExportedMessageRepository) {\n this.repository.import(repository);\n }\n\n public export(): ExportedMessageRepository {\n return this.repository.export();\n }\n}\n","import { BaseAssistantRuntimeCore, ProxyConfigProvider } from \"../../internal\";\nimport { ModelConfigProvider } from \"../../types\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { ExternalStoreThreadRuntimeCore } from \"./ExternalStoreThreadRuntimeCore\";\n\nexport class ExternalStoreRuntimeCore extends BaseAssistantRuntimeCore<ExternalStoreThreadRuntimeCore> {\n private readonly _proxyConfigProvider;\n\n constructor(store: ExternalStoreAdapter<any>) {\n const provider = new ProxyConfigProvider();\n super(new ExternalStoreThreadRuntimeCore(provider, store));\n this._proxyConfigProvider = provider;\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.thread.store.onSwitchToNewThread)\n throw new Error(\"Runtime does not support switching to new threads.\");\n\n this.thread = new ExternalStoreThreadRuntimeCore(\n this._proxyConfigProvider,\n {\n ...this.thread.store,\n messages: [],\n },\n );\n await this.thread.store.onSwitchToNewThread!();\n }\n\n public async switchToThread(threadId: string | null) {\n if (threadId !== null) {\n if (!this.thread.store.onSwitchToThread)\n throw new Error(\"Runtime does not support switching threads.\");\n\n this.thread = new ExternalStoreThreadRuntimeCore(\n this._proxyConfigProvider,\n {\n ...this.thread.store,\n messages: [], // ignore messages until rerender\n },\n );\n this.thread.store.onSwitchToThread!(threadId);\n } else {\n this.switchToNewThread();\n }\n }\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 role = output.role;\n switch (role) {\n case \"system\":\n case \"user\":\n return output;\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(...output.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 PendingAttachment,\n CompleteAttachment,\n} from \"../../types/AttachmentTypes\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nexport class SimpleImageAttachmentAdapter implements AttachmentAdapter {\n public accept = \"image/*\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: state.file.name,\n type: \"image\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\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 CompleteAttachment,\n PendingAttachment,\n} from \"../../types/AttachmentTypes\";\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<PendingAttachment> {\n return {\n id: state.file.name,\n type: \"document\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\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 { Attachment, PendingAttachment } from \"../../types/AttachmentTypes\";\nimport { AttachmentAdapter } from \"./AttachmentAdapter\";\n\nfunction fileMatchesAccept(\n file: { name: string; type: string },\n acceptString: string,\n) {\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 }) {\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(attachment: PendingAttachment) {\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: Attachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (\n fileMatchesAccept(\n {\n name: attachment.name,\n type: attachment.contentType ?? \"unknown/unknown\", // TODO remove after 0.6.0\n },\n adapter.accept,\n )\n ) {\n return adapter.remove(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n}\n","\"use client\";\n\nimport {\n ComponentType,\n FC,\n PropsWithChildren,\n ReactNode,\n createContext,\n useContext,\n} from \"react\";\n\nimport { AssistantRuntime } from \"../api/AssistantRuntime\";\nimport { AvatarProps } from \"./base/avatar\";\nimport { TextContentPartComponent, ToolCallContentPartProps } from \"../types\";\nimport { AssistantRuntimeProvider } from \"../context\";\nimport { AssistantToolUI } from \"../model-config\";\nimport { useAssistantRuntime } 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 = !!useAssistantRuntime({ 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(true);\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\";\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 {\n useAttachmentRuntime,\n useThreadComposerAttachment,\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 = useThreadComposerAttachment((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 attachmentRuntime = useAttachmentRuntime();\n const handleRemoveAttachment = () => {\n attachmentRuntime.remove();\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"]}