@assistant-ui/react 0.5.83 → 0.5.85

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/primitive-hooks/actionBar/useActionBarEdit.tsx","../src/primitive-hooks/actionBar/useActionBarReload.tsx","../src/utils/combined/useCombinedStore.ts","../src/utils/combined/createCombinedStore.ts","../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/primitives/assistantModal/scope.tsx","../src/primitives/assistantModal/AssistantModalTrigger.tsx","../src/primitives/assistantModal/AssistantModalContent.tsx","../src/primitives/assistantModal/AssistantModalAnchor.tsx","../src/primitives/attachment/index.ts","../src/primitives/attachment/AttachmentRoot.tsx","../src/primitives/attachment/AttachmentThumb.tsx","../src/context/react/AttachmentContext.ts","../src/primitives/attachment/AttachmentName.tsx","../src/primitive-hooks/attachment/useAttachmentRemove.ts","../src/primitives/attachment/AttachmentRemove.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/utils/getThreadMessageText.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/providers/AttachmentRuntimeProvider.tsx","../src/primitives/composer/index.ts","../src/primitives/composer/ComposerRoot.tsx","../src/primitives/composer/ComposerInput.tsx","../src/utils/hooks/useOnScrollToBottom.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/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/utils/ProxyConfigProvider.ts","../src/runtimes/core/BaseAssistantRuntimeCore.tsx","../src/internal.ts","../src/runtimes/composer/BaseComposerRuntimeCore.tsx","../src/runtimes/composer/DefaultThreadComposerRuntimeCore.tsx","../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/ThreadRuntime.ts","../src/api/ThreadManagerRuntime.ts","../src/api/AssistantRuntime.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/LocalRuntimeOptions.tsx","../src/runtimes/local/shouldContinue.tsx","../src/runtimes/composer/DefaultEditComposerRuntimeCore.tsx","../src/runtimes/core/BaseThreadRuntimeCore.tsx","../src/runtimes/local/LocalThreadRuntimeCore.tsx","../src/runtimes/local/LocalThreadManagerRuntimeCore.tsx","../src/runtimes/local/LocalRuntimeCore.tsx","../src/runtimes/external-store/useExternalStoreRuntime.tsx","../src/runtimes/external-store/ExternalStoreThreadManagementAdapter.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/attachment.tsx","../src/ui/base/dialog.tsx","../src/ui/thread-welcome.tsx","../src/ui/user-message.tsx","../src/ui/user-action-bar.tsx","../src/ui/edit-composer.tsx"],"names":["actions","useThreadRuntimeStore","useEffect","useThreadStore","useThreadMessagesStore","useThreadComposerStore","useThread","useAssistantRuntimeStore","useAssistantRuntime","useEditComposer","Primitive","useContentPartStore","COMPLETE_STATUS","useAttachmentRuntime","useEscapeKeydown","getComponent","AttachmentComponent","useMessageStore","useMessageUtilsStore","useEditComposerStore","messages","subscribers","EMPTY_ARRAY","exports"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;ACbA,2EAAmD;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,SA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MA;AACJ,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAEO;AjLq2MD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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\nconst useThreadManagerStore = (runtime: AssistantRuntime) => {\n const [store] = useState(() =>\n create(() => runtime.threadManager.getState()),\n );\n\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.threadManager.getState(), true);\n updateState();\n return runtime.threadManager.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const AssistantRuntimeProviderImpl: FC<\n PropsWithChildren<AssistantRuntimeProviderProps>\n> = ({ children, runtime }) => {\n const useAssistantRuntime = useAssistantRuntimeStore(runtime);\n const useToolUIs = useAssistantToolUIsStore();\n const useThreadManager = useThreadManagerStore(runtime);\n const context = useMemo(() => {\n return {\n useToolUIs,\n useAssistantRuntime,\n useAssistantActions: useAssistantRuntime,\n useThreadManager,\n };\n }, [useAssistantRuntime, useToolUIs, useThreadManager]);\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\";\nimport { ThreadManagerState } from \"../../api/ThreadManagerRuntime\";\n\nexport type AssistantContextValue = {\n useToolUIs: UseBoundStore<ReadonlyStore<AssistantToolUIsState>>;\n useAssistantRuntime: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n useThreadManager: UseBoundStore<ReadonlyStore<ThreadManagerState>>;\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\nexport const { useThreadManager } = createContextStoreHook(\n useAssistantContext,\n \"useThreadManager\",\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, useEffect, useState } 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 { ModelConfig, 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\nexport function useThreadModelConfig(options?: {\n optional?: false | undefined;\n}): ModelConfig;\nexport function useThreadModelConfig(options?: {\n optional?: boolean | undefined;\n}): ModelConfig | null;\nexport function useThreadModelConfig(options?: {\n optional?: boolean | undefined;\n}): ModelConfig | null {\n const [, rerender] = useState({});\n\n const runtime = useThreadRuntime(options);\n useEffect(() => {\n return runtime?.unstable_on(\"model-config-update\", () => rerender({}));\n }, [runtime]);\n\n if (!runtime) return null;\n return runtime?.getModelConfig();\n}\n","\"use client\";\nimport { create } from \"zustand\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\n\nexport type ThreadViewportState = Readonly<{\n isAtBottom: boolean;\n scrollToBottom: () => void;\n onScrollToBottom: (callback: () => void) => Unsubscribe;\n}>;\n\nexport const makeThreadViewportStore = () => {\n const scrollToBottomListeners = new Set<() => void>();\n\n return create<ThreadViewportState>(() => ({\n isAtBottom: true,\n scrollToBottom: () => {\n for (const listener of scrollToBottomListeners) {\n listener();\n }\n },\n onScrollToBottom: (callback) => {\n scrollToBottomListeners.add(callback);\n return () => {\n scrollToBottomListeners.delete(callback);\n };\n },\n }));\n};\n","import 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 ContentPartRuntimeImpl,\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 ContentPartRuntimeImpl(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() as ContentPartState & {\n type: \"text\";\n };\n\n const textUpdated = (state as TextContentPart).text !== text;\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 type: \"text\",\n text,\n part: { type: \"text\", text },\n status: targetStatus,\n } satisfies ContentPartState,\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\";\nimport { Unsubscribe } from \"../types\";\nimport { ContentPartRuntimePath } from \"./RuntimePathTypes\";\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<\n ContentPartState,\n ContentPartRuntimePath\n>;\n\nexport type ContentPartRuntime = {\n path: ContentPartRuntimePath;\n\n getState(): ContentPartState;\n addToolResult(result: any): void;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport class ContentPartRuntimeImpl implements ContentPartRuntime {\n public get path() {\n return this.contentBinding.path;\n }\n\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 { useThreadRuntime } from \"../context/react/ThreadContext\";\nimport { CreateAppendMessage } from \"../api/ThreadRuntime\";\n\n/**\n * @deprecated Use `useThreadRuntime().append()` instead. This will be removed in 0.6.\n */\nexport const useAppendMessage = () => {\n const threadRuntime = useThreadRuntime();\n\n const append = useCallback(\n (message: CreateAppendMessage) => {\n threadRuntime.append(message);\n },\n [threadRuntime],\n );\n\n return append;\n};\n","import { useCallback } from \"react\";\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 switchToNewThread = useCallback(() => {\n assistantRuntime.switchToNewThread();\n }, [assistantRuntime]);\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 useMessage,\n useMessageRuntime,\n useMessageUtils,\n} from \"../../context/react/MessageContext\";\nimport { useComposerRuntime } from \"../../context\";\n\nexport type UseActionBarCopyProps = {\n copiedDuration?: number | undefined;\n};\n\nexport const useActionBarCopy = ({\n copiedDuration = 3000,\n}: UseActionBarCopyProps = {}) => {\n const messageRuntime = useMessageRuntime();\n const composerRuntime = useComposerRuntime();\n const setIsCopied = useMessageUtils((s) => s.setIsCopied);\n const hasCopyableContent = useMessage((message) => {\n return (\n (message.role !== \"assistant\" || message.status.type !== \"running\") &&\n message.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n });\n\n const callback = useCallback(() => {\n const { isEditing, text: composerValue } = composerRuntime.getState();\n\n const valueToCopy = isEditing\n ? composerValue\n : messageRuntime.unstable_getCopyText();\n\n navigator.clipboard.writeText(valueToCopy).then(() => {\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), copiedDuration);\n });\n }, [messageRuntime, setIsCopied, composerRuntime, copiedDuration]);\n\n if (!hasCopyableContent) return null;\n return callback;\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 { useMessageRuntime } from \"../../context/react/MessageContext\";\nimport { useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useActionBarReload = () => {\n const messageRuntime = useMessageRuntime();\n const threadRuntime = useThreadRuntime();\n\n const disabled = useCombinedStore(\n [threadRuntime, messageRuntime],\n (t, m) => t.isRunning || t.isDisabled || m.role !== \"assistant\",\n );\n\n const callback = useCallback(() => {\n messageRuntime.reload();\n }, [messageRuntime]);\n\n if (disabled) 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 { useCallback } from \"react\";\n\nimport { useMessage, useMessageRuntime } from \"../../context\";\n\nexport const useActionBarSpeak = () => {\n const messageRunime = useMessageRuntime();\n const callback = useCallback(async () => {\n messageRunime.speak();\n }, [messageRunime]);\n\n const hasSpeakableContent = useMessage((m) => {\n return (\n (m.role !== \"assistant\" || m.status.type !== \"running\") &&\n m.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n });\n\n if (!hasSpeakableContent) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport {\n useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\n\nexport const useActionBarStopSpeaking = () => {\n const messageRuntime = useMessageRuntime();\n const isSpeaking = useMessage((u) => u.speech != null);\n\n const callback = useCallback(async () => {\n messageRuntime.stopSpeaking();\n }, [messageRuntime]);\n\n if (!isSpeaking) return null;\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageRuntime } from \"../../context\";\n\nexport const useActionBarFeedbackPositive = () => {\n const messageRuntime = useMessageRuntime();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({ type: \"positive\" });\n }, [messageRuntime]);\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageRuntime } from \"../../context\";\n\nexport const useActionBarFeedbackNegative = () => {\n const messageRuntime = useMessageRuntime();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({ type: \"negative\" });\n }, [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 {\n useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerNext = () => {\n const messageRuntime = useMessageRuntime();\n const disabled = useMessage((m) => m.branchNumber >= m.branchCount);\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 useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerPrevious = () => {\n const messageRuntime = useMessageRuntime();\n const disabled = useMessage((m) => m.branchNumber <= 1);\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, useComposerRuntime } from \"../../context\";\n\nexport const useComposerCancel = () => {\n const composerRuntime = useComposerRuntime();\n const disabled = useComposer((c) => !c.canCancel);\n\n const callback = useCallback(() => {\n composerRuntime.cancel();\n }, [composerRuntime]);\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 { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport { useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { useComposerRuntime } from \"../../context\";\n\nexport const useComposerSend = () => {\n const composerRuntime = useComposerRuntime();\n const threadRuntime = useThreadRuntime();\n\n const disabled = useCombinedStore(\n [threadRuntime, composerRuntime],\n (t, c) => t.isRunning || !c.isEditing || c.isEmpty,\n );\n\n const callback = useCallback(() => {\n if (!composerRuntime.getState().isEditing) return;\n\n composerRuntime.send();\n }, [threadRuntime]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useComposer, useComposerRuntime } from \"../../context\";\n\nexport const useComposerAddAttachment = () => {\n const disabled = useComposer((c) => !c.isEditing);\n\n const composerRuntime = useComposerRuntime();\n const callback = useCallback(() => {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n\n const attachmentAccept = composerRuntime.getAttachmentAccept();\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 composerRuntime.addAttachment(file);\n };\n\n input.click();\n }, [composerRuntime]);\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 & { part: 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 &\n ImageContentPart & { part: 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 & { part: TextContentPart };\n });\n\n return text;\n};\n","\"use client\";\nimport {\n useMessageRuntime,\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 hasContent: boolean | undefined;\n submittedFeedback: \"positive\" | \"negative\" | null | undefined;\n};\nexport type UseMessageIfProps = RequireAtLeastOne<MessageIfFilters>;\n\nexport const useMessageIf = (props: UseMessageIfProps) => {\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [messageRuntime, messageUtilsStore],\n (\n {\n role,\n attachments,\n content,\n branchCount,\n isLast,\n speech,\n submittedFeedback,\n },\n { isCopied, isHovering },\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 && speech == null) return false;\n if (props.speaking === false && speech != null) 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 (props.hasContent === true && content.length === 0) return false;\n if (props.hasContent === false && content.length > 0) return false;\n\n if (\n props.submittedFeedback !== undefined &&\n (submittedFeedback?.type ?? null) !== 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 { useThreadViewportStore } from \"../../context/react/ThreadContext\";\n\nexport const useThreadScrollToBottom = () => {\n const isAtBottom = useThreadViewport((s) => s.isAtBottom);\n\n const threadViewportStore = useThreadViewportStore();\n\n const handleScrollToBottom = useCallback(() => {\n threadViewportStore.getState().scrollToBottom();\n }, [threadViewportStore]);\n\n if (isAtBottom) return null;\n return handleScrollToBottom;\n};\n","import { useCallback } from \"react\";\nimport { useThread } from \"../../context\";\nimport { useThreadRuntime } 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 threadRuntime = useThreadRuntime();\n\n const disabled = useThread((t) => t.isDisabled);\n const callback = useCallback(() => {\n if (autoSend && !threadRuntime.getState().isRunning) {\n threadRuntime.append(prompt);\n threadRuntime.composer.setText(\"\");\n } else {\n threadRuntime.composer.setText(prompt);\n }\n }, [threadRuntime, autoSend, 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 PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\n/**\n * @deprecated Use `ActionBarPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveRootProps = ActionBarPrimitiveRoot.Props;\n\nexport namespace ActionBarPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = PrimitiveDivProps & UseActionBarFloatStatusProps;\n}\n\nexport const ActionBarPrimitiveRoot = forwardRef<\n ActionBarPrimitiveRoot.Element,\n ActionBarPrimitiveRoot.Props\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 useMessageRuntime,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport { useThreadRuntime } 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 threadRuntime = useThreadRuntime();\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [threadRuntime, messageRuntime, 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.branchCount <= 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\n/**\n * @deprecated Use `ActionBarPrimitive.Copy.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveCopyProps = ActionBarPrimitiveCopy.Props;\n\nexport namespace ActionBarPrimitiveCopy {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarCopy>;\n}\n\nexport const ActionBarPrimitiveCopy = forwardRef<\n ActionBarPrimitiveCopy.Element,\n ActionBarPrimitiveCopy.Props\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 PrimitiveButtonProps = ComponentPropsWithoutRef<typeof Primitive.button>;\n\nexport type ActionButtonProps<THook> = PrimitiveButtonProps &\n (THook extends (props: infer TProps) => unknown ? TProps : never);\n\nexport type ActionButtonElement = ElementRef<typeof Primitive.button>;\n\nexport const createActionButton = <TProps,>(\n displayName: string,\n useActionButton: ActionButtonCallback<TProps>,\n forwardProps: (keyof NonNullable<TProps>)[] = [],\n) => {\n const ActionButton = forwardRef<\n ActionButtonElement,\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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.Reload.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveReloadProps = ActionBarPrimitiveReload.Props;\n\nexport namespace ActionBarPrimitiveReload {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.Edit.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveEditProps = ActionBarPrimitiveEdit.Props;\n\nexport namespace ActionBarPrimitiveEdit {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.Speak.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveSpeakProps = ActionBarPrimitiveSpeak.Props;\n\nexport namespace ActionBarPrimitiveSpeak {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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\n/**\n * @deprecated Use `ActionBarPrimitive.StopSpeaking.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveStopSpeakingProps =\n ActionBarPrimitiveStopSpeaking.Props;\n\nexport namespace ActionBarPrimitiveStopSpeaking {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarStopSpeaking>;\n}\n\nexport const ActionBarPrimitiveStopSpeaking = forwardRef<\n ActionBarPrimitiveStopSpeaking.Element,\n ActionBarPrimitiveStopSpeaking.Props\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 { useMessage } from \"../../context\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.FeedbackPositive.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveFeedbackPositiveProps =\n ActionBarPrimitiveFeedbackPositive.Props;\n\nexport namespace ActionBarPrimitiveFeedbackPositive {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarFeedbackPositive>;\n}\n\nexport const ActionBarPrimitiveFeedbackPositive = forwardRef<\n ActionBarPrimitiveFeedbackPositive.Element,\n ActionBarPrimitiveFeedbackPositive.Props\n>(({ onClick, disabled, ...props }, forwardedRef) => {\n const isSubmitted = useMessage(\n (u) => u.submittedFeedback?.type === \"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 { useMessage } from \"../../context\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.FeedbackNegative.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveFeedbackNegativeProps =\n ActionBarPrimitiveFeedbackNegative.Props;\n\nexport namespace ActionBarPrimitiveFeedbackNegative {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarFeedbackNegative>;\n}\n\nexport const ActionBarPrimitiveFeedbackNegative = forwardRef<\n ActionBarPrimitiveFeedbackNegative.Element,\n ActionBarPrimitiveFeedbackNegative.Props\n>(({ onClick, disabled, ...props }, forwardedRef) => {\n const isSubmitted = useMessage(\n (u) => u.submittedFeedback?.type === \"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, useEffect, useState } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\nimport { useThreadRuntime } from \"../../context\";\n\n/**\n * @deprecated Use `AssistantModalPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantModalPrimitiveRootProps =\n AssistantModalPrimitiveRoot.Props;\n\nexport namespace AssistantModalPrimitiveRoot {\n export type Props = PopoverPrimitive.PopoverProps & {\n unstable_openOnRunStart?: boolean | undefined;\n };\n}\n\nconst useAssistantModalOpenState = ({\n defaultOpen = false,\n unstable_openOnRunStart = true,\n}: {\n defaultOpen?: boolean | undefined;\n unstable_openOnRunStart?: boolean | undefined;\n}) => {\n const state = useState(defaultOpen);\n\n const [, setOpen] = state;\n const threadRuntime = useThreadRuntime();\n useEffect(() => {\n if (!unstable_openOnRunStart) return undefined;\n\n return threadRuntime.unstable_on(\"run-start\", () => {\n setOpen(true);\n });\n }, [unstable_openOnRunStart]);\n\n return state;\n};\n\nexport const AssistantModalPrimitiveRoot: FC<\n AssistantModalPrimitiveRoot.Props\n> = ({\n __scopeAssistantModal,\n defaultOpen,\n unstable_openOnRunStart,\n open,\n onOpenChange,\n ...rest\n}: ScopedProps<AssistantModalPrimitiveRoot.Props>) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n const [modalOpen, setOpen] = useAssistantModalOpenState({\n defaultOpen,\n unstable_openOnRunStart,\n });\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 * 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\n/**\n * @deprecated Use `AssistantModalPrimitive.Trigger.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantModalPrimitiveTriggerProps =\n AssistantModalPrimitiveTrigger.Props;\n\nexport namespace AssistantModalPrimitiveTrigger {\n export type Element = ElementRef<typeof PopoverPrimitive.Trigger>;\n export type Props = ComponentPropsWithoutRef<typeof PopoverPrimitive.Trigger>;\n}\n\nexport const AssistantModalPrimitiveTrigger = forwardRef<\n AssistantModalPrimitiveTrigger.Element,\n AssistantModalPrimitiveTrigger.Props\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveTrigger.Props>,\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\n/**\n * @deprecated Use `AssistantModalPrimitive.Content.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantModalPrimitiveContentProps =\n AssistantModalPrimitiveContent.Props;\n\nexport namespace AssistantModalPrimitiveContent {\n export type Element = ElementRef<typeof PopoverPrimitive.Content>;\n export type Props = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Content\n > & {\n dissmissOnInteractOutside?: boolean | undefined;\n };\n}\n\nexport const AssistantModalPrimitiveContent = forwardRef<\n AssistantModalPrimitiveContent.Element,\n AssistantModalPrimitiveContent.Props\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\nexport namespace AssistantModalPrimitiveAnchor {\n export type Element = ElementRef<typeof PopoverPrimitive.Anchor>;\n export type Props = ComponentPropsWithoutRef<typeof PopoverPrimitive.Anchor>;\n}\n\nexport const AssistantModalPrimitiveAnchor = forwardRef<\n AssistantModalPrimitiveAnchor.Element,\n AssistantModalPrimitiveAnchor.Props\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveAnchor.Props>,\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 { AttachmentPrimitiveRoot as Root } from \"./AttachmentRoot\";\nexport { AttachmentPrimitiveThumb as unstable_Thumb } from \"./AttachmentThumb\";\nexport { AttachmentPrimitiveName as Name } from \"./AttachmentName\";\nexport { AttachmentPrimitiveRemove as Remove } from \"./AttachmentRemove\";\n","import { Primitive } from \"@radix-ui/react-primitive\";\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\n\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport namespace AttachmentPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = PrimitiveDivProps;\n}\n\nexport const AttachmentPrimitiveRoot = forwardRef<\n AttachmentPrimitiveRoot.Element,\n AttachmentPrimitiveRoot.Props\n>((props, ref) => {\n return <Primitive.div {...props} ref={ref} />;\n});\n\nAttachmentPrimitiveRoot.displayName = \"AttachmentPrimitive.Root\";\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type ElementRef } from \"react\";\nimport { useAttachment } from \"../../context/react/AttachmentContext\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport namespace AttachmentPrimitiveThumb {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = PrimitiveDivProps;\n}\n\nexport const AttachmentPrimitiveThumb = forwardRef<\n AttachmentPrimitiveThumb.Element,\n AttachmentPrimitiveThumb.Props\n>((props, ref) => {\n const ext = useAttachment((a) => a.name.split(\".\").pop());\n return (\n <Primitive.div {...props} ref={ref}>\n .{ext}\n </Primitive.div>\n );\n});\n\nAttachmentPrimitiveThumb.displayName = \"AttachmentPrimitive.Thumb\";\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 type { FC } from \"react\";\nimport { useAttachment } from \"../../context/react/AttachmentContext\";\n\nexport namespace AttachmentPrimitiveName {\n export type Props = Record<string, never>;\n}\n\nexport const AttachmentPrimitiveName: FC<\n AttachmentPrimitiveName.Props\n> = () => {\n const name = useAttachment((a) => a.name);\n return <>{name}</>;\n};\n\nAttachmentPrimitiveName.displayName = \"AttachmentPrimitive.Name\";\n","import { useCallback } from \"react\";\nimport { useAttachmentRuntime } from \"../../context/react/AttachmentContext\";\n\nexport const useAttachmentRemove = () => {\n const attachmentRuntime = useAttachmentRuntime();\n\n const handleRemoveAttachment = useCallback(() => {\n attachmentRuntime.remove();\n }, [attachmentRuntime]);\n\n return handleRemoveAttachment;\n};\n","\"use client\";\n\nimport { useAttachmentRemove } from \"../../primitive-hooks/attachment/useAttachmentRemove\";\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport namespace AttachmentPrimitiveRemove {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useAttachmentRemove>;\n}\n\nexport const AttachmentPrimitiveRemove = createActionButton(\n \"AttachmentPrimitive.Remove\",\n useAttachmentRemove,\n);\n","export { BranchPickerPrimitiveNext as Next } from \"./BranchPickerNext\";\nexport { BranchPickerPrimitivePrevious as Previous } from \"./BranchPickerPrevious\";\nexport { BranchPickerPrimitiveCount as Count } from \"./BranchPickerCount\";\nexport { BranchPickerPrimitiveNumber as Number } from \"./BranchPickerNumber\";\nexport { BranchPickerPrimitiveRoot as Root } from \"./BranchPickerRoot\";\n","\n\"use client\";\n\nimport { useBranchPickerNext } from \"../../primitive-hooks/branchPicker/useBranchPickerNext\";\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `BranchPickerPrimitive.Next.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveNextProps = BranchPickerPrimitiveNext.Props;\n\nexport namespace BranchPickerPrimitiveNext {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `BranchPickerPrimitive.Previous.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitivePreviousProps = BranchPickerPrimitivePrevious.Props;\n\nexport namespace BranchPickerPrimitivePrevious {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useBranchPickerPrevious>;\n}\n\nexport const BranchPickerPrimitivePrevious = createActionButton(\n \"BranchPickerPrimitive.Previous\",\n useBranchPickerPrevious\n);\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport { useBranchPickerCount } from \"../../primitive-hooks/branchPicker/useBranchPickerCount\";\n\n/**\n * @deprecated Use `BranchPickerPrimitive.Count.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveCountProps = BranchPickerPrimitiveCount.Props;\n\nexport namespace BranchPickerPrimitiveCount {\n export type Props = Record<string, never>;\n}\n\nexport const BranchPickerPrimitiveCount: FC<\n BranchPickerPrimitiveCount.Props\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\n/**\n * @deprecated Use `BranchPickerPrimitive.Number.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveNumberProps = BranchPickerPrimitiveNumber.Props;\n\nexport namespace BranchPickerPrimitiveNumber {\n export type Props = Record<string, never>;\n}\n\nexport const BranchPickerPrimitiveNumber: FC<\n BranchPickerPrimitiveNumber.Props\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\n/**\n * @deprecated Use `BranchPickerPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveRootProps = BranchPickerPrimitiveRoot.Props;\n\nexport namespace BranchPickerPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div> & {\n hideWhenSingleBranch?: boolean | undefined;\n };\n}\n\nexport const BranchPickerPrimitiveRoot = forwardRef<\n BranchPickerPrimitiveRoot.Element,\n BranchPickerPrimitiveRoot.Props\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\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\n/**\n * @deprecated Use `MessagePrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveRootProps = MessagePrimitiveRoot.Props;\n\nexport namespace MessagePrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div>;\n}\n\nexport const MessagePrimitiveRoot = forwardRef<\n MessagePrimitiveRoot.Element,\n MessagePrimitiveRoot.Props\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\n/**\n * @deprecated Use `MessagePrimitive.If.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveIfProps = MessagePrimitiveIf.Props;\n\nexport namespace MessagePrimitiveIf {\n export type Props = PropsWithChildren<UseMessageIfProps>;\n}\n\nexport const MessagePrimitiveIf: FC<MessagePrimitiveIf.Props> = ({\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 {\n useContentPart,\n useContentPartRuntime,\n useToolUIs,\n} from \"../../context\";\nimport {\n useMessage,\n useMessageRuntime,\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\n/**\n * @deprecated Use `MessagePrimitive.Content.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveContentProps = MessagePrimitiveContent.Props;\n\nexport namespace MessagePrimitiveContent {\n export type Props = {\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}\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 MessagePrimitiveContent.Props[\"components\"];\n\ntype MessageContentPartComponentProps = {\n components: MessagePrimitiveContent.Props[\"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 contentPartRuntime = useContentPartRuntime();\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 contentPartRuntime.addToolResult(result);\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: MessagePrimitiveContent.Props[\"components\"];\n};\n\nconst MessageContentPartImpl: FC<MessageContentPartProps> = ({\n partIndex,\n components,\n}) => {\n const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.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<MessagePrimitiveContent.Props> = ({\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\n/**\n * @deprecated Use `ContentPartPrimitive.Text.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveTextProps = ContentPartPrimitiveText.Props;\n\nexport namespace ContentPartPrimitiveText {\n export type Element = ElementRef<typeof Primitive.span>;\n export type Props = Omit<\n ComponentPropsWithoutRef<typeof Primitive.span>,\n \"children\" | \"asChild\"\n > & {\n smooth?: boolean;\n component?: ElementType;\n };\n}\n\nexport const ContentPartPrimitiveText = forwardRef<\n ContentPartPrimitiveText.Element,\n ContentPartPrimitiveText.Props\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\n/**\n * @deprecated Use `ContentPartPrimitive.Image.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveImageProps = ContentPartPrimitiveImage.Props;\n\nexport namespace ContentPartPrimitiveImage {\n export type Element = ElementRef<typeof Primitive.img>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.img>;\n}\n\nexport const ContentPartPrimitiveImage = forwardRef<\n ContentPartPrimitiveImage.Element,\n ContentPartPrimitiveImage.Props\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\n/**\n * @deprecated Use `ContentPartPrimitive.Display.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveDisplayProps =\n ContentPartPrimitiveDisplay.Props;\n\nexport namespace ContentPartPrimitiveDisplay {\n export type Props = Record<string, never>;\n}\n\nexport const ContentPartPrimitiveDisplay: FC<\n ContentPartPrimitiveDisplay.Props\n> = () => {\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\n/**\n * @deprecated Use `ContentPartPrimitive.InProgress.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveInProgressProps =\n ContentPartPrimitiveInProgress.Props;\n\nexport namespace ContentPartPrimitiveInProgress {\n export type Props = PropsWithChildren;\n}\n\n// TODO should this be renamed to IsRunning?\nexport const ContentPartPrimitiveInProgress: FC<\n ContentPartPrimitiveInProgress.Props\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 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 { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nimport { ComposerRuntimeCoreBinding } from \"./ComposerRuntime\";\nimport {\n Attachment,\n CompleteAttachment,\n PendingAttachment,\n Unsubscribe,\n} from \"../types\";\nimport { AttachmentRuntimePath } from \"./RuntimePathTypes\";\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<\n AttachmentState & { source: Source },\n AttachmentRuntimePath & { attachmentSource: Source }\n >;\n\ntype AttachmentRuntimeSource = AttachmentState[\"source\"];\n\nexport type AttachmentRuntime<\n TSource extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> = {\n path: AttachmentRuntimePath & { attachmentSource: TSource };\n readonly source: TSource;\n getState(): AttachmentState & { source: TSource };\n remove(): Promise<void>;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport abstract class AttachmentRuntimeImpl<\n Source extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> implements AttachmentRuntime\n{\n public get path() {\n return this._core.path;\n }\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 AttachmentRuntimeImpl<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 ThreadComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"thread-composer\"> {\n public get source(): \"thread-composer\" {\n return \"thread-composer\";\n }\n}\n\nexport class EditComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"edit-composer\"> {\n public get source(): \"edit-composer\" {\n return \"edit-composer\";\n }\n}\n\nexport class MessageAttachmentRuntimeImpl extends AttachmentRuntimeImpl<\"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<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n constructor(\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>,\n ) {\n super();\n }\n\n private _previousStateDirty = true;\n private _previousState: TState | 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<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n constructor(\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>,\n ) {\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: TState;\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 EditComposerAttachmentRuntimeImpl,\n ThreadComposerAttachmentRuntimeImpl,\n} from \"./AttachmentRuntime\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport { SKIP_UPDATE } from \"./subscribable/SKIP_UPDATE\";\nimport { ComposerRuntimePath } from \"./RuntimePathTypes\";\n\nexport type ThreadComposerRuntimeCoreBinding = SubscribableWithState<\n ThreadComposerRuntimeCore | undefined,\n ComposerRuntimePath & { composerSource: \"thread\" }\n>;\n\nexport type EditComposerRuntimeCoreBinding = SubscribableWithState<\n ComposerRuntimeCore | undefined,\n ComposerRuntimePath & { composerSource: \"edit\" }\n>;\n\nexport type ComposerRuntimeCoreBinding = SubscribableWithState<\n ComposerRuntimeCore | undefined,\n ComposerRuntimePath\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 attachments: readonly Attachment[];\n\n /** @deprecated Use `useComposerRuntime().addAttachment` instead. This will be removed in 0.6.0. */\n addAttachment: (file: File) => Promise<void>;\n /** @deprecated Use `useComposerRuntime().removeAttachment` instead. This will be removed in 0.6.0. */\n removeAttachment: (attachmentId: string) => Promise<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\ntype BaseComposerState = {\n text: 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): 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\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 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\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 type ComposerRuntime = {\n path: ComposerRuntimePath;\n readonly type: \"edit\" | \"thread\";\n getState(): ComposerState;\n\n /** @deprecated Use `getState().isEditing` instead. This will be removed in 0.6.0. */\n readonly isEditing: boolean;\n\n /** @deprecated Use `getState().isEmpty` instead. This will be removed in 0.6.0. */\n readonly isEmpty: boolean;\n\n /** @deprecated Use `getState().canCancel` instead. This will be removed in 0.6.0. */\n readonly canCancel: boolean;\n\n /** @deprecated Use `getState().text` instead. This will be removed in 0.6.0. */\n readonly text: string;\n\n /** @deprecated Use `getState().attachments` instead. This will be removed in 0.6.0. */\n readonly attachments: readonly Attachment[];\n\n /** @deprecated Use `getState().text` instead. This will be removed in 0.6.0. */\n readonly value: string;\n\n setText(text: string): void;\n setValue(text: string): void;\n\n getAttachmentAccept(): string;\n addAttachment(file: File): Promise<void>;\n\n /** @deprecated Use `getAttachmentById(id).removeAttachment()` instead. This will be removed in 0.6.0. */\n removeAttachment(attachmentId: string): Promise<void>;\n\n /** @deprecated This method will be removed in 0.6.0. Submit feedback if you need this functionality. */\n reset(): void;\n\n send(): void;\n cancel(): void;\n subscribe(callback: () => void): Unsubscribe;\n getAttachmentByIndex(idx: number): AttachmentRuntime;\n};\n\nexport abstract class ComposerRuntimeImpl\n implements ComposerRuntimeCore, ComposerRuntime\n{\n public get path() {\n return this._core.path;\n }\n\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().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 getAttachmentAccept(): string {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.getAttachmentAccept();\n }\n\n public abstract getAttachmentByIndex(idx: number): AttachmentRuntime;\n}\n\nexport type ThreadComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"thread\" };\n readonly type: \"thread\";\n getState(): ThreadComposerState;\n\n /**\n * @deprecated Use `getState().attachments` instead. This will be removed in 0.6.0.\n */\n attachments: readonly PendingAttachment[];\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"thread-composer\" };\n};\n\nexport class ThreadComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements ThreadComposerRuntime, ThreadComposerState\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & {\n composerSource: \"thread\";\n };\n }\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 path: core.path,\n getState: () => getThreadComposerState(core.getState()),\n subscribe: (callback) => core.subscribe(callback),\n });\n super({\n path: core.path,\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 public getAttachmentByIndex(idx: number) {\n return new ThreadComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"thread-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: this.path.ref + `${this.path.ref}.attachments[${idx}]`,\n },\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 type EditComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"edit\" };\n readonly type: \"edit\";\n\n getState(): EditComposerState;\n beginEdit(): void;\n\n /**\n * @deprecated Use `beginEdit()` instead. This will be removed in 0.6.0.\n */\n edit(): void;\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"edit-composer\" };\n};\n\nexport class EditComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements EditComposerRuntime, EditComposerState\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & { composerSource: \"edit\" };\n }\n\n public get type() {\n return \"edit\" as const;\n }\n\n private _getState;\n constructor(\n core: EditComposerRuntimeCoreBinding,\n private _beginEdit: () => void,\n ) {\n const stateBinding = new LazyMemoizeSubject({\n path: core.path,\n getState: () => getEditComposerState(core.getState(), this._beginEdit),\n subscribe: (callback) => core.subscribe(callback),\n });\n\n super({\n path: core.path,\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 getAttachmentByIndex(idx: number) {\n return new EditComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"edit-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: this.path.ref + `${this.path.ref}.attachments[${idx}]`,\n },\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, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>, NestedSubscribable<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n constructor(private binding: NestedSubscribable<TState, TPath>) {\n super();\n }\n\n public getState() {\n return this.binding.getState();\n }\n\n public outerSubscribe(callback: () => void) {\n return this.binding.subscribe(callback);\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.outerSubscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n","import {\n SpeechState,\n SubmittedFeedback,\n} from \"../runtimes/core/ThreadRuntimeCore\";\nimport {\n ThreadMessage,\n ThreadAssistantContentPart,\n ThreadUserContentPart,\n Unsubscribe,\n} from \"../types\";\nimport {\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../types/AssistantTypes\";\nimport { getThreadMessageText } from \"../utils/getThreadMessageText\";\nimport {\n AttachmentRuntime,\n AttachmentState,\n MessageAttachmentRuntimeImpl,\n} from \"./AttachmentRuntime\";\nimport {\n EditComposerRuntime,\n EditComposerRuntimeImpl,\n} from \"./ComposerRuntime\";\nimport {\n ContentPartRuntime,\n ContentPartRuntimeImpl,\n ContentPartState,\n} from \"./ContentPartRuntime\";\nimport { MessageRuntimePath } from \"./RuntimePathTypes\";\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 /**\n * @deprecated This API is still under active development and might change without notice.\n */\n speech: SpeechState | undefined;\n submittedFeedback: SubmittedFeedback | undefined;\n};\n\nexport type MessageStateBinding = SubscribableWithState<\n MessageState,\n MessageRuntimePath\n>;\n\nexport type MessageRuntime = {\n readonly path: MessageRuntimePath;\n\n readonly composer: EditComposerRuntime;\n\n getState(): MessageState;\n reload(): void;\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n speak(): void;\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n submitFeedback({ type }: { type: \"positive\" | \"negative\" }): void;\n switchToBranch({\n position,\n branchId,\n }: {\n position?: \"previous\" | \"next\" | undefined;\n branchId?: string | undefined;\n }): void;\n unstable_getCopyText(): string;\n\n subscribe(callback: () => void): Unsubscribe;\n\n getContentPartByIndex(idx: number): ContentPartRuntime;\n getContentPartByToolCallId(toolCallId: string): ContentPartRuntime;\n\n getAttachmentByIndex(idx: number): AttachmentRuntime & { source: \"message\" };\n};\n\nexport class MessageRuntimeImpl implements MessageRuntime {\n public get path() {\n return this._core.path;\n }\n\n constructor(\n private _core: MessageStateBinding,\n private _threadBinding: ThreadRuntimeCoreBinding,\n ) {\n this.composer = new EditComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.composer`,\n composerSource: \"edit\",\n },\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\n public composer;\n\n public getState() {\n return this._core.getState();\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 stopSpeaking() {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n const thread = this._threadBinding.getState();\n if (thread.speech?.messageId === state.id) {\n this._threadBinding.getState().stopSpeaking();\n } else {\n throw new Error(\"Message is not being spoken\");\n }\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 unstable_getCopyText() {\n return getThreadMessageText(this.getState());\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n public getContentPartByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Content part index must be >= 0\");\n return new ContentPartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.content[${idx}]`,\n contentPartSelector: { type: \"index\", index: idx },\n },\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 getContentPartByToolCallId(toolCallId: string) {\n return new ContentPartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref:\n this.path.ref +\n `${this.path.ref}.content[toolCallId=${JSON.stringify(toolCallId)}]`,\n contentPartSelector: { type: \"toolCallId\", toolCallId },\n },\n getState: () => {\n const state = this._core.getState();\n const idx = state.content.findIndex(\n (part) =>\n part.type === \"tool-call\" && part.toolCallId === toolCallId,\n );\n if (idx === -1) return SKIP_UPDATE;\n return getContentPartState(state, idx);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n this._threadBinding,\n );\n }\n\n public getAttachmentByIndex(idx: number) {\n return new MessageAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.attachments[${idx}]`,\n attachmentSource: \"message\",\n attachmentSelector: { type: \"index\", index: idx },\n },\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\n/**\n * @deprecated Define a custom Text renderer via ContentPartPrimitiveInProgress instead. This will be removed in 0.6.\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\n/**\n * @deprecated Use `MessagePrimitive.Attachments.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveAttachmentsProps =\n MessagePrimitiveAttachments.Props;\n\nexport namespace MessagePrimitiveAttachments {\n export type Props = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n };\n}\n\nconst getComponent = (\n components: MessagePrimitiveAttachments.Props[\"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: MessagePrimitiveAttachments.Props[\"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 MessagePrimitiveAttachments.Props & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.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 MessagePrimitiveAttachments.Props\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 {\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\nexport type ComposerPrimitiveRootProps = ComposerPrimitiveRoot.Props;\n\nexport namespace ComposerPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.form>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.form>;\n}\n\nexport const ComposerPrimitiveRoot = forwardRef<\n ComposerPrimitiveRoot.Element,\n ComposerPrimitiveRoot.Props\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 useComposerRuntime,\n} from \"../../context/react/ComposerContext\";\nimport { useThread, useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { useEscapeKeydown } from \"@radix-ui/react-use-escape-keydown\";\nimport { useOnScrollToBottom } from \"../../utils/hooks/useOnScrollToBottom\";\n\n/**\n * @deprecated Use `ComposerPrimitive.Input.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveInputProps = ComposerPrimitiveInput.Props;\n\nexport namespace ComposerPrimitiveInput {\n export type Element = HTMLTextAreaElement;\n export type Props = TextareaAutosizeProps & {\n asChild?: boolean | undefined;\n submitOnEnter?: boolean | undefined;\n cancelOnEscape?: boolean | undefined;\n unstable_focusOnRunStart?: boolean | undefined;\n unstable_focusOnScrollToBottom?: boolean | undefined;\n unstable_focusOnThreadSwitched?: boolean | undefined;\n };\n}\n\nexport const ComposerPrimitiveInput = forwardRef<\n ComposerPrimitiveInput.Element,\n ComposerPrimitiveInput.Props\n>(\n (\n {\n autoFocus = false,\n asChild,\n disabled: disabledProp,\n onChange,\n onKeyDown,\n submitOnEnter = true,\n cancelOnEscape = true,\n unstable_focusOnRunStart = true,\n unstable_focusOnScrollToBottom = true,\n unstable_focusOnThreadSwitched = true,\n ...rest\n },\n forwardedRef,\n ) => {\n const threadRuntime = useThreadRuntime();\n const composerRuntime = useComposerRuntime();\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 if (composerRuntime.getState().canCancel) {\n composerRuntime.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 } = threadRuntime.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 useOnScrollToBottom(() => {\n if (composerRuntime.type === \"thread\" && unstable_focusOnScrollToBottom) {\n focus();\n }\n });\n\n useEffect(() => {\n if (composerRuntime.type !== \"thread\" || !unstable_focusOnRunStart)\n return undefined;\n\n return threadRuntime.unstable_on(\"run-start\", focus);\n }, [unstable_focusOnRunStart]);\n\n useEffect(() => {\n if (composerRuntime.type !== \"thread\" || !unstable_focusOnThreadSwitched)\n return undefined;\n\n return threadRuntime.unstable_on(\"switched-to\", focus);\n }, [unstable_focusOnThreadSwitched]);\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 if (!composerRuntime.getState().isEditing) return;\n return composerRuntime.setText(e.target.value);\n })}\n onKeyDown={composeEventHandlers(onKeyDown, handleKeyPress)}\n />\n );\n },\n);\n\nComposerPrimitiveInput.displayName = \"ComposerPrimitive.Input\";\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useEffect } from \"react\";\nimport { useThreadViewport } from \"../../context/react/ThreadContext\";\n\nexport const useOnScrollToBottom = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n const onScrollToBottom = useThreadViewport((vp) => vp.onScrollToBottom);\n\n useEffect(() => {\n return onScrollToBottom(callbackRef);\n }, [onScrollToBottom, callbackRef]);\n};\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerSend } from \"../../primitive-hooks\";\n\n/**\n * @deprecated Use `ComposerPrimitive.Send.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveSendProps = ComposerPrimitiveSend.Props;\n\nexport namespace ComposerPrimitiveSend {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useComposerSend>;\n}\n\nexport const ComposerPrimitiveSend = createActionButton(\n \"ComposerPrimitive.Send\",\n useComposerSend\n);\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerCancel } from \"../../primitive-hooks/composer/useComposerCancel\";\n\n/**\n * @deprecated Use `ComposerPrimitive.Cancel.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveCancelProps = ComposerPrimitiveCancel.Props;\n\nexport namespace ComposerPrimitiveCancel {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useComposerCancel>;\n}\n\nexport const ComposerPrimitiveCancel = createActionButton(\n \"ComposerPrimitive.Cancel\",\n useComposerCancel,\n);\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerAddAttachment } from \"../../primitive-hooks/composer\";\n\n/**\n * @deprecated Use `ComposerPrimitive.AddAttachment.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveAddAttachmentProps = ComposerPrimitiveAddAttachment.Props;\n\nexport namespace ComposerPrimitiveAddAttachment {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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\n/**\n * @deprecated Use `ComposerPrimitive.Attachments.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveAttachmentsProps =\n ComposerPrimitiveAttachments.Props;\n\nexport namespace ComposerPrimitiveAttachments {\n export type Props = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n };\n}\n\nconst getComponent = (\n components: ComposerPrimitiveAttachments.Props[\"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: ComposerPrimitiveAttachments.Props[\"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 ComposerPrimitiveAttachments.Props & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n const composerRuntime = useComposerRuntime();\n const runtime = useMemo(\n () => composerRuntime.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 ComposerPrimitiveAttachments.Props\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\n/**\n * @deprecated Use `ComposerPrimitive.If.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveIfProps = ComposerPrimitiveIf.Props;\n\nexport namespace ComposerPrimitiveIf {\n export type Props = PropsWithChildren<UseComposerIfProps>;\n}\n\nexport const ComposerPrimitiveIf: FC<ComposerPrimitiveIf.Props> = ({\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\n/**\n * @deprecated Use `ThreadPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveRootProps = ThreadPrimitiveRoot.Props;\n\nexport namespace ThreadPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div>;\n}\n\nexport const ThreadPrimitiveRoot = forwardRef<\n ThreadPrimitiveRoot.Element,\n ThreadPrimitiveRoot.Props\n>((props, ref) => {\n return <Primitive.div {...props} ref={ref} />;\n});\n\nThreadPrimitiveRoot.displayName = \"ThreadPrimitive.Root\";\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { useThreadEmpty } from \"../../primitive-hooks\";\n\n/**\n * @deprecated Use `ThreadPrimitive.Empty.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveEmptyProps = ThreadPrimitiveEmpty.Props;\n\nexport namespace ThreadPrimitiveEmpty {\n export type Props = PropsWithChildren;\n}\n\nexport const ThreadPrimitiveEmpty: FC<ThreadPrimitiveEmpty.Props> = ({\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\n/**\n * @deprecated Use `ThreadPrimitive.If.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveIfProps = ThreadPrimitiveIf.Props;\n\nexport namespace ThreadPrimitiveIf {\n export type Props = PropsWithChildren<UseThreadIfProps>;\n}\n\nexport const ThreadPrimitiveIf: FC<ThreadPrimitiveIf.Props> = ({\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\n/**\n * @deprecated Use `ThreadPrimitive.Viewport.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveViewportProps = ThreadPrimitiveViewport.Props;\n\nexport namespace ThreadPrimitiveViewport {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div> &\n UseThreadViewportAutoScrollProps;\n}\n\nexport const ThreadPrimitiveViewport = forwardRef<\n ThreadPrimitiveViewport.Element,\n ThreadPrimitiveViewport.Props\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 { useEffect, useRef } from \"react\";\nimport {\n useThreadRuntime,\n useThreadViewportStore,\n} 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 unstable_scrollToBottomOnRunStart?: boolean | undefined;\n};\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll = true,\n unstable_scrollToBottomOnRunStart = 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 // autoscroll on run start\n const threadRuntime = useThreadRuntime();\n useEffect(() => {\n if (!unstable_scrollToBottomOnRunStart) return undefined;\n\n return threadRuntime.unstable_on(\"run-start\", focus);\n }, [unstable_scrollToBottomOnRunStart]);\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","\"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\n/**\n * @deprecated Use `ThreadPrimitive.Messages.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveMessagesProps = ThreadPrimitiveMessages.Props;\n\nexport namespace ThreadPrimitiveMessages {\n export type Props = {\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}\n\nconst isComponentsSame = (\n prev: ThreadPrimitiveMessages.Props[\"components\"],\n next: ThreadPrimitiveMessages.Props[\"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: ThreadPrimitiveMessages.Props[\"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: ThreadPrimitiveMessages.Props[\"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: ThreadPrimitiveMessages.Props[\"components\"];\n};\n\nconst ThreadMessageImpl: FC<ThreadMessageProps> = ({\n messageIndex,\n components,\n}) => {\n const threadRuntime = useThreadRuntime();\n const runtime = useMemo(\n () => threadRuntime.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<ThreadPrimitiveMessages.Props> = ({\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\";\n\nexport type MessageUtilsState = Readonly<{\n isCopied: boolean;\n setIsCopied: (value: boolean) => void;\n\n isHovering: boolean;\n setIsHovering: (value: boolean) => void;\n}>;\n\nexport const makeMessageUtilsStore = () =>\n create<MessageUtilsState>((set) => {\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 };\n });\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadScrollToBottom } from \"../../primitive-hooks/thread/useThreadScrollToBottom\";\n\n/**\n * @deprecated Use `ThreadPrimitive.ScrollToBottom.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveScrollToBottomProps =\n ThreadPrimitiveScrollToBottom.Props;\n\nexport namespace ThreadPrimitiveScrollToBottom {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useThreadScrollToBottom>;\n}\n\nexport const ThreadPrimitiveScrollToBottom = createActionButton(\n \"ThreadPrimitive.ScrollToBottom\",\n useThreadScrollToBottom,\n);\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadSuggestion } from \"../../primitive-hooks/thread/useThreadSuggestion\";\n\n/**\n * @deprecated Use `ThreadPrimitive.Suggestion.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveSuggestionProps = ThreadPrimitiveSuggestion.Props;\n\nexport namespace ThreadPrimitiveSuggestion {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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.threadManager.mainThread.subscribe(callback);\n\n if (!first) {\n callback();\n }\n first = false;\n };\n\n const unsubscribe = runtime.threadManager.mainThread.subscribe(inner);\n inner();\n\n return () => {\n unsubscribe();\n cleanup?.();\n };\n};\n","\"use client\";\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntimeCore } from \"./LocalRuntimeCore\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport {\n AssistantRuntime,\n AssistantRuntimeImpl,\n} from \"../../api/AssistantRuntime\";\nimport { ThreadRuntimeImpl } from \"../../internal\";\nimport { ThreadRuntime } from \"../../api\";\n\nexport type LocalRuntime = AssistantRuntime & {\n reset: (options?: Parameters<LocalRuntimeCore[\"reset\"]>[0]) => void;\n};\n\nclass LocalRuntimeImpl extends AssistantRuntimeImpl implements LocalRuntime {\n private constructor(\n private core: LocalRuntimeCore,\n thread: ThreadRuntime,\n ) {\n super(core, thread);\n }\n\n public reset(options?: Parameters<LocalRuntimeCore[\"reset\"]>[0]) {\n this.core.reset(options);\n }\n\n public static override create(_core: LocalRuntimeCore) {\n return new LocalRuntimeImpl(\n _core,\n AssistantRuntimeImpl.createMainThreadRuntime(_core, ThreadRuntimeImpl),\n ) as LocalRuntime;\n }\n}\n\nexport const useLocalRuntime = (\n adapter: ChatModelAdapter,\n options: LocalRuntimeOptions = {},\n) => {\n const opt = {\n ...options,\n adapters: {\n ...options.adapters,\n chatModel: adapter,\n },\n };\n\n const [runtime] = useState(() => new LocalRuntimeCore(opt));\n\n useEffect(() => {\n runtime.setOptions(opt);\n });\n\n return useMemo(() => LocalRuntimeImpl.create(runtime), [runtime]);\n};\n","import {\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 const unsubscribe = provider.subscribe?.(() => {\n this.notifySubscribers();\n });\n this.notifySubscribers();\n return () => {\n this._providers.delete(provider);\n unsubscribe?.();\n this.notifySubscribers();\n };\n }\n\n private _subscribers = new Set<() => void>();\n\n notifySubscribers() {\n for (const callback of this._subscribers) callback();\n }\n\n subscribe(callback: () => void) {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n}\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport type { AssistantRuntimeCore } from \"./AssistantRuntimeCore\";\nimport { ProxyConfigProvider } from \"../../utils/ProxyConfigProvider\";\nimport { ThreadManagerRuntimeCore } from \"./ThreadManagerRuntimeCore\";\n\nexport abstract class BaseAssistantRuntimeCore implements AssistantRuntimeCore {\n protected readonly _proxyConfigProvider = new ProxyConfigProvider();\n public abstract get threadManager(): ThreadManagerRuntimeCore;\n\n constructor() {}\n\n public registerModelConfigProvider(\n provider: ModelConfigProvider,\n ): Unsubscribe {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n}\n","export type { ThreadRuntimeCore } from \"./runtimes/core/ThreadRuntimeCore\";\nexport type { ThreadManagerRuntimeCore } from \"./runtimes/core/ThreadManagerRuntimeCore\";\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 { AssistantRuntimeImpl } from \"./api/AssistantRuntime\";\nexport {\n ThreadRuntimeImpl,\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 protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n\n public getAttachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\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 adapter = this.getAttachmentAdapter();\n const attachments =\n adapter && this.attachments.length > 0\n ? await Promise.all(\n this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n const result = await adapter.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 async addAttachment(file: File) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n\n const attachment = await adapter.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 const adapter = this.getAttachmentAdapter();\n if (!adapter) 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 adapter.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 { AttachmentAdapter } from \"../attachment\";\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 protected getAttachmentAdapter() {\n return this.runtime.adapters?.attachments;\n }\n\n constructor(\n private runtime: Omit<ThreadRuntimeCore, \"composer\"> & {\n adapters?: { attachments?: AttachmentAdapter | undefined } | undefined;\n },\n ) {\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","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 {\n AddToolResultOptions,\n ThreadSuggestion,\n RuntimeCapabilities,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n SpeechState,\n SubmittedFeedback,\n ThreadRuntimeEventType,\n} from \"../runtimes/core/ThreadRuntimeCore\";\nimport { ExportedMessageRepository } from \"../runtimes/utils/MessageRepository\";\nimport {\n AppendMessage,\n ModelConfig,\n ThreadMessage,\n Unsubscribe,\n} from \"../types\";\nimport {\n MessageRuntime,\n MessageRuntimeImpl,\n MessageState,\n} from \"./MessageRuntime\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport {\n Subscribable,\n SubscribableWithState,\n} from \"./subscribable/Subscribable\";\nimport {\n ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./ComposerRuntime\";\nimport { LazyMemoizeSubject } from \"./subscribable/LazyMemoizeSubject\";\nimport { SKIP_UPDATE } from \"./subscribable/SKIP_UPDATE\";\nimport { ComposerRuntimeCore } from \"../runtimes/core/ComposerRuntimeCore\";\nimport { MessageRuntimePath, ThreadRuntimePath } from \"./RuntimePathTypes\";\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<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadState = Readonly<{\n threadId: string;\n isDisabled: boolean;\n isRunning: boolean;\n capabilities: RuntimeCapabilities;\n messages: readonly ThreadMessage[];\n suggestions: readonly ThreadSuggestion[];\n extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n speech: SpeechState | 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 suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n });\n};\n\nexport type ThreadRuntime = Readonly<{\n readonly path: ThreadRuntimePath;\n\n readonly composer: ThreadComposerRuntime;\n getState(): ThreadState;\n\n /**\n * @deprecated This method will be removed in 0.6.0. Submit feedback if you need this functionality.\n */\n unstable_getCore(): ThreadRuntimeCore;\n\n append(message: CreateAppendMessage): void;\n startRun(parentId: string | null): void;\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n getModelConfig(): ModelConfig;\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n getMesssageByIndex(idx: number): MessageRuntime;\n getMesssageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking: () => void;\n\n unstable_on(event: ThreadRuntimeEventType, callback: () => void): Unsubscribe;\n\n // Legacy methods with deprecations\n\n /**\n * @deprecated Use `getState().capabilities` instead. This will be removed in 0.6.0.\n */\n capabilities: Readonly<RuntimeCapabilities>;\n\n /**\n * @deprecated Use `getState().threadId` instead. This will be removed in 0.6.0.\n */\n threadId: string;\n\n /**\n * @deprecated Use `getState().isDisabled` instead. This will be removed in 0.6.0.\n */\n isDisabled: boolean;\n\n /**\n * @deprecated Use `getState().isRunning` instead. This will be removed in 0.6.0.\n */\n isRunning: boolean;\n\n /**\n * @deprecated Use `getState().messages` instead. This will be removed in 0.6.0.\n */\n messages: readonly ThreadMessage[];\n\n /**\n * @deprecated Use `getState().followupSuggestions` instead. This will be removed in 0.6.0.\n */\n suggestions: readonly ThreadSuggestion[];\n\n /**\n * @deprecated Use `getState().speechState` instead. This will be removed in 0.6.0.\n */\n speech: SpeechState | undefined;\n\n /**\n * @deprecated Use `getState().extras` instead. This will be removed in 0.6.0.\n */\n extras: unknown;\n\n /**\n * @deprecated Use `getMesssageById(id).getState().branchNumber` / `getMesssageById(id).getState().branchCount` instead. This will be removed in 0.6.0.\n */\n getBranches: (messageId: string) => readonly string[];\n\n /**\n * @deprecated Use `getMesssageById(id).switchToBranch({ options })` instead. This will be removed in 0.6.0.\n */\n switchToBranch: (branchId: string) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).getContentPartByToolCallId(toolCallId).addToolResult({ result })` instead. This will be removed in 0.6.0.\n */\n addToolResult: (options: AddToolResultOptions) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).speak()` instead. This will be removed in 0.6.0.\n */\n speak: (messageId: string) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).getState().submittedFeedback` instead. This will be removed in 0.6.0.\n */\n getSubmittedFeedback: (messageId: string) => SubmittedFeedback | undefined;\n\n /**\n * @deprecated Use `getMesssageById(id).submitFeedback({ type })` instead. This will be removed in 0.6.0.\n */\n submitFeedback: (feedback: SubmitFeedbackOptions) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).composer` instead. This will be removed in 0.6.0.\n */\n getEditComposer: (messageId: string) => ComposerRuntimeCore | undefined;\n\n /**\n * @deprecated Use `getMesssageById(id).composer.beginEdit()` instead. This will be removed in 0.6.0.\n */\n beginEdit: (messageId: string) => void;\n}>;\n\nexport class ThreadRuntimeImpl\n implements Omit<ThreadRuntimeCore, \"getMessageById\">, ThreadRuntime\n{\n public get path() {\n return this._threadBinding.path;\n }\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().extras` instead. This will be removed in 0.6.0.\n */\n public get extras() {\n return this._threadBinding.getState().extras;\n }\n\n /**\n * @deprecated Use `getState().followupSuggestions` instead. This will be removed in 0.6.0.\n */\n public get suggestions() {\n return this._threadBinding.getState().suggestions;\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 /**\n * @deprecated Use `getState().speechState` instead. This will be removed in 0.6.0.\n */\n public get speech() {\n return this._threadBinding.getState().speech;\n }\n\n public unstable_getCore() {\n return this._threadBinding.getState();\n }\n\n private _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n\n constructor(threadBinding: ThreadRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n path: threadBinding.path,\n getState: () => getThreadState(threadBinding.getState()),\n subscribe: (callback) => threadBinding.subscribe(callback),\n });\n\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n }\n\n public readonly composer;\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 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 /**\n * @deprecated Use `getMesssageById(id).switchToBranch({ options })` instead. This will be removed in 0.6.0.\n */\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 public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public getSubmittedFeedback(messageId: string) {\n return this._threadBinding.getState().getSubmittedFeedback(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).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).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 getMesssageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n };\n },\n );\n }\n\n public getMesssageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref:\n this.path.ref +\n `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined) return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n const submittedFeedback = thread.getSubmittedFeedback(message.id);\n\n return {\n ...message,\n\n message,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branches,\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n\n submittedFeedback,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventListenerNestedSubscriptions = new Map<\n string,\n NestedSubscriptionSubject<Subscribable, ThreadRuntimePath>\n >();\n\n public unstable_on(\n event: ThreadRuntimeEventType,\n callback: () => void,\n ): Unsubscribe {\n let subject = this._eventListenerNestedSubscriptions.get(event);\n if (!subject) {\n subject = new NestedSubscriptionSubject({\n path: this.path,\n getState: () => ({\n subscribe: (callback) =>\n this._threadBinding.getState().unstable_on(event, callback),\n }),\n subscribe: (callback) => this._threadBinding.outerSubscribe(callback),\n });\n this._eventListenerNestedSubscriptions.set(event, subject);\n }\n return subject.subscribe(callback);\n }\n}\n","import { LazyMemoizeSubject } from \"./subscribable/LazyMemoizeSubject\";\nimport {\n ThreadManagerMetadata,\n ThreadManagerRuntimeCore,\n} from \"../runtimes/core/ThreadManagerRuntimeCore\";\nimport { Unsubscribe } from \"../types\";\nimport { ThreadManagerRuntimePath } from \"./RuntimePathTypes\";\n\nexport type ThreadManagerState = Readonly<{\n threads: readonly ThreadManagerMetadata[];\n archivedThreads: readonly ThreadManagerMetadata[];\n}>;\n\nexport type ThreadManagerRuntime = Readonly<{\n path: ThreadManagerRuntimePath;\n getState(): ThreadManagerState;\n\n rename(threadId: string, newTitle: string): Promise<void>;\n archive(threadId: string): Promise<void>;\n unarchive(threadId: string): Promise<void>;\n delete(threadId: string): Promise<void>;\n\n subscribe(callback: () => void): Unsubscribe;\n}>;\n\nconst getThreadManagerState = (\n threadManager: ThreadManagerRuntimeCore,\n): ThreadManagerState => {\n return {\n threads: threadManager.threads,\n archivedThreads: threadManager.archivedThreads,\n };\n};\n\nconst THREAD_MANAGER_PATH = {\n ref: \"threadManager\",\n};\n\nexport type ThreadManagerRuntimeCoreBinding = ThreadManagerRuntimeCore;\n\nexport class ThreadManagerRuntimeImpl implements ThreadManagerRuntime {\n public get path() {\n return THREAD_MANAGER_PATH;\n }\n\n private _getState;\n constructor(private _core: ThreadManagerRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n path: THREAD_MANAGER_PATH,\n getState: () => getThreadManagerState(_core),\n subscribe: (callback) => _core.subscribe(callback),\n });\n\n this._getState = stateBinding.getState.bind(stateBinding);\n }\n\n public getState(): ThreadManagerState {\n return this._getState();\n }\n\n public rename(threadId: string, newTitle: string): Promise<void> {\n return this._core.rename(threadId, newTitle);\n }\n\n public archive(threadId: string): Promise<void> {\n return this._core.archive(threadId);\n }\n\n public unarchive(threadId: string): Promise<void> {\n return this._core.unarchive(threadId);\n }\n\n public delete(threadId: string): Promise<void> {\n return this._core.delete(threadId);\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n return this._core.subscribe(callback);\n }\n}\n","import { AssistantRuntimeCore } from \"../runtimes/core/AssistantRuntimeCore\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ModelConfigProvider } from \"../types/ModelConfigTypes\";\nimport {\n ThreadRuntime,\n ThreadRuntimeCoreBinding,\n ThreadRuntimeImpl,\n} from \"./ThreadRuntime\";\nimport { Unsubscribe } from \"../types\";\nimport {\n ThreadManagerRuntime,\n ThreadManagerRuntimeImpl,\n} from \"./ThreadManagerRuntime\";\n\nexport type AssistantRuntime = {\n thread: ThreadRuntime;\n threadManager: ThreadManagerRuntime;\n\n switchToNewThread(): void;\n\n switchToThread(threadId: string): void;\n /**\n * @deprecated Use `switchToNewThread` instead. This will be removed in 0.6.0.\n */\n switchToThread(threadId: string | null): void;\n\n registerModelConfigProvider(provider: ModelConfigProvider): Unsubscribe;\n\n /**\n * @deprecated Thread is now static and never gets updated. This will be removed in 0.6.0.\n */\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport class AssistantRuntimeImpl\n implements\n Omit<AssistantRuntimeCore, \"thread\" | \"threadManager\">,\n AssistantRuntime\n{\n public readonly threadManager;\n\n protected constructor(\n private readonly _core: AssistantRuntimeCore,\n private readonly _thread: ThreadRuntime,\n ) {\n this.threadManager = new ThreadManagerRuntimeImpl(_core.threadManager);\n }\n\n public get thread() {\n return this._thread;\n }\n\n public switchToNewThread() {\n return this._core.threadManager.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 if (threadId === null) return this.switchToNewThread();\n return this._core.threadManager.switchToThread(threadId);\n }\n\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._core.registerModelConfigProvider(provider);\n }\n\n /**\n * @deprecated Thread is now static and never gets updated. This will be removed in 0.6.0.\n */\n public subscribe() {\n return () => {};\n }\n\n protected static createMainThreadRuntime(\n _core: AssistantRuntimeCore,\n CustomThreadRuntime: new (\n binding: ThreadRuntimeCoreBinding,\n ) => ThreadRuntime = ThreadRuntimeImpl,\n ) {\n return new CustomThreadRuntime(\n new NestedSubscriptionSubject({\n path: {\n ref: \"threads.main\",\n threadSelector: { type: \"main\" },\n },\n getState: () => _core.threadManager.mainThread,\n subscribe: (callback) => _core.threadManager.subscribe(callback),\n }),\n );\n }\n\n public static create(\n _core: AssistantRuntimeCore,\n CustomThreadRuntime: new (\n binding: ThreadRuntimeCoreBinding,\n ) => ThreadRuntime = ThreadRuntimeImpl,\n ) {\n return new AssistantRuntimeImpl(\n _core,\n AssistantRuntimeImpl.createMainThreadRuntime(_core, CustomThreadRuntime),\n ) as AssistantRuntime;\n }\n}\n","import { LanguageModelV1Message } from \"@ai-sdk/provider\";\nimport { CoreMessage, ToolCallContentPart } from \"../../../types\";\n\ntype fromLanguageModelMessagesOptions = {\n mergeSteps: boolean;\n};\n\nexport const fromLanguageModelMessages = (\n lm: LanguageModelV1Message[],\n { mergeSteps }: 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 (mergeSteps) {\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\n/**\n * @deprecated `streamUtils` will be replaced with `assistant-stream` once it is ready.\n */\nexport const streamUtils = {\n streamPartEncoderStream,\n streamPartDecoderStream,\n};\n","import { LocalRuntimeOptions, useLocalRuntime } from \"..\";\nimport { useState } from \"react\";\nimport { EdgeChatAdapterOptions, EdgeChatAdapter } from \"./EdgeChatAdapter\";\nimport { splitLocalRuntimeOptions } from \"../local/LocalRuntimeOptions\";\n\nexport type EdgeRuntimeOptions = EdgeChatAdapterOptions & LocalRuntimeOptions;\n\nexport const useEdgeRuntime = (options: EdgeRuntimeOptions) => {\n const { localRuntimeOptions, otherOptions } =\n splitLocalRuntimeOptions(options);\n const [adapter] = useState(() => new EdgeChatAdapter(otherOptions));\n return useLocalRuntime(adapter, localRuntimeOptions);\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.ToolCallDelta &&\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 { toolCallId: id, toolName: name } = value;\n toolCallNames.set(id, name);\n currentToolCall = { id, name, argsText: \"\" };\n\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId: id,\n toolName: name,\n argsTextDelta: \"\",\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallDelta: {\n const { toolCallId, argsTextDelta } = value;\n\n const toolName = toolCallNames.get(toolCallId)!;\n if (currentToolCall?.id === toolCallId) {\n currentToolCall.argsText += argsTextDelta;\n }\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId,\n toolName,\n argsTextDelta: argsTextDelta,\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallResult: {\n controller.enqueue({\n type: \"tool-result\",\n toolCallType: \"function\",\n toolCallId: value.toolCallId,\n toolName: toolCallNames.get(value.toolCallId)!,\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\n case AssistantStreamChunkType.ToolCall: {\n const { toolCallId, toolName, args } = value;\n const argsText = JSON.stringify(args);\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId,\n toolName,\n argsTextDelta: argsText,\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallType: \"function\",\n toolCallId: toolCallId,\n toolName: toolName,\n args: argsText,\n });\n break;\n }\n\n case AssistantStreamChunkType.StepFinish: {\n controller.enqueue({\n type: \"step-finish\",\n ...value,\n });\n break;\n }\n\n // TODO\n case AssistantStreamChunkType.Data:\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.ok) {\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 { CoreMessage } from \"../../types\";\nimport { AttachmentAdapter } from \"../attachment/AttachmentAdapter\";\nimport { FeedbackAdapter } from \"../feedback/FeedbackAdapter\";\nimport { SpeechSynthesisAdapter } from \"../speech/SpeechAdapterTypes\";\nimport { ChatModelAdapter } from \"./ChatModelAdapter\";\n\nexport type LocalRuntimeOptionsBase = {\n maxSteps?: number | undefined;\n /**\n * @deprecated Use `maxSteps` (which is `maxToolRoundtrips` + 1; if you set `maxToolRoundtrips` to 2, set `maxSteps` to 3) instead. This field will be removed in v0.6.\n */\n maxToolRoundtrips?: number | undefined;\n adapters: {\n chatModel: ChatModelAdapter;\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n };\n};\n\n// TODO align LocalRuntimeOptions with LocalRuntimeOptionsBase\nexport type LocalRuntimeOptions = Omit<LocalRuntimeOptionsBase, \"adapters\"> & {\n initialMessages?: readonly CoreMessage[] | undefined;\n adapters?: Omit<LocalRuntimeOptionsBase[\"adapters\"], \"chatModel\"> | undefined;\n};\n\nexport const splitLocalRuntimeOptions = <T extends LocalRuntimeOptions>(\n options: T,\n) => {\n const { initialMessages, maxToolRoundtrips, maxSteps, adapters, ...rest } =\n options;\n\n return {\n localRuntimeOptions: {\n initialMessages,\n maxToolRoundtrips,\n maxSteps,\n adapters,\n },\n otherOptions: rest,\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 { AttachmentAdapter } from \"../attachment\";\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 protected getAttachmentAdapter() {\n return this.runtime.adapters?.attachments;\n }\n\n private _nonTextParts;\n private _previousText;\n private _parentId;\n constructor(\n private runtime: Omit<ThreadRuntimeCore, \"composer\"> & {\n adapters?: { attachments?: AttachmentAdapter | undefined } | undefined;\n },\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 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 type {\n ModelConfigProvider,\n AppendMessage,\n Unsubscribe,\n} from \"../../types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/MessageRepository\";\nimport { DefaultThreadComposerRuntimeCore } from \"../composer/DefaultThreadComposerRuntimeCore\";\nimport {\n AddToolResultOptions,\n ThreadSuggestion,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n SpeechState,\n RuntimeCapabilities,\n SubmittedFeedback,\n ThreadRuntimeEventType,\n} from \"../core/ThreadRuntimeCore\";\nimport { DefaultEditComposerRuntimeCore } from \"../composer/DefaultEditComposerRuntimeCore\";\nimport { SpeechSynthesisAdapter } from \"../speech\";\nimport { FeedbackAdapter } from \"../feedback/FeedbackAdapter\";\nimport { AttachmentAdapter } from \"../attachment\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\n\ntype BaseThreadAdapters = {\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n attachments?: AttachmentAdapter | undefined;\n};\n\nexport abstract class BaseThreadRuntimeCore implements ThreadRuntimeCore {\n private _subscriptions = new Set<() => void>();\n\n protected readonly repository = new MessageRepository();\n public abstract get adapters(): BaseThreadAdapters | undefined;\n\n public abstract get threadId(): string;\n public abstract get isDisabled(): boolean;\n public abstract get suggestions(): readonly ThreadSuggestion[];\n public abstract get extras(): unknown;\n\n public abstract get capabilities(): RuntimeCapabilities;\n public abstract append(message: AppendMessage): void;\n public abstract startRun(parentId: string | null): void;\n public abstract addToolResult(options: AddToolResultOptions): void;\n public abstract cancelRun(): void;\n\n public get messages() {\n return this.repository.getMessages();\n }\n\n public readonly composer = new DefaultThreadComposerRuntimeCore(this);\n\n constructor(private configProvider: ModelConfigProvider) {}\n\n public getModelConfig() {\n return this.configProvider.getModelConfig();\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 getMessageById(messageId: string) {\n return this.repository.getMessage(messageId);\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 protected _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public _notifyEventSubscribers(event: ThreadRuntimeEventType) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n for (const callback of subscribers) callback();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private _submittedFeedback: Record<string, SubmittedFeedback> = {};\n\n public getSubmittedFeedback(messageId: string) {\n return this._submittedFeedback[messageId];\n }\n\n public submitFeedback({ messageId, type }: SubmitFeedbackOptions) {\n const adapter = this.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 this._submittedFeedback[messageId] = { type };\n this._notifySubscribers();\n }\n\n private _stopSpeaking: Unsubscribe | undefined;\n public speech: SpeechState | undefined;\n\n public speak(messageId: string) {\n const adapter = this.adapters?.speech;\n if (!adapter) throw new Error(\"Speech adapter not configured\");\n\n const { message } = this.repository.getMessage(messageId);\n\n this._stopSpeaking?.();\n\n const utterance = adapter.speak(getThreadMessageText(message));\n const unsub = utterance.subscribe(() => {\n if (utterance.status.type === \"ended\") {\n this._stopSpeaking = undefined;\n this.speech = undefined;\n } else {\n this.speech = { messageId, status: utterance.status };\n }\n this._notifySubscribers();\n });\n\n this.speech = { messageId, status: utterance.status };\n this._notifySubscribers();\n\n this._stopSpeaking = () => {\n utterance.cancel();\n unsub();\n this.speech = undefined;\n this._stopSpeaking = undefined;\n };\n }\n\n public stopSpeaking() {\n if (!this._stopSpeaking) throw new Error(\"No message is being spoken\");\n this._stopSpeaking();\n this._notifySubscribers();\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 private _eventSubscribers = new Map<string, Set<() => void>>();\n\n public unstable_on(event: ThreadRuntimeEventType, callback: () => void) {\n if (event === \"model-config-update\") {\n return this.configProvider.subscribe?.(callback) ?? (() => {});\n }\n\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n this._eventSubscribers.set(event, new Set([callback]));\n } else {\n subscribers.add(callback);\n }\n\n return () => {\n const subscribers = this._eventSubscribers.get(event)!;\n subscribers.delete(callback);\n };\n }\n}\n","import { generateId } from \"../../internal\";\nimport type {\n ModelConfigProvider,\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types\";\nimport { fromCoreMessage } from \"../edge\";\nimport type { ChatModelRunResult } from \"./ChatModelAdapter\";\nimport { shouldContinue } from \"./shouldContinue\";\nimport { LocalRuntimeOptionsBase } from \"./LocalRuntimeOptions\";\nimport {\n AddToolResultOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n} from \"../core/ThreadRuntimeCore\";\nimport { BaseThreadRuntimeCore } from \"../core/BaseThreadRuntimeCore\";\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n edit: true,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n attachments: false,\n feedback: false,\n };\n\n private abortController: AbortController | null = null;\n\n public readonly isDisabled = false;\n public readonly suggestions: readonly ThreadSuggestion[] = [];\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n configProvider: ModelConfigProvider,\n public readonly threadId: string,\n options: LocalRuntimeOptionsBase,\n ) {\n super(configProvider);\n\n this._options = options;\n }\n\n private _options: LocalRuntimeOptionsBase;\n\n public get extras() {\n return undefined;\n }\n\n public setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n public 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 this._notifyEventSubscribers(\"run-start\");\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 initialSteps = message.metadata?.steps;\n const initalCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps || m.metadata?.roundtrips;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\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 ...(steps ? { roundtrips: steps } : undefined),\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(steps ? { roundtrips: steps, steps } : 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 maxSteps = this._options.maxSteps\n ? this._options.maxSteps\n : (this._options.maxToolRoundtrips ?? 1) + 1;\n\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\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.adapters.chatModel.run({\n messages,\n abortSignal: this.abortController.signal,\n config: this.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 public cancelRun() {\n this.abortController?.abort();\n this.abortController = null;\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","import type { Unsubscribe } from \"../../types\";\nimport {\n ThreadManagerMetadata,\n ThreadManagerRuntimeCore,\n} from \"../core/ThreadManagerRuntimeCore\";\nimport { ExportedMessageRepository } from \"../utils/MessageRepository\";\nimport { generateId } from \"../../utils/idUtils\";\nimport { LocalThreadRuntimeCore } from \"./LocalThreadRuntimeCore\";\n\nexport type LocalThreadData = {\n data: ExportedMessageRepository;\n metadata: ThreadManagerMetadata;\n isArchived: boolean;\n};\n\nexport type LocalThreadFactory = (\n threadId: string,\n data: ExportedMessageRepository,\n) => LocalThreadRuntimeCore;\n\nexport class LocalThreadManagerRuntimeCore implements ThreadManagerRuntimeCore {\n private _threadData = new Map<string, LocalThreadData>();\n\n private _threads: readonly ThreadManagerMetadata[] = [];\n private _archivedThreads: readonly ThreadManagerMetadata[] = [];\n\n public get threads() {\n return this._threads;\n }\n\n public get archivedThreads() {\n return this._archivedThreads;\n }\n\n private _mainThread: LocalThreadRuntimeCore;\n\n public get mainThread(): LocalThreadRuntimeCore {\n return this._mainThread;\n }\n\n constructor(private _threadFactory: LocalThreadFactory) {\n this._mainThread = this._threadFactory(generateId(), { messages: [] });\n }\n\n public switchToThread(threadId: string): void {\n if (this._mainThread.threadId === threadId) return;\n\n const data = this._threadData.get(threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n const thread = this._threadFactory(threadId, data.data);\n this._performThreadSwitch(thread);\n }\n\n public switchToNewThread(): void {\n if (!this._mainThread) return;\n\n const thread = this._threadFactory(generateId(), { messages: [] });\n this._performThreadSwitch(thread);\n }\n\n private _performThreadSwitch(newThreadCore: LocalThreadRuntimeCore) {\n if (this._mainThread) {\n const data = this._threadData.get(this._mainThread.threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n const exprt = this._mainThread.export();\n data.data = exprt;\n }\n\n this._mainThread._notifyEventSubscribers(\"switched-away\");\n this._mainThread = newThreadCore;\n newThreadCore._notifyEventSubscribers(\"switched-to\");\n\n this._notifySubscribers();\n }\n\n private _performMoveOp(\n threadId: string,\n operation: \"archive\" | \"unarchive\" | \"delete\",\n ) {\n const data = this._threadData.get(threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n if (operation === \"archive\" && data.isArchived) return;\n if (operation === \"unarchive\" && !data.isArchived) return;\n\n if (operation === \"archive\") {\n data.isArchived = true;\n this._archivedThreads = [...this._archivedThreads, data.metadata];\n }\n if (operation === \"unarchive\") {\n data.isArchived = false;\n this._threads = [...this._threads, data.metadata];\n }\n if (operation === \"delete\") {\n this._threadData.delete(threadId);\n }\n\n if (\n operation === \"archive\" ||\n (operation === \"delete\" && data.isArchived)\n ) {\n this._archivedThreads = this._archivedThreads.filter(\n (t) => t.threadId !== threadId,\n );\n }\n\n if (\n operation === \"unarchive\" ||\n (operation === \"delete\" && !data.isArchived)\n ) {\n this._threads = this._threads.filter((t) => t.threadId !== threadId);\n }\n\n this._notifySubscribers();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const data = this._threadData.get(threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n data.metadata = {\n ...data.metadata,\n title: newTitle,\n };\n\n const threadList = data.isArchived ? this.archivedThreads : this.threads;\n const idx = threadList.findIndex((t) => t.threadId === threadId);\n const updatedThreadList = threadList.toSpliced(idx, 1, data.metadata);\n if (data.isArchived) {\n this._archivedThreads = updatedThreadList;\n } else {\n this._threads = updatedThreadList;\n }\n this._notifySubscribers();\n }\n\n public async archive(threadId: string): Promise<void> {\n this._performMoveOp(threadId, \"archive\");\n }\n\n public async unarchive(threadId: string): Promise<void> {\n this._performMoveOp(threadId, \"unarchive\");\n }\n\n public async delete(threadId: string): Promise<void> {\n this._performMoveOp(threadId, \"delete\");\n }\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 _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n","import type { CoreMessage } from \"../../types/AssistantTypes\";\nimport { BaseAssistantRuntimeCore } from \"../core/BaseAssistantRuntimeCore\";\nimport { LocalThreadRuntimeCore } from \"./LocalThreadRuntimeCore\";\nimport { LocalRuntimeOptionsBase } from \"./LocalRuntimeOptions\";\nimport { fromCoreMessages } from \"../edge/converters/fromCoreMessage\";\nimport { LocalThreadManagerRuntimeCore } from \"./LocalThreadManagerRuntimeCore\";\nimport { ExportedMessageRepository } from \"../utils/MessageRepository\";\n\nconst getExportFromInitialMessages = (\n initialMessages: readonly CoreMessage[],\n): ExportedMessageRepository => {\n const messages = fromCoreMessages(initialMessages);\n return {\n messages: messages.map((m, idx) => ({\n parentId: messages[idx - 1]?.id ?? null,\n message: m,\n })),\n };\n};\n\nexport class LocalRuntimeCore extends BaseAssistantRuntimeCore {\n public readonly threadManager;\n\n private _options: LocalRuntimeOptionsBase;\n\n constructor(\n options: LocalRuntimeOptionsBase,\n initialMessages?: CoreMessage[],\n ) {\n super();\n\n this._options = options;\n\n this.threadManager = new LocalThreadManagerRuntimeCore((threadId, data) => {\n const thread = new LocalThreadRuntimeCore(\n this._proxyConfigProvider,\n threadId,\n this._options,\n );\n thread.import(data);\n return thread;\n });\n\n if (initialMessages) {\n this.threadManager.mainThread.import(\n getExportFromInitialMessages(initialMessages),\n );\n }\n }\n\n public setOptions(options: LocalRuntimeOptionsBase) {\n this._options = options;\n\n this.threadManager.mainThread.setOptions(options);\n }\n\n public reset({\n initialMessages,\n }: {\n initialMessages?: readonly CoreMessage[] | undefined;\n } = {}) {\n this.threadManager.switchToNewThread();\n if (!initialMessages) return;\n\n this.threadManager.mainThread.import(\n getExportFromInitialMessages(initialMessages),\n );\n }\n}\n","import { useEffect, useMemo, useState } from \"react\";\nimport { ExternalStoreRuntimeCore } from \"./ExternalStoreRuntimeCore\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { AssistantRuntimeImpl } from \"../../api/AssistantRuntime\";\nimport { ThreadRuntimeImpl } from \"../../api/ThreadRuntime\";\n\nexport const useExternalStoreRuntime = <T,>(store: ExternalStoreAdapter<T>) => {\n const [runtime] = useState(() => new ExternalStoreRuntimeCore(store));\n\n useEffect(() => {\n runtime.setStore(store);\n });\n\n return useMemo(\n () => AssistantRuntimeImpl.create(runtime, ThreadRuntimeImpl),\n [runtime],\n );\n};\n","import type { Unsubscribe } from \"../../types\";\nimport { ExternalStoreThreadRuntimeCore } from \"./ExternalStoreThreadRuntimeCore\";\nimport { ThreadManagerRuntimeCore } from \"../core/ThreadManagerRuntimeCore\";\nimport { ExternalStoreThreadManagerAdapter } from \"./ExternalStoreAdapter\";\n\nexport type ExternalStoreThreadFactory = (\n threadId: string,\n) => ExternalStoreThreadRuntimeCore;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst DEFAULT_THREAD_ID = \"DEFAULT_THREAD_ID\";\n\nexport class ExternalStoreThreadManagerRuntimeCore\n implements ThreadManagerRuntimeCore\n{\n public get threads() {\n return this.adapter.threads ?? EMPTY_ARRAY;\n }\n\n public get archivedThreads() {\n return this.adapter.archivedThreads ?? EMPTY_ARRAY;\n }\n\n private _mainThread: ExternalStoreThreadRuntimeCore;\n\n public get mainThread() {\n return this._mainThread;\n }\n\n constructor(\n private adapter: ExternalStoreThreadManagerAdapter = {},\n private threadFactory: ExternalStoreThreadFactory,\n ) {\n this._mainThread = this.threadFactory(DEFAULT_THREAD_ID);\n }\n\n public setAdapter(adapter: ExternalStoreThreadManagerAdapter) {\n const previousAdapter = this.adapter;\n this.adapter = adapter;\n\n const newThreadId = adapter.threadId ?? DEFAULT_THREAD_ID;\n const newThreads = adapter.threads ?? EMPTY_ARRAY;\n const newArchivedThreads = adapter.archivedThreads ?? EMPTY_ARRAY;\n\n if (\n previousAdapter.threadId === newThreadId &&\n previousAdapter.threads === newThreads &&\n previousAdapter.archivedThreads === newArchivedThreads\n ) {\n return;\n }\n\n if (previousAdapter.threadId !== newThreadId) {\n this._mainThread._notifyEventSubscribers(\"switched-away\");\n this._mainThread = this.threadFactory(newThreadId);\n this._mainThread._notifyEventSubscribers(\"switched-to\");\n }\n\n this._notifySubscribers();\n }\n\n public switchToThread(threadId: string): void {\n if (this._mainThread?.threadId === threadId) return;\n const onSwitchToThread = this.adapter.onSwitchToThread;\n if (!onSwitchToThread)\n throw new Error(\n \"External store adapter does not support switching to thread\",\n );\n onSwitchToThread(threadId);\n }\n\n public switchToNewThread(): void {\n const onSwitchToNewThread = this.adapter.onSwitchToNewThread;\n if (!onSwitchToNewThread)\n throw new Error(\n \"External store adapter does not support switching to new thread\",\n );\n\n onSwitchToNewThread();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const onRename = this.adapter.onRename;\n if (!onRename)\n throw new Error(\"External store adapter does not support renaming\");\n\n onRename(threadId, newTitle);\n }\n\n public async archive(threadId: string): Promise<void> {\n const onArchive = this.adapter.onArchive;\n if (!onArchive)\n throw new Error(\"External store adapter does not support archiving\");\n\n onArchive(threadId);\n }\n\n public async unarchive(threadId: string): Promise<void> {\n const onUnarchive = this.adapter.onUnarchive;\n if (!onUnarchive)\n throw new Error(\"External store adapter does not support unarchiving\");\n\n onUnarchive(threadId);\n }\n\n public async delete(threadId: string): Promise<void> {\n const onDelete = this.adapter.onDelete;\n if (!onDelete)\n throw new Error(\"External store adapter does not support deleting\");\n\n onDelete(threadId);\n }\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 _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n","import { ThreadMessage } from \"../../types\";\n\nexport const symbolInnerMessage = Symbol(\"innerMessage\");\n\nexport type ExternalStoreThreadMessage<T> = ThreadMessage & {\n [symbolInnerMessage]?: T;\n};\n\nexport const getExternalStoreMessage = <T,>(message: ThreadMessage) => {\n return (message as ExternalStoreThreadMessage<T>)[symbolInnerMessage];\n};\n","import { ThreadMessage } from \"../../types\";\n\nexport type ConverterCallback<TIn> = (\n cache: ThreadMessage | undefined,\n message: TIn,\n idx: number,\n) => ThreadMessage;\n\nexport class ThreadMessageConverter {\n private readonly cache = new WeakMap<WeakKey, ThreadMessage>();\n\n convertMessages<TIn extends WeakKey>(\n messages: TIn[],\n converter: ConverterCallback<TIn>,\n ): ThreadMessage[] {\n return messages.map((m, idx) => {\n const cached = this.cache.get(m);\n const newMessage = converter(cached, m, idx);\n this.cache.set(m, newMessage);\n return newMessage;\n });\n }\n}\n","import { MessageStatus } from \"../../types\";\n\nconst AUTO_STATUS_RUNNING = Object.freeze({ type: \"running\" });\nconst AUTO_STATUS_COMPLETE = Object.freeze({\n type: \"complete\",\n reason: \"unknown\",\n});\n\nexport const isAutoStatus = (status: MessageStatus) =>\n status === AUTO_STATUS_RUNNING || status === AUTO_STATUS_COMPLETE;\n\nexport const getAutoStatus = (isLast: boolean, isRunning: boolean) =>\n isLast && isRunning ? AUTO_STATUS_RUNNING : AUTO_STATUS_COMPLETE;\n","import {\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, ThreadSuggestion } from \"../core\";\n\nimport { AppendMessage, ModelConfigProvider, ThreadMessage } 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 {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../core/ThreadRuntimeCore\";\nimport { BaseThreadRuntimeCore } from \"../core/BaseThreadRuntimeCore\";\n\nconst EMPTY_ARRAY = Object.freeze([]);\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\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\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 speech: false,\n attachments: false,\n feedback: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n public threadId!: string;\n private _messages!: ThreadMessage[];\n public isDisabled!: boolean;\n\n public override get messages() {\n return this._messages;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n configProvider: ModelConfigProvider,\n threadId: string,\n store: ExternalStoreAdapter<any>,\n ) {\n super(configProvider);\n this.threadId = threadId;\n this.setStore(store);\n }\n\n public setStore(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\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.extras = store.extras;\n this.suggestions = store.suggestions ?? EMPTY_ARRAY;\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 speech: this._store.adapters?.speech !== 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 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 override 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 private updateMessages = (messages: ThreadMessage[]) => {\n this._store.setMessages?.(\n messages.flatMap(getExternalStoreMessage).filter((m) => m != null),\n );\n };\n}\n","import { BaseAssistantRuntimeCore } from \"../../internal\";\nimport { ExternalStoreThreadManagerRuntimeCore } from \"./ExternalStoreThreadManagementAdapter\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { ExternalStoreThreadRuntimeCore } from \"./ExternalStoreThreadRuntimeCore\";\n\nconst getThreadManagerAdapter = (store: ExternalStoreAdapter<any>) => {\n return {\n threadId: store.threadId,\n onSwitchToNewThread: store.onSwitchToNewThread,\n onSwitchToThread: store.onSwitchToThread,\n ...store.adapters?.threadManager,\n };\n};\n\nexport class ExternalStoreRuntimeCore extends BaseAssistantRuntimeCore {\n public readonly threadManager;\n\n private _store: ExternalStoreAdapter<any>;\n\n constructor(store: ExternalStoreAdapter<any>) {\n super();\n this._store = store;\n this.threadManager = new ExternalStoreThreadManagerRuntimeCore(\n getThreadManagerAdapter(store),\n (threadId) =>\n new ExternalStoreThreadRuntimeCore(\n this._proxyConfigProvider,\n threadId,\n this._store,\n ),\n );\n }\n\n public setStore(store: ExternalStoreAdapter<any>) {\n this._store = store;\n this.threadManager.setAdapter(getThreadManagerAdapter(store));\n this.threadManager.mainThread.setStore(store);\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\";\nimport { splitLocalRuntimeOptions } from \"../local/LocalRuntimeOptions\";\n\nexport type DangerousInBrowserRuntimeOptions =\n DangerousInBrowserAdapterOptions & LocalRuntimeOptions;\n\nexport const useDangerousInBrowserRuntime = (\n options: DangerousInBrowserRuntimeOptions,\n) => {\n const { localRuntimeOptions, otherOptions } =\n splitLocalRuntimeOptions(options);\n const [adapter] = useState(() => new DangerousInBrowserAdapter(otherOptions));\n return useLocalRuntime(adapter, localRuntimeOptions);\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 { SpeechSynthesisAdapter } from \"./SpeechAdapterTypes\";\n\nexport class WebSpeechSynthesisAdapter implements SpeechSynthesisAdapter {\n speak(text: string): SpeechSynthesisAdapter.Utterance {\n const utterance = new SpeechSynthesisUtterance(text);\n\n const subscribers = 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 subscribers.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 subscribe: (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 subscribers.add(callback);\n return () => {\n subscribers.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 | undefined;\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 welcome?: {\n message?: string | undefined;\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 | undefined;\n\n assistantAvatar?: AvatarProps | undefined;\n\n welcome?: ThreadWelcomeConfig | undefined;\n assistantMessage?: AssistantMessageConfig | undefined;\n userMessage?: UserMessageConfig | undefined;\n\n branchPicker?: BranchPickerConfig | undefined;\n\n composer?: ComposerConfig | undefined;\n\n strings?: StringsConfig | undefined;\n\n tools?: AssistantToolUI[] | undefined; // TODO add AssistantTool support\n\n components?:\n | {\n Composer?: ComponentType | undefined;\n ThreadWelcome?: ComponentType | undefined;\n }\n | undefined;\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 speechSupported = useThread((t) => t.capabilities.speech);\n return allowSpeak && (!ensureCapability || speechSupported);\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\nnamespace AssistantActionBarCopy {\n export type Element = ActionBarPrimitive.Copy.Element;\n export type Props = Partial<TooltipIconButtonProps> & {\n copiedDuration?: number | undefined;\n };\n}\n\nconst AssistantActionBarCopy = forwardRef<\n AssistantActionBarCopy.Element,\n AssistantActionBarCopy.Props\n>(({ copiedDuration, ...props }, ref) => {\n const {\n strings: {\n assistantMessage: { copy: { tooltip = \"Copy\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n return (\n <ActionBarPrimitive.Copy copiedDuration={copiedDuration} 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\nnamespace AssistantActionBarSpeak {\n export type Element = ActionBarPrimitive.Speak.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarSpeak = forwardRef<\n AssistantActionBarSpeak.Element,\n AssistantActionBarSpeak.Props\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\nnamespace AssistantActionBarStopSpeaking {\n export type Element = ActionBarPrimitive.StopSpeaking.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarStopSpeaking = forwardRef<\n AssistantActionBarStopSpeaking.Element,\n AssistantActionBarStopSpeaking.Props\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\nnamespace AssistantActionBarReload {\n export type Element = ActionBarPrimitive.Reload.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarReload = forwardRef<\n AssistantActionBarReload.Element,\n AssistantActionBarReload.Props\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\nnamespace AssistantActionBarFeedbackPositive {\n export type Element = ActionBarPrimitive.FeedbackPositive.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarFeedbackPositive = forwardRef<\n AssistantActionBarFeedbackPositive.Element,\n AssistantActionBarFeedbackPositive.Props\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\nnamespace AssistantActionBarFeedbackNegative {\n export type Element = ActionBarPrimitive.FeedbackNegative.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarFeedbackNegative = forwardRef<\n AssistantActionBarFeedbackNegative.Element,\n AssistantActionBarFeedbackNegative.Props\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 } 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\n/**\n * @deprecated Use `AssistantMessage.Content.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantMessageContentProps = AssistantMessageContent.Props;\n\nnamespace AssistantMessageContent {\n export type Element = HTMLDivElement;\n export type Props = MessagePrimitive.Content.Props &\n ComponentPropsWithoutRef<\"div\">;\n}\n\nconst AssistantMessageContent = forwardRef<\n AssistantMessageContent.Element,\n AssistantMessageContent.Props\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\nnamespace BranchPickerPrevious {\n export type Element = BranchPickerPrimitive.Previous.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst BranchPickerPrevious = forwardRef<\n BranchPickerPrevious.Element,\n BranchPickerPrevious.Props\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\nnamespace BranchPickerState {\n export type Element = HTMLSpanElement;\n export type Props = ComponentPropsWithoutRef<\"span\">;\n}\n\nconst BranchPickerState = forwardRef<\n BranchPickerState.Element,\n BranchPickerState.Props\n>((props, ref) => {\n return (\n <BranchPickerStateWrapper {...props} ref={ref}>\n <BranchPickerPrimitive.Number /> / <BranchPickerPrimitive.Count />\n </BranchPickerStateWrapper>\n );\n});\n\nBranchPickerState.displayName = \"BranchPickerState\";\n\nnamespace BranchPickerNext {\n export type Element = BranchPickerPrimitive.Next.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst BranchPickerNext = forwardRef<\n BranchPickerNext.Element,\n BranchPickerNext.Props\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 { AssistantModalPrimitive } 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\nnamespace AssistantModalRoot {\n export type Props = AssistantModalPrimitive.Root.Props &\n ThreadConfigProviderProps;\n}\n\nconst AssistantModalRoot: FC<AssistantModalRoot.Props> = ({\n config,\n ...props\n}) => {\n return (\n <ThreadConfigProvider config={config}>\n <AssistantModalPrimitive.Root {...props} />\n </ThreadConfigProvider>\n );\n};\n\nAssistantModalRoot.displayName = \"AssistantModalRoot\";\n\nnamespace AssistantModalTrigger {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantModalTrigger = forwardRef<\n AssistantModalTrigger.Element,\n AssistantModalTrigger.Props\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\nnamespace AssistantModalButton {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps> & {\n \"data-state\"?: \"open\" | \"closed\";\n };\n}\n\nconst AssistantModalButton = forwardRef<\n AssistantModalButton.Element,\n AssistantModalButton.Props\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 } from \"../primitives\";\nimport { useThread } from \"../context\";\n\nconst Thread: FC<ThreadConfig> = (config) => {\n const {\n components: {\n Composer: ComposerComponent = Composer,\n ThreadWelcome: ThreadWelcomeComponent = ThreadWelcome,\n } = {},\n } = config;\n return (\n <ThreadRoot config={config}>\n <ThreadViewport>\n <ThreadWelcomeComponent />\n <ThreadMessages />\n <ThreadFollowupSuggestions />\n <ThreadViewportFooter>\n <ThreadScrollToBottom />\n <ComposerComponent />\n </ThreadViewportFooter>\n </ThreadViewport>\n </ThreadRoot>\n );\n};\n\n/**\n * @deprecated Use `Thread.Root.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadRootProps = ThreadRoot.Props;\n\nnamespace ThreadRoot {\n export type Element = HTMLDivElement;\n export type Props = ThreadPrimitive.Root.Props & ThreadConfigProviderProps;\n}\n\nconst ThreadRootStyled = withDefaults(ThreadPrimitive.Root, {\n className: \"aui-root aui-thread-root\",\n});\n\nconst ThreadRoot = forwardRef<ThreadRoot.Element, ThreadRoot.Props>(\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 unstable_flexGrowDiv?: boolean;\n components?: {\n UserMessage?: ComponentType | undefined;\n EditComposer?: ComponentType | undefined;\n AssistantMessage?: ComponentType | undefined;\n SystemMessage?: ComponentType | undefined;\n };\n}> = ({ components, unstable_flexGrowDiv: flexGrowDiv = true, ...rest }) => {\n return (\n <>\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 {flexGrowDiv && (\n <ThreadPrimitive.If empty={false}>\n <div style={{ flexGrow: 1 }} />\n </ThreadPrimitive.If>\n )}\n </>\n );\n};\n\nThreadMessages.displayName = \"ThreadMessages\";\n\nconst ThreadFollowupSuggestions: FC = () => {\n const suggestions = useThread((t) => t.suggestions);\n\n return (\n <ThreadPrimitive.If empty={false} running={false}>\n <div className=\"aui-thread-followup-suggestions\">\n {suggestions?.map((suggestion, idx) => (\n <ThreadPrimitive.Suggestion\n key={idx}\n className=\"aui-thread-followup-suggestion\"\n prompt={suggestion.prompt}\n method=\"replace\"\n autoSend\n >\n {suggestion.prompt}\n </ThreadPrimitive.Suggestion>\n ))}\n </div>\n </ThreadPrimitive.If>\n );\n};\n\nconst ThreadScrollToBottomIconButton = withDefaults(TooltipIconButton, {\n variant: \"outline\",\n className: \"aui-thread-scroll-to-bottom\",\n});\n\nnamespace ThreadScrollToBottom {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ThreadScrollToBottom = forwardRef<\n ThreadScrollToBottom.Element,\n ThreadScrollToBottom.Props\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 FollowupSuggestions: ThreadFollowupSuggestions,\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 Attachment from \"./attachment\";\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\nnamespace ComposerInput {\n export type Element = HTMLTextAreaElement;\n export type Props = ComponentPropsWithoutRef<typeof ComposerInputStyled>;\n}\n\n/**\n * @deprecated Use `ComposerInput.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerInputProps = ComposerInput.Props;\n\nconst ComposerInput = forwardRef<ComposerInput.Element, ComposerInput.Props>(\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\nnamespace ComposerAttachments {\n export type Props = Partial<ComposerPrimitive.Attachments.Props>;\n}\n\nconst ComposerAttachments: FC<ComposerAttachments.Props> = ({ components }) => {\n return (\n <ComposerAttachmentsContainer>\n <ComposerPrimitive.Attachments\n components={{\n ...components,\n Attachment: components?.Attachment ?? Attachment,\n }}\n />\n </ComposerAttachmentsContainer>\n );\n};\n\nconst ComposerAttachButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-attach\",\n});\n\nnamespace ComposerAddAttachment {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ComposerAddAttachment = forwardRef<\n ComposerAddAttachment.Element,\n ComposerAddAttachment.Props\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\nnamespace ComposerSend {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ComposerSend = forwardRef<ComposerSend.Element, ComposerSend.Props>(\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);\n\nComposerSend.displayName = \"ComposerSend\";\n\nconst ComposerCancelButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-cancel\",\n});\n\nnamespace ComposerCancel {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ComposerCancel = forwardRef<ComposerCancel.Element, ComposerCancel.Props>(\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);\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 {\n forwardRef,\n PropsWithChildren,\n useEffect,\n useState,\n type FC,\n} from \"react\";\nimport { CircleXIcon, FileIcon } 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 { AttachmentPrimitive } from \"../primitives\";\nimport { useAttachment } from \"../context/react/AttachmentContext\";\nimport {\n AvatarImage,\n AvatarRoot,\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"./base\";\nimport { Dialog, DialogTrigger, DialogContent } from \"./base/dialog\";\nimport { AvatarFallback } from \"@radix-ui/react-avatar\";\n\nconst AttachmentRoot = withDefaults(AttachmentPrimitive.Root, {\n className: \"aui-attachment-root\",\n});\n\nAttachmentRoot.displayName = \"AttachmentRoot\";\n\nconst useFileSrc = (file: File | undefined) => {\n const [src, setSrc] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n if (!file) {\n setSrc(undefined);\n return;\n }\n\n const objectUrl = URL.createObjectURL(file);\n setSrc(objectUrl);\n\n return () => {\n URL.revokeObjectURL(objectUrl);\n };\n }, [file]);\n\n return src;\n};\n\nconst useAttachmentSrc = () => {\n const { file, src } = useAttachment((a): { file?: File; src?: string } => {\n if (a.type !== \"image\") return {};\n if (a.file) return { file: a.file };\n const src = a.content?.filter((c) => c.type === \"image\")[0]?.image;\n if (!src) return {};\n return { src };\n });\n\n return useFileSrc(file) ?? src;\n};\n\ntype AttachmentPreviewProps = {\n src: string;\n};\n\nconst AttachmentPreview: FC<AttachmentPreviewProps> = ({ src }) => {\n const [isLoaded, setIsLoaded] = useState(false);\n\n return (\n // eslint-disable-next-line @next/next/no-img-element\n <img\n src={src}\n style={{\n width: \"auto\",\n height: \"auto\",\n maxWidth: \"75dvh\",\n maxHeight: \"75dvh\",\n display: isLoaded ? \"block\" : \"none\",\n overflow: \"clip\",\n }}\n onLoad={() => setIsLoaded(true)}\n alt=\"Image Preview\"\n />\n );\n};\n\nconst AttachmentPreviewDialog: FC<PropsWithChildren> = ({ children }) => {\n const src = useAttachmentSrc();\n\n if (!src) return children;\n\n return (\n <Dialog>\n <DialogTrigger className=\"aui-attachment-preview-trigger\" asChild>\n {children}\n </DialogTrigger>\n <DialogContent>\n <AttachmentPreview src={src} />\n </DialogContent>\n </Dialog>\n );\n};\n\nconst AttachmentThumb: FC = () => {\n const isImage = useAttachment((a) => a.type === \"image\");\n const src = useAttachmentSrc();\n return (\n <AvatarRoot className=\"aui-attachment-thumb\">\n <AvatarFallback delayMs={isImage ? 200 : 0}>\n <FileIcon />\n </AvatarFallback>\n <AvatarImage src={src}></AvatarImage>\n </AvatarRoot>\n );\n};\n\nconst Attachment: FC = () => {\n const canRemove = useAttachment((a) => a.source !== \"message\");\n const typeLabel = useAttachment((a) => {\n const type = a.type;\n switch (type) {\n case \"image\":\n return \"Image\";\n case \"document\":\n return \"Document\";\n case \"file\":\n return \"File\";\n default:\n const _exhaustiveCheck: never = type;\n throw new Error(`Unknown attachment type: ${_exhaustiveCheck}`);\n }\n });\n return (\n <Tooltip>\n <AttachmentPreviewDialog>\n <TooltipTrigger asChild>\n <AttachmentRoot>\n <AttachmentThumb />\n <div className=\"aui-attachment-text\">\n <p className=\"aui-attachment-name\">\n <AttachmentPrimitive.Name />\n </p>\n <p className=\"aui-attachment-type\">{typeLabel}</p>\n </div>\n {canRemove && <AttachmentRemove />}\n </AttachmentRoot>\n </TooltipTrigger>\n </AttachmentPreviewDialog>\n <TooltipContent side=\"top\">\n <AttachmentPrimitive.Name />\n </TooltipContent>\n </Tooltip>\n );\n};\n\nAttachment.displayName = \"Attachment\";\n\nnamespace AttachmentRemove {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AttachmentRemove = forwardRef<\n AttachmentRemove.Element,\n AttachmentRemove.Props\n>((props, ref) => {\n const {\n strings: {\n composer: { removeAttachment: { tooltip = \"Remove file\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n return (\n <AttachmentPrimitive.Remove asChild>\n <TooltipIconButton\n tooltip={tooltip}\n className=\"aui-attachment-remove\"\n side=\"top\"\n {...props}\n ref={ref}\n >\n {props.children ?? <CircleXIcon />}\n </TooltipIconButton>\n </AttachmentPrimitive.Remove>\n );\n});\n\nAttachmentRemove.displayName = \"AttachmentRemove\";\n\nconst exports = {\n Root: AttachmentRoot,\n Remove: AttachmentRemove,\n};\n\nexport default Object.assign(Attachment, exports) as typeof Attachment &\n typeof exports;\n","\"use client\";\n\nimport * as React from \"react\";\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\";\n\nimport classNames from \"classnames\";\n\nconst Dialog = DialogPrimitive.Root;\n\nconst DialogTrigger = DialogPrimitive.Trigger;\n\nconst DialogPortal = DialogPrimitive.Portal;\n\nconst DialogClose = DialogPrimitive.Close;\n\nconst DialogOverlay = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Overlay>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Overlay\n ref={ref}\n className={classNames(\"aui-dialog-overlay\", className)}\n {...props}\n />\n));\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName;\n\nconst DialogContent = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Content\n ref={ref}\n className={classNames(\"aui-dialog-content\", className)}\n {...props}\n >\n {children}\n {/* <DialogPrimitive.Close className=\"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none\">\n <XIcon className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close> */}\n </DialogPrimitive.Content>\n </DialogPortal>\n));\nDialogContent.displayName = DialogPrimitive.Content.displayName;\n\n// const DialogHeader = ({\n// className,\n// ...props\n// }: React.HTMLAttributes<HTMLDivElement>) => (\n// <div\n// className={classNames(\n// \"flex flex-col space-y-1.5 text-center sm:text-left\",\n// className,\n// )}\n// {...props}\n// />\n// );\n// DialogHeader.displayName = \"DialogHeader\";\n\n// const DialogFooter = ({\n// className,\n// ...props\n// }: React.HTMLAttributes<HTMLDivElement>) => (\n// <div\n// className={classNames(\n// \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n// className,\n// )}\n// {...props}\n// />\n// );\n// DialogFooter.displayName = \"DialogFooter\";\n\n// const DialogTitle = React.forwardRef<\n// React.ElementRef<typeof DialogPrimitive.Title>,\n// React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n// >(({ className, ...props }, ref) => (\n// <DialogPrimitive.Title\n// ref={ref}\n// className={classNames(\n// \"text-lg font-semibold leading-none tracking-tight\",\n// className,\n// )}\n// {...props}\n// />\n// ));\n// DialogTitle.displayName = DialogPrimitive.Title.displayName;\n\n// const DialogDescription = React.forwardRef<\n// React.ElementRef<typeof DialogPrimitive.Description>,\n// React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n// >(({ className, ...props }, ref) => (\n// <DialogPrimitive.Description\n// ref={ref}\n// className={classNames(\"text-muted-foreground text-sm\", className)}\n// {...props}\n// />\n// ));\n// DialogDescription.displayName = DialogPrimitive.Description.displayName;\n\nexport {\n Dialog,\n DialogPortal,\n DialogOverlay,\n DialogTrigger,\n DialogClose,\n DialogContent,\n // DialogHeader,\n // DialogFooter,\n // DialogTitle,\n // DialogDescription,\n};\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\";\nimport { useThread } from \"../context\";\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\nnamespace ThreadWelcomeRoot {\n export type Element = HTMLDivElement;\n export type Props = ComponentPropsWithoutRef<\"div\">;\n}\n\nconst ThreadWelcomeRoot = forwardRef<\n ThreadWelcomeRoot.Element,\n ThreadWelcomeRoot.Props\n>((props, ref) => {\n return (\n <ThreadPrimitive.Empty>\n <ThreadWelcomeRootStyled {...props} ref={ref} />\n </ThreadPrimitive.Empty>\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\n/**\n * @deprecated Use `ThreadWelcome.Message.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadWelcomeMessageProps = ThreadWelcomeMessage.Props;\n\nnamespace ThreadWelcomeMessage {\n export type Element = HTMLParagraphElement;\n export type Props = Omit<\n ComponentPropsWithoutRef<typeof ThreadWelcomeMessageStyled>,\n \"children\"\n > & { message?: string | undefined };\n}\n\nconst ThreadWelcomeMessage = forwardRef<\n ThreadWelcomeMessage.Element,\n ThreadWelcomeMessage.Props\n>(({ message: messageProp, ...rest }, ref) => {\n const {\n welcome: { message } = {},\n strings: {\n welcome: { message: defaultMessage = \"How can I help you today?\" } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ThreadWelcomeMessageStyled {...rest} ref={ref}>\n {messageProp ?? message ?? defaultMessage}\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 prompt={prompt} method=\"replace\" autoSend>\n <span className=\"aui-thread-welcome-suggestion-text\">\n {text ?? prompt}\n </span>\n </ThreadWelcomeSuggestionStyled>\n );\n};\n\nconst ThreadWelcomeSuggestions: FC = () => {\n const suggestions2 = useThread((t) => t.suggestions);\n const { welcome: { suggestions } = {} } = useThreadConfig();\n\n const finalSuggestions = suggestions2.length ? suggestions2 : suggestions;\n\n return (\n <ThreadWelcomeSuggestionContainer>\n {finalSuggestions?.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 } from \"../primitives\";\nimport Attachment from \"./attachment\";\n\nconst UserMessage: FC = () => {\n return (\n <UserMessageRoot>\n <UserMessageAttachments />\n {/* TODO this is temporary until we place the UserActionBar in a better place */}\n <MessagePrimitive.If hasContent>\n <UserActionBar />\n <UserMessageContent />\n </MessagePrimitive.If>\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\n/**\n * @deprecated Use `UserMessage.Content.Props` instead. This will be removed in 0.6.\n */\nexport type UserMessageContentProps = UserMessageContent.Props;\n\nnamespace UserMessageContent {\n export type Element = HTMLDivElement;\n export type Props = MessagePrimitive.Content.Props &\n ComponentPropsWithoutRef<\"div\">;\n}\n\nconst UserMessageContent = forwardRef<\n UserMessageContent.Element,\n UserMessageContent.Props\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\nUserMessageContent.displayName = \"UserMessageContent\";\n\nconst UserMessageAttachmentsContainer = withDefaults(\"div\", {\n className: \"aui-user-message-attachments\",\n});\n\n/**\n * @deprecated Use `UserMessage.Attachments.Props` instead. This will be removed in 0.6.\n */\nexport type UserMessageAttachmentsProps = UserMessageAttachments.Props;\n\nnamespace UserMessageAttachments {\n export type Props = Partial<MessagePrimitive.Attachments.Props>;\n}\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 ?? Attachment,\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\nnamespace UserActionBarEdit {\n export type Element = ActionBarPrimitive.Edit.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst UserActionBarEdit = forwardRef<\n UserActionBarEdit.Element,\n UserActionBarEdit.Props\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 { 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\nnamespace EditComposerCancel {\n export type Element = HTMLButtonElement;\n export type Props = Partial<ButtonProps>;\n}\n\nconst EditComposerCancel = forwardRef<\n EditComposerCancel.Element,\n EditComposerCancel.Props\n>((props, ref) => {\n const {\n strings: { editComposer: { cancel: { label = \"Cancel\" } = {} } = {} } = {},\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\nEditComposerCancel.displayName = \"EditComposerCancel\";\n\nnamespace EditComposerSend {\n export type Element = HTMLButtonElement;\n export type Props = Partial<ButtonProps>;\n}\n\nconst EditComposerSend = forwardRef<\n EditComposerSend.Element,\n EditComposerSend.Props\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\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/model-config/useInlineRender.tsx","../src/primitive-hooks/actionBar/useActionBarCopy.tsx","../src/primitive-hooks/actionBar/useActionBarEdit.tsx","../src/primitive-hooks/actionBar/useActionBarReload.tsx","../src/utils/combined/useCombinedStore.ts","../src/utils/combined/createCombinedStore.ts","../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/primitives/assistantModal/scope.tsx","../src/primitives/assistantModal/AssistantModalTrigger.tsx","../src/primitives/assistantModal/AssistantModalContent.tsx","../src/primitives/assistantModal/AssistantModalAnchor.tsx","../src/primitives/attachment/index.ts","../src/primitives/attachment/AttachmentRoot.tsx","../src/primitives/attachment/AttachmentThumb.tsx","../src/context/react/AttachmentContext.ts","../src/primitives/attachment/AttachmentName.tsx","../src/primitive-hooks/attachment/useAttachmentRemove.ts","../src/primitives/attachment/AttachmentRemove.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/utils/getThreadMessageText.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/providers/AttachmentRuntimeProvider.tsx","../src/primitives/composer/index.ts","../src/primitives/composer/ComposerRoot.tsx","../src/primitives/composer/ComposerInput.tsx","../src/utils/hooks/useOnScrollToBottom.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/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/utils/ProxyConfigProvider.ts","../src/runtimes/core/BaseAssistantRuntimeCore.tsx","../src/internal.ts","../src/runtimes/composer/BaseComposerRuntimeCore.tsx","../src/runtimes/composer/DefaultThreadComposerRuntimeCore.tsx","../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/ThreadRuntime.ts","../src/api/ThreadManagerRuntime.ts","../src/api/AssistantRuntime.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/LocalRuntimeOptions.tsx","../src/runtimes/local/shouldContinue.tsx","../src/runtimes/composer/DefaultEditComposerRuntimeCore.tsx","../src/runtimes/core/BaseThreadRuntimeCore.tsx","../src/runtimes/local/LocalThreadRuntimeCore.tsx","../src/runtimes/local/LocalThreadManagerRuntimeCore.tsx","../src/runtimes/local/LocalRuntimeCore.tsx","../src/runtimes/external-store/useExternalStoreRuntime.tsx","../src/runtimes/external-store/ExternalStoreThreadManagementAdapter.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/attachment.tsx","../src/ui/base/dialog.tsx","../src/ui/thread-welcome.tsx","../src/ui/user-message.tsx","../src/ui/user-action-bar.tsx","../src/ui/edit-composer.tsx"],"names":["actions","useThreadRuntimeStore","useEffect","useThreadStore","useThreadMessagesStore","useThreadComposerStore","useThread","useAssistantRuntimeStore","useAssistantRuntime","useEditComposer","Primitive","useContentPartStore","COMPLETE_STATUS","useAttachmentRuntime","useEscapeKeydown","getComponent","AttachmentComponent","useMessageStore","useMessageUtilsStore","useEditComposerStore","messages","subscribers","EMPTY_ARRAY","exports"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;ACbA,2EAAmD;ADenD;AACA;AEjBA;AFmBA;AACA;AGtBA;AAQO,SAAS,iBAAA,CACd,OAAA,EACA,YAAA,EACA;AAKA,EAAA,SAAS,cAAA,CAAe,OAAA,EAA8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A;AACA,EAAA;AACD;AASK;AAIJ,EAAA;AACE,IAAA;AACE,MAAA;AAAgB,QAAA;AACR,UAAA;AACoD,QAAA;AACrD,QAAA;AACG,UAAA;AACmD,QAAA;AAE7D,MAAA;AACF,IAAA;AACE,EAAA;AACJ,EAAA;AAEA,EAAA;AACG,IAAA;AAAA,IAAA;AACC,MAAA;AACA,MAAA;AACA,MAAA;AACC,MAAA;AACD,MAAA;AAEC,MAAA;AAEG,wBAAA;AAAA,UAAA;AAAC,UAAA;AAAA,YAAA;AACa,YAAA;AACF,UAAA;AAAA,QAAA;AACZ,wBAAA;AACA,UAAA;AAAC,UAAA;AAAA,YAAA;AACa,YAAA;AACF,UAAA;AAAA,QAAA;AACZ,MAAA;AACF,IAAA;AAEJ,EAAA;AAEH;AAED;AAEM;AACJ,EAAA;AACA,EAAA;AACD;AAED;AAEMA;AACJ,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAEO;AlL23MD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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\nconst useThreadManagerStore = (runtime: AssistantRuntime) => {\n const [store] = useState(() =>\n create(() => runtime.threadManager.getState()),\n );\n\n useEffect(() => {\n const updateState = () =>\n writableStore(store).setState(runtime.threadManager.getState(), true);\n updateState();\n return runtime.threadManager.subscribe(updateState);\n }, [runtime, store]);\n\n return store;\n};\n\nexport const AssistantRuntimeProviderImpl: FC<\n PropsWithChildren<AssistantRuntimeProviderProps>\n> = ({ children, runtime }) => {\n const useAssistantRuntime = useAssistantRuntimeStore(runtime);\n const useToolUIs = useAssistantToolUIsStore();\n const useThreadManager = useThreadManagerStore(runtime);\n const context = useMemo(() => {\n return {\n useToolUIs,\n useAssistantRuntime,\n useAssistantActions: useAssistantRuntime,\n useThreadManager,\n };\n }, [useAssistantRuntime, useToolUIs, useThreadManager]);\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\";\nimport { ThreadManagerState } from \"../../api/ThreadManagerRuntime\";\n\nexport type AssistantContextValue = {\n useToolUIs: UseBoundStore<ReadonlyStore<AssistantToolUIsState>>;\n useAssistantRuntime: UseBoundStore<ReadonlyStore<AssistantRuntime>>;\n useThreadManager: UseBoundStore<ReadonlyStore<ThreadManagerState>>;\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\nexport const { useThreadManager } = createContextStoreHook(\n useAssistantContext,\n \"useThreadManager\",\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\";\nimport { Unsubscribe } from \"../../types\";\n\nexport type AssistantToolUIsState = Readonly<{\n getToolUI: (toolName: string) => ToolCallContentPartComponent | null;\n setToolUI: (\n toolName: string,\n render: ToolCallContentPartComponent,\n ) => Unsubscribe;\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, useEffect, useState } 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 { ModelConfig, 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\nexport function useThreadModelConfig(options?: {\n optional?: false | undefined;\n}): ModelConfig;\nexport function useThreadModelConfig(options?: {\n optional?: boolean | undefined;\n}): ModelConfig | null;\nexport function useThreadModelConfig(options?: {\n optional?: boolean | undefined;\n}): ModelConfig | null {\n const [, rerender] = useState({});\n\n const runtime = useThreadRuntime(options);\n useEffect(() => {\n return runtime?.unstable_on(\"model-config-update\", () => rerender({}));\n }, [runtime]);\n\n if (!runtime) return null;\n return runtime?.getModelConfig();\n}\n","\"use client\";\nimport { create } from \"zustand\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\n\nexport type ThreadViewportState = Readonly<{\n isAtBottom: boolean;\n scrollToBottom: () => void;\n onScrollToBottom: (callback: () => void) => Unsubscribe;\n}>;\n\nexport const makeThreadViewportStore = () => {\n const scrollToBottomListeners = new Set<() => void>();\n\n return create<ThreadViewportState>(() => ({\n isAtBottom: true,\n scrollToBottom: () => {\n for (const listener of scrollToBottomListeners) {\n listener();\n }\n },\n onScrollToBottom: (callback) => {\n scrollToBottomListeners.add(callback);\n return () => {\n scrollToBottomListeners.delete(callback);\n };\n },\n }));\n};\n","import 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 ContentPartRuntimeImpl,\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 ContentPartRuntimeImpl(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() as ContentPartState & {\n type: \"text\";\n };\n\n const textUpdated = (state as TextContentPart).text !== text;\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 type: \"text\",\n text,\n part: { type: \"text\", text },\n status: targetStatus,\n } satisfies ContentPartState,\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\";\nimport { Unsubscribe } from \"../types\";\nimport { ContentPartRuntimePath } from \"./RuntimePathTypes\";\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<\n ContentPartState,\n ContentPartRuntimePath\n>;\n\nexport type ContentPartRuntime = {\n path: ContentPartRuntimePath;\n\n getState(): ContentPartState;\n addToolResult(result: any): void;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport class ContentPartRuntimeImpl implements ContentPartRuntime {\n public get path() {\n return this.contentBinding.path;\n }\n\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 { useThreadRuntime } from \"../context/react/ThreadContext\";\nimport { CreateAppendMessage } from \"../api/ThreadRuntime\";\n\n/**\n * @deprecated Use `useThreadRuntime().append()` instead. This will be removed in 0.6.\n */\nexport const useAppendMessage = () => {\n const threadRuntime = useThreadRuntime();\n\n const append = useCallback(\n (message: CreateAppendMessage) => {\n threadRuntime.append(message);\n },\n [threadRuntime],\n );\n\n return append;\n};\n","import { useCallback } from \"react\";\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 switchToNewThread = useCallback(() => {\n assistantRuntime.switchToNewThread();\n }, [assistantRuntime]);\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\n useEffect(() => {\n return tool.render\n ? toolUIsStore.getState().setToolUI(tool.toolName, tool.render)\n : undefined;\n }, [toolUIsStore, tool.toolName, tool.render]);\n\n useEffect(() => {\n const { toolName, render, ...rest } = tool;\n const config = {\n tools: {\n [toolName]: rest,\n },\n };\n return assistantRuntime.registerModelConfigProvider({\n getModelConfig: () => config,\n });\n }, [assistantRuntime, 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 // TODO remove null option in 0.6\n tool: AssistantToolUIProps<any, any> | null,\n) => {\n const toolUIsStore = useToolUIsStore();\n useEffect(() => {\n if (!tool) return;\n return toolUIsStore.getState().setToolUI(tool.toolName, tool.render);\n }, [toolUIsStore, tool?.toolName, tool?.render]);\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 { FC, useCallback, useEffect, useState } from \"react\";\nimport { ToolCallContentPartProps } from \"../types\";\nimport { create } from \"zustand\";\n\nexport const useInlineRender = <TArgs extends Record<string, unknown>, TResult>(\n toolUI: FC<ToolCallContentPartProps<TArgs, TResult>>,\n): FC<ToolCallContentPartProps<TArgs, TResult>> => {\n const [useToolUI] = useState(() => create(() => toolUI));\n\n useEffect(() => {\n useToolUI.setState(toolUI);\n });\n\n return useCallback((args) => {\n const toolUI = useToolUI();\n return toolUI(args);\n }, []);\n};\n","import { useCallback } from \"react\";\nimport {\n useMessage,\n useMessageRuntime,\n useMessageUtils,\n} from \"../../context/react/MessageContext\";\nimport { useComposerRuntime } from \"../../context\";\n\nexport type UseActionBarCopyProps = {\n copiedDuration?: number | undefined;\n};\n\nexport const useActionBarCopy = ({\n copiedDuration = 3000,\n}: UseActionBarCopyProps = {}) => {\n const messageRuntime = useMessageRuntime();\n const composerRuntime = useComposerRuntime();\n const setIsCopied = useMessageUtils((s) => s.setIsCopied);\n const hasCopyableContent = useMessage((message) => {\n return (\n (message.role !== \"assistant\" || message.status.type !== \"running\") &&\n message.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n });\n\n const callback = useCallback(() => {\n const { isEditing, text: composerValue } = composerRuntime.getState();\n\n const valueToCopy = isEditing\n ? composerValue\n : messageRuntime.unstable_getCopyText();\n\n navigator.clipboard.writeText(valueToCopy).then(() => {\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), copiedDuration);\n });\n }, [messageRuntime, setIsCopied, composerRuntime, copiedDuration]);\n\n if (!hasCopyableContent) return null;\n return callback;\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 { useMessageRuntime } from \"../../context/react/MessageContext\";\nimport { useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\n\nexport const useActionBarReload = () => {\n const messageRuntime = useMessageRuntime();\n const threadRuntime = useThreadRuntime();\n\n const disabled = useCombinedStore(\n [threadRuntime, messageRuntime],\n (t, m) => t.isRunning || t.isDisabled || m.role !== \"assistant\",\n );\n\n const callback = useCallback(() => {\n messageRuntime.reload();\n }, [messageRuntime]);\n\n if (disabled) 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 { useCallback } from \"react\";\n\nimport { useMessage, useMessageRuntime } from \"../../context\";\n\nexport const useActionBarSpeak = () => {\n const messageRunime = useMessageRuntime();\n const callback = useCallback(async () => {\n messageRunime.speak();\n }, [messageRunime]);\n\n const hasSpeakableContent = useMessage((m) => {\n return (\n (m.role !== \"assistant\" || m.status.type !== \"running\") &&\n m.content.some((c) => c.type === \"text\" && c.text.length > 0)\n );\n });\n\n if (!hasSpeakableContent) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport {\n useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\n\nexport const useActionBarStopSpeaking = () => {\n const messageRuntime = useMessageRuntime();\n const isSpeaking = useMessage((u) => u.speech != null);\n\n const callback = useCallback(async () => {\n messageRuntime.stopSpeaking();\n }, [messageRuntime]);\n\n if (!isSpeaking) return null;\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageRuntime } from \"../../context\";\n\nexport const useActionBarFeedbackPositive = () => {\n const messageRuntime = useMessageRuntime();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({ type: \"positive\" });\n }, [messageRuntime]);\n\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useMessageRuntime } from \"../../context\";\n\nexport const useActionBarFeedbackNegative = () => {\n const messageRuntime = useMessageRuntime();\n\n const callback = useCallback(() => {\n messageRuntime.submitFeedback({ type: \"negative\" });\n }, [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 {\n useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerNext = () => {\n const messageRuntime = useMessageRuntime();\n const disabled = useMessage((m) => m.branchNumber >= m.branchCount);\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 useMessage,\n useMessageRuntime,\n} from \"../../context/react/MessageContext\";\n\nexport const useBranchPickerPrevious = () => {\n const messageRuntime = useMessageRuntime();\n const disabled = useMessage((m) => m.branchNumber <= 1);\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, useComposerRuntime } from \"../../context\";\n\nexport const useComposerCancel = () => {\n const composerRuntime = useComposerRuntime();\n const disabled = useComposer((c) => !c.canCancel);\n\n const callback = useCallback(() => {\n composerRuntime.cancel();\n }, [composerRuntime]);\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 { useCombinedStore } from \"../../utils/combined/useCombinedStore\";\nimport { useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { useComposerRuntime } from \"../../context\";\n\nexport const useComposerSend = () => {\n const composerRuntime = useComposerRuntime();\n const threadRuntime = useThreadRuntime();\n\n const disabled = useCombinedStore(\n [threadRuntime, composerRuntime],\n (t, c) => t.isRunning || !c.isEditing || c.isEmpty,\n );\n\n const callback = useCallback(() => {\n if (!composerRuntime.getState().isEditing) return;\n\n composerRuntime.send();\n }, [threadRuntime]);\n\n if (disabled) return null;\n return callback;\n};\n","import { useCallback } from \"react\";\nimport { useComposer, useComposerRuntime } from \"../../context\";\n\nexport const useComposerAddAttachment = () => {\n const disabled = useComposer((c) => !c.isEditing);\n\n const composerRuntime = useComposerRuntime();\n const callback = useCallback(() => {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n\n const attachmentAccept = composerRuntime.getAttachmentAccept();\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 composerRuntime.addAttachment(file);\n };\n\n input.click();\n }, [composerRuntime]);\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 & { part: 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 &\n ImageContentPart & { part: 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 & { part: TextContentPart };\n });\n\n return text;\n};\n","\"use client\";\nimport {\n useMessageRuntime,\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 hasContent: boolean | undefined;\n submittedFeedback: \"positive\" | \"negative\" | null | undefined;\n};\nexport type UseMessageIfProps = RequireAtLeastOne<MessageIfFilters>;\n\nexport const useMessageIf = (props: UseMessageIfProps) => {\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [messageRuntime, messageUtilsStore],\n (\n {\n role,\n attachments,\n content,\n branchCount,\n isLast,\n speech,\n submittedFeedback,\n },\n { isCopied, isHovering },\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 && speech == null) return false;\n if (props.speaking === false && speech != null) 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 (props.hasContent === true && content.length === 0) return false;\n if (props.hasContent === false && content.length > 0) return false;\n\n if (\n props.submittedFeedback !== undefined &&\n (submittedFeedback?.type ?? null) !== 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 { useThreadViewportStore } from \"../../context/react/ThreadContext\";\n\nexport const useThreadScrollToBottom = () => {\n const isAtBottom = useThreadViewport((s) => s.isAtBottom);\n\n const threadViewportStore = useThreadViewportStore();\n\n const handleScrollToBottom = useCallback(() => {\n threadViewportStore.getState().scrollToBottom();\n }, [threadViewportStore]);\n\n if (isAtBottom) return null;\n return handleScrollToBottom;\n};\n","import { useCallback } from \"react\";\nimport { useThread } from \"../../context\";\nimport { useThreadRuntime } 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 threadRuntime = useThreadRuntime();\n\n const disabled = useThread((t) => t.isDisabled);\n const callback = useCallback(() => {\n if (autoSend && !threadRuntime.getState().isRunning) {\n threadRuntime.append(prompt);\n threadRuntime.composer.setText(\"\");\n } else {\n threadRuntime.composer.setText(prompt);\n }\n }, [threadRuntime, autoSend, 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 PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\n/**\n * @deprecated Use `ActionBarPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveRootProps = ActionBarPrimitiveRoot.Props;\n\nexport namespace ActionBarPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = PrimitiveDivProps & UseActionBarFloatStatusProps;\n}\n\nexport const ActionBarPrimitiveRoot = forwardRef<\n ActionBarPrimitiveRoot.Element,\n ActionBarPrimitiveRoot.Props\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 useMessageRuntime,\n useMessageUtilsStore,\n} from \"../../context/react/MessageContext\";\nimport { useThreadRuntime } 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 threadRuntime = useThreadRuntime();\n const messageRuntime = useMessageRuntime();\n const messageUtilsStore = useMessageUtilsStore();\n\n return useCombinedStore(\n [threadRuntime, messageRuntime, 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.branchCount <= 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\n/**\n * @deprecated Use `ActionBarPrimitive.Copy.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveCopyProps = ActionBarPrimitiveCopy.Props;\n\nexport namespace ActionBarPrimitiveCopy {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarCopy>;\n}\n\nexport const ActionBarPrimitiveCopy = forwardRef<\n ActionBarPrimitiveCopy.Element,\n ActionBarPrimitiveCopy.Props\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 PrimitiveButtonProps = ComponentPropsWithoutRef<typeof Primitive.button>;\n\nexport type ActionButtonProps<THook> = PrimitiveButtonProps &\n (THook extends (props: infer TProps) => unknown ? TProps : never);\n\nexport type ActionButtonElement = ElementRef<typeof Primitive.button>;\n\nexport const createActionButton = <TProps,>(\n displayName: string,\n useActionButton: ActionButtonCallback<TProps>,\n forwardProps: (keyof NonNullable<TProps>)[] = [],\n) => {\n const ActionButton = forwardRef<\n ActionButtonElement,\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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.Reload.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveReloadProps = ActionBarPrimitiveReload.Props;\n\nexport namespace ActionBarPrimitiveReload {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.Edit.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveEditProps = ActionBarPrimitiveEdit.Props;\n\nexport namespace ActionBarPrimitiveEdit {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.Speak.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveSpeakProps = ActionBarPrimitiveSpeak.Props;\n\nexport namespace ActionBarPrimitiveSpeak {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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\n/**\n * @deprecated Use `ActionBarPrimitive.StopSpeaking.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveStopSpeakingProps =\n ActionBarPrimitiveStopSpeaking.Props;\n\nexport namespace ActionBarPrimitiveStopSpeaking {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarStopSpeaking>;\n}\n\nexport const ActionBarPrimitiveStopSpeaking = forwardRef<\n ActionBarPrimitiveStopSpeaking.Element,\n ActionBarPrimitiveStopSpeaking.Props\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 { useMessage } from \"../../context\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.FeedbackPositive.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveFeedbackPositiveProps =\n ActionBarPrimitiveFeedbackPositive.Props;\n\nexport namespace ActionBarPrimitiveFeedbackPositive {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarFeedbackPositive>;\n}\n\nexport const ActionBarPrimitiveFeedbackPositive = forwardRef<\n ActionBarPrimitiveFeedbackPositive.Element,\n ActionBarPrimitiveFeedbackPositive.Props\n>(({ onClick, disabled, ...props }, forwardedRef) => {\n const isSubmitted = useMessage(\n (u) => u.submittedFeedback?.type === \"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 { useMessage } from \"../../context\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\n/**\n * @deprecated Use `ActionBarPrimitive.FeedbackNegative.Props` instead. This will be removed in 0.6.\n */\nexport type ActionBarPrimitiveFeedbackNegativeProps =\n ActionBarPrimitiveFeedbackNegative.Props;\n\nexport namespace ActionBarPrimitiveFeedbackNegative {\n export type Element = HTMLButtonElement;\n export type Props = ActionButtonProps<typeof useActionBarFeedbackNegative>;\n}\n\nexport const ActionBarPrimitiveFeedbackNegative = forwardRef<\n ActionBarPrimitiveFeedbackNegative.Element,\n ActionBarPrimitiveFeedbackNegative.Props\n>(({ onClick, disabled, ...props }, forwardedRef) => {\n const isSubmitted = useMessage(\n (u) => u.submittedFeedback?.type === \"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, useEffect, useState } from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport { composeEventHandlers } from \"@radix-ui/primitive\";\nimport { ScopedProps, usePopoverScope } from \"./scope\";\nimport { useThreadRuntime } from \"../../context\";\n\n/**\n * @deprecated Use `AssistantModalPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantModalPrimitiveRootProps =\n AssistantModalPrimitiveRoot.Props;\n\nexport namespace AssistantModalPrimitiveRoot {\n export type Props = PopoverPrimitive.PopoverProps & {\n unstable_openOnRunStart?: boolean | undefined;\n };\n}\n\nconst useAssistantModalOpenState = ({\n defaultOpen = false,\n unstable_openOnRunStart = true,\n}: {\n defaultOpen?: boolean | undefined;\n unstable_openOnRunStart?: boolean | undefined;\n}) => {\n const state = useState(defaultOpen);\n\n const [, setOpen] = state;\n const threadRuntime = useThreadRuntime();\n useEffect(() => {\n if (!unstable_openOnRunStart) return undefined;\n\n return threadRuntime.unstable_on(\"run-start\", () => {\n setOpen(true);\n });\n }, [unstable_openOnRunStart]);\n\n return state;\n};\n\nexport const AssistantModalPrimitiveRoot: FC<\n AssistantModalPrimitiveRoot.Props\n> = ({\n __scopeAssistantModal,\n defaultOpen,\n unstable_openOnRunStart,\n open,\n onOpenChange,\n ...rest\n}: ScopedProps<AssistantModalPrimitiveRoot.Props>) => {\n const scope = usePopoverScope(__scopeAssistantModal);\n\n const [modalOpen, setOpen] = useAssistantModalOpenState({\n defaultOpen,\n unstable_openOnRunStart,\n });\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 * 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\n/**\n * @deprecated Use `AssistantModalPrimitive.Trigger.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantModalPrimitiveTriggerProps =\n AssistantModalPrimitiveTrigger.Props;\n\nexport namespace AssistantModalPrimitiveTrigger {\n export type Element = ElementRef<typeof PopoverPrimitive.Trigger>;\n export type Props = ComponentPropsWithoutRef<typeof PopoverPrimitive.Trigger>;\n}\n\nexport const AssistantModalPrimitiveTrigger = forwardRef<\n AssistantModalPrimitiveTrigger.Element,\n AssistantModalPrimitiveTrigger.Props\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveTrigger.Props>,\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\n/**\n * @deprecated Use `AssistantModalPrimitive.Content.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantModalPrimitiveContentProps =\n AssistantModalPrimitiveContent.Props;\n\nexport namespace AssistantModalPrimitiveContent {\n export type Element = ElementRef<typeof PopoverPrimitive.Content>;\n export type Props = ComponentPropsWithoutRef<\n typeof PopoverPrimitive.Content\n > & {\n dissmissOnInteractOutside?: boolean | undefined;\n };\n}\n\nexport const AssistantModalPrimitiveContent = forwardRef<\n AssistantModalPrimitiveContent.Element,\n AssistantModalPrimitiveContent.Props\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\nexport namespace AssistantModalPrimitiveAnchor {\n export type Element = ElementRef<typeof PopoverPrimitive.Anchor>;\n export type Props = ComponentPropsWithoutRef<typeof PopoverPrimitive.Anchor>;\n}\n\nexport const AssistantModalPrimitiveAnchor = forwardRef<\n AssistantModalPrimitiveAnchor.Element,\n AssistantModalPrimitiveAnchor.Props\n>(\n (\n {\n __scopeAssistantModal,\n ...rest\n }: ScopedProps<AssistantModalPrimitiveAnchor.Props>,\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 { AttachmentPrimitiveRoot as Root } from \"./AttachmentRoot\";\nexport { AttachmentPrimitiveThumb as unstable_Thumb } from \"./AttachmentThumb\";\nexport { AttachmentPrimitiveName as Name } from \"./AttachmentName\";\nexport { AttachmentPrimitiveRemove as Remove } from \"./AttachmentRemove\";\n","import { Primitive } from \"@radix-ui/react-primitive\";\nimport { ComponentPropsWithoutRef, ElementRef, forwardRef } from \"react\";\n\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport namespace AttachmentPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = PrimitiveDivProps;\n}\n\nexport const AttachmentPrimitiveRoot = forwardRef<\n AttachmentPrimitiveRoot.Element,\n AttachmentPrimitiveRoot.Props\n>((props, ref) => {\n return <Primitive.div {...props} ref={ref} />;\n});\n\nAttachmentPrimitiveRoot.displayName = \"AttachmentPrimitive.Root\";\n","\"use client\";\n\nimport { ComponentPropsWithoutRef, forwardRef, type ElementRef } from \"react\";\nimport { useAttachment } from \"../../context/react/AttachmentContext\";\nimport { Primitive } from \"@radix-ui/react-primitive\";\n\ntype PrimitiveDivProps = ComponentPropsWithoutRef<typeof Primitive.div>;\n\nexport namespace AttachmentPrimitiveThumb {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = PrimitiveDivProps;\n}\n\nexport const AttachmentPrimitiveThumb = forwardRef<\n AttachmentPrimitiveThumb.Element,\n AttachmentPrimitiveThumb.Props\n>((props, ref) => {\n const ext = useAttachment((a) => a.name.split(\".\").pop());\n return (\n <Primitive.div {...props} ref={ref}>\n .{ext}\n </Primitive.div>\n );\n});\n\nAttachmentPrimitiveThumb.displayName = \"AttachmentPrimitive.Thumb\";\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 type { FC } from \"react\";\nimport { useAttachment } from \"../../context/react/AttachmentContext\";\n\nexport namespace AttachmentPrimitiveName {\n export type Props = Record<string, never>;\n}\n\nexport const AttachmentPrimitiveName: FC<\n AttachmentPrimitiveName.Props\n> = () => {\n const name = useAttachment((a) => a.name);\n return <>{name}</>;\n};\n\nAttachmentPrimitiveName.displayName = \"AttachmentPrimitive.Name\";\n","import { useCallback } from \"react\";\nimport { useAttachmentRuntime } from \"../../context/react/AttachmentContext\";\n\nexport const useAttachmentRemove = () => {\n const attachmentRuntime = useAttachmentRuntime();\n\n const handleRemoveAttachment = useCallback(() => {\n attachmentRuntime.remove();\n }, [attachmentRuntime]);\n\n return handleRemoveAttachment;\n};\n","\"use client\";\n\nimport { useAttachmentRemove } from \"../../primitive-hooks/attachment/useAttachmentRemove\";\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\nexport namespace AttachmentPrimitiveRemove {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useAttachmentRemove>;\n}\n\nexport const AttachmentPrimitiveRemove = createActionButton(\n \"AttachmentPrimitive.Remove\",\n useAttachmentRemove,\n);\n","export { BranchPickerPrimitiveNext as Next } from \"./BranchPickerNext\";\nexport { BranchPickerPrimitivePrevious as Previous } from \"./BranchPickerPrevious\";\nexport { BranchPickerPrimitiveCount as Count } from \"./BranchPickerCount\";\nexport { BranchPickerPrimitiveNumber as Number } from \"./BranchPickerNumber\";\nexport { BranchPickerPrimitiveRoot as Root } from \"./BranchPickerRoot\";\n","\n\"use client\";\n\nimport { useBranchPickerNext } from \"../../primitive-hooks/branchPicker/useBranchPickerNext\";\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `BranchPickerPrimitive.Next.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveNextProps = BranchPickerPrimitiveNext.Props;\n\nexport namespace BranchPickerPrimitiveNext {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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 ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\n\n/**\n * @deprecated Use `BranchPickerPrimitive.Previous.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitivePreviousProps = BranchPickerPrimitivePrevious.Props;\n\nexport namespace BranchPickerPrimitivePrevious {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useBranchPickerPrevious>;\n}\n\nexport const BranchPickerPrimitivePrevious = createActionButton(\n \"BranchPickerPrimitive.Previous\",\n useBranchPickerPrevious\n);\n","\"use client\";\n\nimport type { FC } from \"react\";\nimport { useBranchPickerCount } from \"../../primitive-hooks/branchPicker/useBranchPickerCount\";\n\n/**\n * @deprecated Use `BranchPickerPrimitive.Count.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveCountProps = BranchPickerPrimitiveCount.Props;\n\nexport namespace BranchPickerPrimitiveCount {\n export type Props = Record<string, never>;\n}\n\nexport const BranchPickerPrimitiveCount: FC<\n BranchPickerPrimitiveCount.Props\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\n/**\n * @deprecated Use `BranchPickerPrimitive.Number.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveNumberProps = BranchPickerPrimitiveNumber.Props;\n\nexport namespace BranchPickerPrimitiveNumber {\n export type Props = Record<string, never>;\n}\n\nexport const BranchPickerPrimitiveNumber: FC<\n BranchPickerPrimitiveNumber.Props\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\n/**\n * @deprecated Use `BranchPickerPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type BranchPickerPrimitiveRootProps = BranchPickerPrimitiveRoot.Props;\n\nexport namespace BranchPickerPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div> & {\n hideWhenSingleBranch?: boolean | undefined;\n };\n}\n\nexport const BranchPickerPrimitiveRoot = forwardRef<\n BranchPickerPrimitiveRoot.Element,\n BranchPickerPrimitiveRoot.Props\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\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\n/**\n * @deprecated Use `MessagePrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveRootProps = MessagePrimitiveRoot.Props;\n\nexport namespace MessagePrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div>;\n}\n\nexport const MessagePrimitiveRoot = forwardRef<\n MessagePrimitiveRoot.Element,\n MessagePrimitiveRoot.Props\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\n/**\n * @deprecated Use `MessagePrimitive.If.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveIfProps = MessagePrimitiveIf.Props;\n\nexport namespace MessagePrimitiveIf {\n export type Props = PropsWithChildren<UseMessageIfProps>;\n}\n\nexport const MessagePrimitiveIf: FC<MessagePrimitiveIf.Props> = ({\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 {\n useContentPart,\n useContentPartRuntime,\n useToolUIs,\n} from \"../../context\";\nimport {\n useMessage,\n useMessageRuntime,\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\n/**\n * @deprecated Use `MessagePrimitive.Content.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveContentProps = MessagePrimitiveContent.Props;\n\nexport namespace MessagePrimitiveContent {\n export type Props = {\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}\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 MessagePrimitiveContent.Props[\"components\"];\n\ntype MessageContentPartComponentProps = {\n components: MessagePrimitiveContent.Props[\"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 contentPartRuntime = useContentPartRuntime();\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 contentPartRuntime.addToolResult(result);\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: MessagePrimitiveContent.Props[\"components\"];\n};\n\nconst MessageContentPartImpl: FC<MessageContentPartProps> = ({\n partIndex,\n components,\n}) => {\n const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.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<MessagePrimitiveContent.Props> = ({\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\n/**\n * @deprecated Use `ContentPartPrimitive.Text.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveTextProps = ContentPartPrimitiveText.Props;\n\nexport namespace ContentPartPrimitiveText {\n export type Element = ElementRef<typeof Primitive.span>;\n export type Props = Omit<\n ComponentPropsWithoutRef<typeof Primitive.span>,\n \"children\" | \"asChild\"\n > & {\n smooth?: boolean;\n component?: ElementType;\n };\n}\n\nexport const ContentPartPrimitiveText = forwardRef<\n ContentPartPrimitiveText.Element,\n ContentPartPrimitiveText.Props\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\n/**\n * @deprecated Use `ContentPartPrimitive.Image.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveImageProps = ContentPartPrimitiveImage.Props;\n\nexport namespace ContentPartPrimitiveImage {\n export type Element = ElementRef<typeof Primitive.img>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.img>;\n}\n\nexport const ContentPartPrimitiveImage = forwardRef<\n ContentPartPrimitiveImage.Element,\n ContentPartPrimitiveImage.Props\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\n/**\n * @deprecated Use `ContentPartPrimitive.Display.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveDisplayProps =\n ContentPartPrimitiveDisplay.Props;\n\nexport namespace ContentPartPrimitiveDisplay {\n export type Props = Record<string, never>;\n}\n\nexport const ContentPartPrimitiveDisplay: FC<\n ContentPartPrimitiveDisplay.Props\n> = () => {\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\n/**\n * @deprecated Use `ContentPartPrimitive.InProgress.Props` instead. This will be removed in 0.6.\n */\nexport type ContentPartPrimitiveInProgressProps =\n ContentPartPrimitiveInProgress.Props;\n\nexport namespace ContentPartPrimitiveInProgress {\n export type Props = PropsWithChildren;\n}\n\n// TODO should this be renamed to IsRunning?\nexport const ContentPartPrimitiveInProgress: FC<\n ContentPartPrimitiveInProgress.Props\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 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 { SubscribableWithState } from \"./subscribable/Subscribable\";\n\nimport { ComposerRuntimeCoreBinding } from \"./ComposerRuntime\";\nimport {\n Attachment,\n CompleteAttachment,\n PendingAttachment,\n Unsubscribe,\n} from \"../types\";\nimport { AttachmentRuntimePath } from \"./RuntimePathTypes\";\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<\n AttachmentState & { source: Source },\n AttachmentRuntimePath & { attachmentSource: Source }\n >;\n\ntype AttachmentRuntimeSource = AttachmentState[\"source\"];\n\nexport type AttachmentRuntime<\n TSource extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> = {\n path: AttachmentRuntimePath & { attachmentSource: TSource };\n readonly source: TSource;\n getState(): AttachmentState & { source: TSource };\n remove(): Promise<void>;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport abstract class AttachmentRuntimeImpl<\n Source extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> implements AttachmentRuntime\n{\n public get path() {\n return this._core.path;\n }\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 AttachmentRuntimeImpl<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 ThreadComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"thread-composer\"> {\n public get source(): \"thread-composer\" {\n return \"thread-composer\";\n }\n}\n\nexport class EditComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"edit-composer\"> {\n public get source(): \"edit-composer\" {\n return \"edit-composer\";\n }\n}\n\nexport class MessageAttachmentRuntimeImpl extends AttachmentRuntimeImpl<\"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<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n constructor(\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>,\n ) {\n super();\n }\n\n private _previousStateDirty = true;\n private _previousState: TState | 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<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n constructor(\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>,\n ) {\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: TState;\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 EditComposerAttachmentRuntimeImpl,\n ThreadComposerAttachmentRuntimeImpl,\n} from \"./AttachmentRuntime\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport { SKIP_UPDATE } from \"./subscribable/SKIP_UPDATE\";\nimport { ComposerRuntimePath } from \"./RuntimePathTypes\";\n\nexport type ThreadComposerRuntimeCoreBinding = SubscribableWithState<\n ThreadComposerRuntimeCore | undefined,\n ComposerRuntimePath & { composerSource: \"thread\" }\n>;\n\nexport type EditComposerRuntimeCoreBinding = SubscribableWithState<\n ComposerRuntimeCore | undefined,\n ComposerRuntimePath & { composerSource: \"edit\" }\n>;\n\nexport type ComposerRuntimeCoreBinding = SubscribableWithState<\n ComposerRuntimeCore | undefined,\n ComposerRuntimePath\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 attachments: readonly Attachment[];\n\n /** @deprecated Use `useComposerRuntime().addAttachment` instead. This will be removed in 0.6.0. */\n addAttachment: (file: File) => Promise<void>;\n /** @deprecated Use `useComposerRuntime().removeAttachment` instead. This will be removed in 0.6.0. */\n removeAttachment: (attachmentId: string) => Promise<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\ntype BaseComposerState = {\n text: 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): 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\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 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\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 type ComposerRuntime = {\n path: ComposerRuntimePath;\n readonly type: \"edit\" | \"thread\";\n getState(): ComposerState;\n\n /** @deprecated Use `getState().isEditing` instead. This will be removed in 0.6.0. */\n readonly isEditing: boolean;\n\n /** @deprecated Use `getState().isEmpty` instead. This will be removed in 0.6.0. */\n readonly isEmpty: boolean;\n\n /** @deprecated Use `getState().canCancel` instead. This will be removed in 0.6.0. */\n readonly canCancel: boolean;\n\n /** @deprecated Use `getState().text` instead. This will be removed in 0.6.0. */\n readonly text: string;\n\n /** @deprecated Use `getState().attachments` instead. This will be removed in 0.6.0. */\n readonly attachments: readonly Attachment[];\n\n /** @deprecated Use `getState().text` instead. This will be removed in 0.6.0. */\n readonly value: string;\n\n setText(text: string): void;\n setValue(text: string): void;\n\n getAttachmentAccept(): string;\n addAttachment(file: File): Promise<void>;\n\n /** @deprecated Use `getAttachmentById(id).removeAttachment()` instead. This will be removed in 0.6.0. */\n removeAttachment(attachmentId: string): Promise<void>;\n\n /** @deprecated This method will be removed in 0.6.0. Submit feedback if you need this functionality. */\n reset(): void;\n\n send(): void;\n cancel(): void;\n subscribe(callback: () => void): Unsubscribe;\n getAttachmentByIndex(idx: number): AttachmentRuntime;\n};\n\nexport abstract class ComposerRuntimeImpl\n implements ComposerRuntimeCore, ComposerRuntime\n{\n public get path() {\n return this._core.path;\n }\n\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().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 getAttachmentAccept(): string {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.getAttachmentAccept();\n }\n\n public abstract getAttachmentByIndex(idx: number): AttachmentRuntime;\n}\n\nexport type ThreadComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"thread\" };\n readonly type: \"thread\";\n getState(): ThreadComposerState;\n\n /**\n * @deprecated Use `getState().attachments` instead. This will be removed in 0.6.0.\n */\n attachments: readonly PendingAttachment[];\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"thread-composer\" };\n};\n\nexport class ThreadComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements ThreadComposerRuntime, ThreadComposerState\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & {\n composerSource: \"thread\";\n };\n }\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 path: core.path,\n getState: () => getThreadComposerState(core.getState()),\n subscribe: (callback) => core.subscribe(callback),\n });\n super({\n path: core.path,\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 public getAttachmentByIndex(idx: number) {\n return new ThreadComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"thread-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: this.path.ref + `${this.path.ref}.attachments[${idx}]`,\n },\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 type EditComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"edit\" };\n readonly type: \"edit\";\n\n getState(): EditComposerState;\n beginEdit(): void;\n\n /**\n * @deprecated Use `beginEdit()` instead. This will be removed in 0.6.0.\n */\n edit(): void;\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"edit-composer\" };\n};\n\nexport class EditComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements EditComposerRuntime, EditComposerState\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & { composerSource: \"edit\" };\n }\n\n public get type() {\n return \"edit\" as const;\n }\n\n private _getState;\n constructor(\n core: EditComposerRuntimeCoreBinding,\n private _beginEdit: () => void,\n ) {\n const stateBinding = new LazyMemoizeSubject({\n path: core.path,\n getState: () => getEditComposerState(core.getState(), this._beginEdit),\n subscribe: (callback) => core.subscribe(callback),\n });\n\n super({\n path: core.path,\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 getAttachmentByIndex(idx: number) {\n return new EditComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"edit-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: this.path.ref + `${this.path.ref}.attachments[${idx}]`,\n },\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, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>, NestedSubscribable<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n constructor(private binding: NestedSubscribable<TState, TPath>) {\n super();\n }\n\n public getState() {\n return this.binding.getState();\n }\n\n public outerSubscribe(callback: () => void) {\n return this.binding.subscribe(callback);\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.outerSubscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n","import {\n SpeechState,\n SubmittedFeedback,\n} from \"../runtimes/core/ThreadRuntimeCore\";\nimport {\n ThreadMessage,\n ThreadAssistantContentPart,\n ThreadUserContentPart,\n Unsubscribe,\n} from \"../types\";\nimport {\n ContentPartStatus,\n ToolCallContentPartStatus,\n} from \"../types/AssistantTypes\";\nimport { getThreadMessageText } from \"../utils/getThreadMessageText\";\nimport {\n AttachmentRuntime,\n AttachmentState,\n MessageAttachmentRuntimeImpl,\n} from \"./AttachmentRuntime\";\nimport {\n EditComposerRuntime,\n EditComposerRuntimeImpl,\n} from \"./ComposerRuntime\";\nimport {\n ContentPartRuntime,\n ContentPartRuntimeImpl,\n ContentPartState,\n} from \"./ContentPartRuntime\";\nimport { MessageRuntimePath } from \"./RuntimePathTypes\";\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 /**\n * @deprecated This API is still under active development and might change without notice.\n */\n speech: SpeechState | undefined;\n submittedFeedback: SubmittedFeedback | undefined;\n};\n\nexport type MessageStateBinding = SubscribableWithState<\n MessageState,\n MessageRuntimePath\n>;\n\nexport type MessageRuntime = {\n readonly path: MessageRuntimePath;\n\n readonly composer: EditComposerRuntime;\n\n getState(): MessageState;\n reload(): void;\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n speak(): void;\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n submitFeedback({ type }: { type: \"positive\" | \"negative\" }): void;\n switchToBranch({\n position,\n branchId,\n }: {\n position?: \"previous\" | \"next\" | undefined;\n branchId?: string | undefined;\n }): void;\n unstable_getCopyText(): string;\n\n subscribe(callback: () => void): Unsubscribe;\n\n getContentPartByIndex(idx: number): ContentPartRuntime;\n getContentPartByToolCallId(toolCallId: string): ContentPartRuntime;\n\n getAttachmentByIndex(idx: number): AttachmentRuntime & { source: \"message\" };\n};\n\nexport class MessageRuntimeImpl implements MessageRuntime {\n public get path() {\n return this._core.path;\n }\n\n constructor(\n private _core: MessageStateBinding,\n private _threadBinding: ThreadRuntimeCoreBinding,\n ) {\n this.composer = new EditComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.composer`,\n composerSource: \"edit\",\n },\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\n public composer;\n\n public getState() {\n return this._core.getState();\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 stopSpeaking() {\n const state = this._core.getState();\n if (!state) throw new Error(\"Message is not available\");\n\n const thread = this._threadBinding.getState();\n if (thread.speech?.messageId === state.id) {\n this._threadBinding.getState().stopSpeaking();\n } else {\n throw new Error(\"Message is not being spoken\");\n }\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 unstable_getCopyText() {\n return getThreadMessageText(this.getState());\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n public getContentPartByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Content part index must be >= 0\");\n return new ContentPartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.content[${idx}]`,\n contentPartSelector: { type: \"index\", index: idx },\n },\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 getContentPartByToolCallId(toolCallId: string) {\n return new ContentPartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref:\n this.path.ref +\n `${this.path.ref}.content[toolCallId=${JSON.stringify(toolCallId)}]`,\n contentPartSelector: { type: \"toolCallId\", toolCallId },\n },\n getState: () => {\n const state = this._core.getState();\n const idx = state.content.findIndex(\n (part) =>\n part.type === \"tool-call\" && part.toolCallId === toolCallId,\n );\n if (idx === -1) return SKIP_UPDATE;\n return getContentPartState(state, idx);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n this._threadBinding,\n );\n }\n\n public getAttachmentByIndex(idx: number) {\n return new MessageAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.attachments[${idx}]`,\n attachmentSource: \"message\",\n attachmentSelector: { type: \"index\", index: idx },\n },\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\n/**\n * @deprecated Define a custom Text renderer via ContentPartPrimitiveInProgress instead. This will be removed in 0.6.\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\n/**\n * @deprecated Use `MessagePrimitive.Attachments.Props` instead. This will be removed in 0.6.\n */\nexport type MessagePrimitiveAttachmentsProps =\n MessagePrimitiveAttachments.Props;\n\nexport namespace MessagePrimitiveAttachments {\n export type Props = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n };\n}\n\nconst getComponent = (\n components: MessagePrimitiveAttachments.Props[\"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: MessagePrimitiveAttachments.Props[\"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 MessagePrimitiveAttachments.Props & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n const messageRuntime = useMessageRuntime();\n const runtime = useMemo(\n () => messageRuntime.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 MessagePrimitiveAttachments.Props\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 {\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\nexport type ComposerPrimitiveRootProps = ComposerPrimitiveRoot.Props;\n\nexport namespace ComposerPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.form>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.form>;\n}\n\nexport const ComposerPrimitiveRoot = forwardRef<\n ComposerPrimitiveRoot.Element,\n ComposerPrimitiveRoot.Props\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 useComposerRuntime,\n} from \"../../context/react/ComposerContext\";\nimport { useThread, useThreadRuntime } from \"../../context/react/ThreadContext\";\nimport { useEscapeKeydown } from \"@radix-ui/react-use-escape-keydown\";\nimport { useOnScrollToBottom } from \"../../utils/hooks/useOnScrollToBottom\";\n\n/**\n * @deprecated Use `ComposerPrimitive.Input.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveInputProps = ComposerPrimitiveInput.Props;\n\nexport namespace ComposerPrimitiveInput {\n export type Element = HTMLTextAreaElement;\n export type Props = TextareaAutosizeProps & {\n asChild?: boolean | undefined;\n submitOnEnter?: boolean | undefined;\n cancelOnEscape?: boolean | undefined;\n unstable_focusOnRunStart?: boolean | undefined;\n unstable_focusOnScrollToBottom?: boolean | undefined;\n unstable_focusOnThreadSwitched?: boolean | undefined;\n };\n}\n\nexport const ComposerPrimitiveInput = forwardRef<\n ComposerPrimitiveInput.Element,\n ComposerPrimitiveInput.Props\n>(\n (\n {\n autoFocus = false,\n asChild,\n disabled: disabledProp,\n onChange,\n onKeyDown,\n submitOnEnter = true,\n cancelOnEscape = true,\n unstable_focusOnRunStart = true,\n unstable_focusOnScrollToBottom = true,\n unstable_focusOnThreadSwitched = true,\n ...rest\n },\n forwardedRef,\n ) => {\n const threadRuntime = useThreadRuntime();\n const composerRuntime = useComposerRuntime();\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 if (composerRuntime.getState().canCancel) {\n composerRuntime.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 } = threadRuntime.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 useOnScrollToBottom(() => {\n if (composerRuntime.type === \"thread\" && unstable_focusOnScrollToBottom) {\n focus();\n }\n });\n\n useEffect(() => {\n if (composerRuntime.type !== \"thread\" || !unstable_focusOnRunStart)\n return undefined;\n\n return threadRuntime.unstable_on(\"run-start\", focus);\n }, [unstable_focusOnRunStart]);\n\n useEffect(() => {\n if (composerRuntime.type !== \"thread\" || !unstable_focusOnThreadSwitched)\n return undefined;\n\n return threadRuntime.unstable_on(\"switched-to\", focus);\n }, [unstable_focusOnThreadSwitched]);\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 if (!composerRuntime.getState().isEditing) return;\n return composerRuntime.setText(e.target.value);\n })}\n onKeyDown={composeEventHandlers(onKeyDown, handleKeyPress)}\n />\n );\n },\n);\n\nComposerPrimitiveInput.displayName = \"ComposerPrimitive.Input\";\n","import { useCallbackRef } from \"@radix-ui/react-use-callback-ref\";\nimport { useEffect } from \"react\";\nimport { useThreadViewport } from \"../../context/react/ThreadContext\";\n\nexport const useOnScrollToBottom = (callback: () => void) => {\n const callbackRef = useCallbackRef(callback);\n const onScrollToBottom = useThreadViewport((vp) => vp.onScrollToBottom);\n\n useEffect(() => {\n return onScrollToBottom(callbackRef);\n }, [onScrollToBottom, callbackRef]);\n};\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerSend } from \"../../primitive-hooks\";\n\n/**\n * @deprecated Use `ComposerPrimitive.Send.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveSendProps = ComposerPrimitiveSend.Props;\n\nexport namespace ComposerPrimitiveSend {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useComposerSend>;\n}\n\nexport const ComposerPrimitiveSend = createActionButton(\n \"ComposerPrimitive.Send\",\n useComposerSend\n);\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerCancel } from \"../../primitive-hooks/composer/useComposerCancel\";\n\n/**\n * @deprecated Use `ComposerPrimitive.Cancel.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveCancelProps = ComposerPrimitiveCancel.Props;\n\nexport namespace ComposerPrimitiveCancel {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useComposerCancel>;\n}\n\nexport const ComposerPrimitiveCancel = createActionButton(\n \"ComposerPrimitive.Cancel\",\n useComposerCancel,\n);\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useComposerAddAttachment } from \"../../primitive-hooks/composer\";\n\n/**\n * @deprecated Use `ComposerPrimitive.AddAttachment.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveAddAttachmentProps = ComposerPrimitiveAddAttachment.Props;\n\nexport namespace ComposerPrimitiveAddAttachment {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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\n/**\n * @deprecated Use `ComposerPrimitive.Attachments.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveAttachmentsProps =\n ComposerPrimitiveAttachments.Props;\n\nexport namespace ComposerPrimitiveAttachments {\n export type Props = {\n components:\n | {\n Image?: ComponentType | undefined;\n Document?: ComponentType | undefined;\n File?: ComponentType | undefined;\n Attachment?: ComponentType | undefined;\n }\n | undefined;\n };\n}\n\nconst getComponent = (\n components: ComposerPrimitiveAttachments.Props[\"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: ComposerPrimitiveAttachments.Props[\"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 ComposerPrimitiveAttachments.Props & { attachmentIndex: number }\n> = ({ components, attachmentIndex }) => {\n const composerRuntime = useComposerRuntime();\n const runtime = useMemo(\n () => composerRuntime.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 ComposerPrimitiveAttachments.Props\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\n/**\n * @deprecated Use `ComposerPrimitive.If.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerPrimitiveIfProps = ComposerPrimitiveIf.Props;\n\nexport namespace ComposerPrimitiveIf {\n export type Props = PropsWithChildren<UseComposerIfProps>;\n}\n\nexport const ComposerPrimitiveIf: FC<ComposerPrimitiveIf.Props> = ({\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\n/**\n * @deprecated Use `ThreadPrimitive.Root.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveRootProps = ThreadPrimitiveRoot.Props;\n\nexport namespace ThreadPrimitiveRoot {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div>;\n}\n\nexport const ThreadPrimitiveRoot = forwardRef<\n ThreadPrimitiveRoot.Element,\n ThreadPrimitiveRoot.Props\n>((props, ref) => {\n return <Primitive.div {...props} ref={ref} />;\n});\n\nThreadPrimitiveRoot.displayName = \"ThreadPrimitive.Root\";\n","\"use client\";\n\nimport type { FC, PropsWithChildren } from \"react\";\nimport { useThreadEmpty } from \"../../primitive-hooks\";\n\n/**\n * @deprecated Use `ThreadPrimitive.Empty.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveEmptyProps = ThreadPrimitiveEmpty.Props;\n\nexport namespace ThreadPrimitiveEmpty {\n export type Props = PropsWithChildren;\n}\n\nexport const ThreadPrimitiveEmpty: FC<ThreadPrimitiveEmpty.Props> = ({\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\n/**\n * @deprecated Use `ThreadPrimitive.If.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveIfProps = ThreadPrimitiveIf.Props;\n\nexport namespace ThreadPrimitiveIf {\n export type Props = PropsWithChildren<UseThreadIfProps>;\n}\n\nexport const ThreadPrimitiveIf: FC<ThreadPrimitiveIf.Props> = ({\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\n/**\n * @deprecated Use `ThreadPrimitive.Viewport.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveViewportProps = ThreadPrimitiveViewport.Props;\n\nexport namespace ThreadPrimitiveViewport {\n export type Element = ElementRef<typeof Primitive.div>;\n export type Props = ComponentPropsWithoutRef<typeof Primitive.div> &\n UseThreadViewportAutoScrollProps;\n}\n\nexport const ThreadPrimitiveViewport = forwardRef<\n ThreadPrimitiveViewport.Element,\n ThreadPrimitiveViewport.Props\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 { useEffect, useRef } from \"react\";\nimport {\n useThreadRuntime,\n useThreadViewportStore,\n} 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 unstable_scrollToBottomOnRunStart?: boolean | undefined;\n};\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll = true,\n unstable_scrollToBottomOnRunStart = 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 // autoscroll on run start\n const threadRuntime = useThreadRuntime();\n useEffect(() => {\n if (!unstable_scrollToBottomOnRunStart) return undefined;\n\n return threadRuntime.unstable_on(\"run-start\", focus);\n }, [unstable_scrollToBottomOnRunStart]);\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","\"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\n/**\n * @deprecated Use `ThreadPrimitive.Messages.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveMessagesProps = ThreadPrimitiveMessages.Props;\n\nexport namespace ThreadPrimitiveMessages {\n export type Props = {\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}\n\nconst isComponentsSame = (\n prev: ThreadPrimitiveMessages.Props[\"components\"],\n next: ThreadPrimitiveMessages.Props[\"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: ThreadPrimitiveMessages.Props[\"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: ThreadPrimitiveMessages.Props[\"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: ThreadPrimitiveMessages.Props[\"components\"];\n};\n\nconst ThreadMessageImpl: FC<ThreadMessageProps> = ({\n messageIndex,\n components,\n}) => {\n const threadRuntime = useThreadRuntime();\n const runtime = useMemo(\n () => threadRuntime.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<ThreadPrimitiveMessages.Props> = ({\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\";\n\nexport type MessageUtilsState = Readonly<{\n isCopied: boolean;\n setIsCopied: (value: boolean) => void;\n\n isHovering: boolean;\n setIsHovering: (value: boolean) => void;\n}>;\n\nexport const makeMessageUtilsStore = () =>\n create<MessageUtilsState>((set) => {\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 };\n });\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadScrollToBottom } from \"../../primitive-hooks/thread/useThreadScrollToBottom\";\n\n/**\n * @deprecated Use `ThreadPrimitive.ScrollToBottom.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveScrollToBottomProps =\n ThreadPrimitiveScrollToBottom.Props;\n\nexport namespace ThreadPrimitiveScrollToBottom {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<typeof useThreadScrollToBottom>;\n}\n\nexport const ThreadPrimitiveScrollToBottom = createActionButton(\n \"ThreadPrimitive.ScrollToBottom\",\n useThreadScrollToBottom,\n);\n","\"use client\";\n\nimport {\n ActionButtonElement,\n ActionButtonProps,\n createActionButton,\n} from \"../../utils/createActionButton\";\nimport { useThreadSuggestion } from \"../../primitive-hooks/thread/useThreadSuggestion\";\n\n/**\n * @deprecated Use `ThreadPrimitive.Suggestion.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadPrimitiveSuggestionProps = ThreadPrimitiveSuggestion.Props;\n\nexport namespace ThreadPrimitiveSuggestion {\n export type Element = ActionButtonElement;\n export type Props = ActionButtonProps<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.threadManager.mainThread.subscribe(callback);\n\n if (!first) {\n callback();\n }\n first = false;\n };\n\n const unsubscribe = runtime.threadManager.mainThread.subscribe(inner);\n inner();\n\n return () => {\n unsubscribe();\n cleanup?.();\n };\n};\n","\"use client\";\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { ChatModelAdapter } from \"./ChatModelAdapter\";\nimport { LocalRuntimeCore } from \"./LocalRuntimeCore\";\nimport { LocalRuntimeOptions } from \"./LocalRuntimeOptions\";\nimport {\n AssistantRuntime,\n AssistantRuntimeImpl,\n} from \"../../api/AssistantRuntime\";\nimport { ThreadRuntimeImpl } from \"../../internal\";\nimport { ThreadRuntime } from \"../../api\";\n\nexport type LocalRuntime = AssistantRuntime & {\n reset: (options?: Parameters<LocalRuntimeCore[\"reset\"]>[0]) => void;\n};\n\nclass LocalRuntimeImpl extends AssistantRuntimeImpl implements LocalRuntime {\n private constructor(\n private core: LocalRuntimeCore,\n thread: ThreadRuntime,\n ) {\n super(core, thread);\n }\n\n public reset(options?: Parameters<LocalRuntimeCore[\"reset\"]>[0]) {\n this.core.reset(options);\n }\n\n public static override create(_core: LocalRuntimeCore) {\n return new LocalRuntimeImpl(\n _core,\n AssistantRuntimeImpl.createMainThreadRuntime(_core, ThreadRuntimeImpl),\n ) as LocalRuntime;\n }\n}\n\nexport const useLocalRuntime = (\n adapter: ChatModelAdapter,\n options: LocalRuntimeOptions = {},\n) => {\n const opt = {\n ...options,\n adapters: {\n ...options.adapters,\n chatModel: adapter,\n },\n };\n\n const [runtime] = useState(() => new LocalRuntimeCore(opt));\n\n useEffect(() => {\n runtime.setOptions(opt);\n });\n\n return useMemo(() => LocalRuntimeImpl.create(runtime), [runtime]);\n};\n","import {\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 const unsubscribe = provider.subscribe?.(() => {\n this.notifySubscribers();\n });\n this.notifySubscribers();\n return () => {\n this._providers.delete(provider);\n unsubscribe?.();\n this.notifySubscribers();\n };\n }\n\n private _subscribers = new Set<() => void>();\n\n notifySubscribers() {\n for (const callback of this._subscribers) callback();\n }\n\n subscribe(callback: () => void) {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n}\n","import { type ModelConfigProvider } from \"../../types/ModelConfigTypes\";\nimport type { Unsubscribe } from \"../../types/Unsubscribe\";\nimport type { AssistantRuntimeCore } from \"./AssistantRuntimeCore\";\nimport { ProxyConfigProvider } from \"../../utils/ProxyConfigProvider\";\nimport { ThreadManagerRuntimeCore } from \"./ThreadManagerRuntimeCore\";\n\nexport abstract class BaseAssistantRuntimeCore implements AssistantRuntimeCore {\n protected readonly _proxyConfigProvider = new ProxyConfigProvider();\n public abstract get threadManager(): ThreadManagerRuntimeCore;\n\n constructor() {}\n\n public registerModelConfigProvider(\n provider: ModelConfigProvider,\n ): Unsubscribe {\n return this._proxyConfigProvider.registerModelConfigProvider(provider);\n }\n}\n","export type { ThreadRuntimeCore } from \"./runtimes/core/ThreadRuntimeCore\";\nexport type { ThreadManagerRuntimeCore } from \"./runtimes/core/ThreadManagerRuntimeCore\";\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 { AssistantRuntimeImpl } from \"./api/AssistantRuntime\";\nexport {\n ThreadRuntimeImpl,\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 protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n\n public getAttachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\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 adapter = this.getAttachmentAdapter();\n const attachments =\n adapter && this.attachments.length > 0\n ? await Promise.all(\n this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n const result = await adapter.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 async addAttachment(file: File) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n\n const attachment = await adapter.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 const adapter = this.getAttachmentAdapter();\n if (!adapter) 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 adapter.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 { AttachmentAdapter } from \"../attachment\";\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 protected getAttachmentAdapter() {\n return this.runtime.adapters?.attachments;\n }\n\n constructor(\n private runtime: Omit<ThreadRuntimeCore, \"composer\"> & {\n adapters?: { attachments?: AttachmentAdapter | undefined } | undefined;\n },\n ) {\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","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 {\n AddToolResultOptions,\n ThreadSuggestion,\n RuntimeCapabilities,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n SpeechState,\n SubmittedFeedback,\n ThreadRuntimeEventType,\n} from \"../runtimes/core/ThreadRuntimeCore\";\nimport { ExportedMessageRepository } from \"../runtimes/utils/MessageRepository\";\nimport {\n AppendMessage,\n ModelConfig,\n ThreadMessage,\n Unsubscribe,\n} from \"../types\";\nimport {\n MessageRuntime,\n MessageRuntimeImpl,\n MessageState,\n} from \"./MessageRuntime\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ShallowMemoizeSubject } from \"./subscribable/ShallowMemoizeSubject\";\nimport {\n Subscribable,\n SubscribableWithState,\n} from \"./subscribable/Subscribable\";\nimport {\n ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./ComposerRuntime\";\nimport { LazyMemoizeSubject } from \"./subscribable/LazyMemoizeSubject\";\nimport { SKIP_UPDATE } from \"./subscribable/SKIP_UPDATE\";\nimport { ComposerRuntimeCore } from \"../runtimes/core/ComposerRuntimeCore\";\nimport { MessageRuntimePath, ThreadRuntimePath } from \"./RuntimePathTypes\";\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<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadState = Readonly<{\n threadId: string;\n isDisabled: boolean;\n isRunning: boolean;\n capabilities: RuntimeCapabilities;\n messages: readonly ThreadMessage[];\n suggestions: readonly ThreadSuggestion[];\n extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n speech: SpeechState | 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 suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n });\n};\n\nexport type ThreadRuntime = Readonly<{\n readonly path: ThreadRuntimePath;\n\n readonly composer: ThreadComposerRuntime;\n getState(): ThreadState;\n\n /**\n * @deprecated This method will be removed in 0.6.0. Submit feedback if you need this functionality.\n */\n unstable_getCore(): ThreadRuntimeCore;\n\n append(message: CreateAppendMessage): void;\n startRun(parentId: string | null): void;\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n getModelConfig(): ModelConfig;\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n getMesssageByIndex(idx: number): MessageRuntime;\n getMesssageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking: () => void;\n\n unstable_on(event: ThreadRuntimeEventType, callback: () => void): Unsubscribe;\n\n // Legacy methods with deprecations\n\n /**\n * @deprecated Use `getState().capabilities` instead. This will be removed in 0.6.0.\n */\n capabilities: Readonly<RuntimeCapabilities>;\n\n /**\n * @deprecated Use `getState().threadId` instead. This will be removed in 0.6.0.\n */\n threadId: string;\n\n /**\n * @deprecated Use `getState().isDisabled` instead. This will be removed in 0.6.0.\n */\n isDisabled: boolean;\n\n /**\n * @deprecated Use `getState().isRunning` instead. This will be removed in 0.6.0.\n */\n isRunning: boolean;\n\n /**\n * @deprecated Use `getState().messages` instead. This will be removed in 0.6.0.\n */\n messages: readonly ThreadMessage[];\n\n /**\n * @deprecated Use `getState().followupSuggestions` instead. This will be removed in 0.6.0.\n */\n suggestions: readonly ThreadSuggestion[];\n\n /**\n * @deprecated Use `getState().speechState` instead. This will be removed in 0.6.0.\n */\n speech: SpeechState | undefined;\n\n /**\n * @deprecated Use `getState().extras` instead. This will be removed in 0.6.0.\n */\n extras: unknown;\n\n /**\n * @deprecated Use `getMesssageById(id).getState().branchNumber` / `getMesssageById(id).getState().branchCount` instead. This will be removed in 0.6.0.\n */\n getBranches: (messageId: string) => readonly string[];\n\n /**\n * @deprecated Use `getMesssageById(id).switchToBranch({ options })` instead. This will be removed in 0.6.0.\n */\n switchToBranch: (branchId: string) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).getContentPartByToolCallId(toolCallId).addToolResult({ result })` instead. This will be removed in 0.6.0.\n */\n addToolResult: (options: AddToolResultOptions) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).speak()` instead. This will be removed in 0.6.0.\n */\n speak: (messageId: string) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).getState().submittedFeedback` instead. This will be removed in 0.6.0.\n */\n getSubmittedFeedback: (messageId: string) => SubmittedFeedback | undefined;\n\n /**\n * @deprecated Use `getMesssageById(id).submitFeedback({ type })` instead. This will be removed in 0.6.0.\n */\n submitFeedback: (feedback: SubmitFeedbackOptions) => void;\n\n /**\n * @deprecated Use `getMesssageById(id).composer` instead. This will be removed in 0.6.0.\n */\n getEditComposer: (messageId: string) => ComposerRuntimeCore | undefined;\n\n /**\n * @deprecated Use `getMesssageById(id).composer.beginEdit()` instead. This will be removed in 0.6.0.\n */\n beginEdit: (messageId: string) => void;\n}>;\n\nexport class ThreadRuntimeImpl\n implements Omit<ThreadRuntimeCore, \"getMessageById\">, ThreadRuntime\n{\n public get path() {\n return this._threadBinding.path;\n }\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().extras` instead. This will be removed in 0.6.0.\n */\n public get extras() {\n return this._threadBinding.getState().extras;\n }\n\n /**\n * @deprecated Use `getState().followupSuggestions` instead. This will be removed in 0.6.0.\n */\n public get suggestions() {\n return this._threadBinding.getState().suggestions;\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 /**\n * @deprecated Use `getState().speechState` instead. This will be removed in 0.6.0.\n */\n public get speech() {\n return this._threadBinding.getState().speech;\n }\n\n public unstable_getCore() {\n return this._threadBinding.getState();\n }\n\n private _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n\n constructor(threadBinding: ThreadRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n path: threadBinding.path,\n getState: () => getThreadState(threadBinding.getState()),\n subscribe: (callback) => threadBinding.subscribe(callback),\n });\n\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n }\n\n public readonly composer;\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 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 /**\n * @deprecated Use `getMesssageById(id).switchToBranch({ options })` instead. This will be removed in 0.6.0.\n */\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 public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public getSubmittedFeedback(messageId: string) {\n return this._threadBinding.getState().getSubmittedFeedback(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).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).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 getMesssageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: this.path.ref + `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n };\n },\n );\n }\n\n public getMesssageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref:\n this.path.ref +\n `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined) return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n const submittedFeedback = thread.getSubmittedFeedback(message.id);\n\n return {\n ...message,\n\n message,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branches,\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n\n submittedFeedback,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventListenerNestedSubscriptions = new Map<\n string,\n NestedSubscriptionSubject<Subscribable, ThreadRuntimePath>\n >();\n\n public unstable_on(\n event: ThreadRuntimeEventType,\n callback: () => void,\n ): Unsubscribe {\n let subject = this._eventListenerNestedSubscriptions.get(event);\n if (!subject) {\n subject = new NestedSubscriptionSubject({\n path: this.path,\n getState: () => ({\n subscribe: (callback) =>\n this._threadBinding.getState().unstable_on(event, callback),\n }),\n subscribe: (callback) => this._threadBinding.outerSubscribe(callback),\n });\n this._eventListenerNestedSubscriptions.set(event, subject);\n }\n return subject.subscribe(callback);\n }\n}\n","import { LazyMemoizeSubject } from \"./subscribable/LazyMemoizeSubject\";\nimport {\n ThreadManagerMetadata,\n ThreadManagerRuntimeCore,\n} from \"../runtimes/core/ThreadManagerRuntimeCore\";\nimport { Unsubscribe } from \"../types\";\nimport { ThreadManagerRuntimePath } from \"./RuntimePathTypes\";\n\nexport type ThreadManagerState = Readonly<{\n threads: readonly ThreadManagerMetadata[];\n archivedThreads: readonly ThreadManagerMetadata[];\n}>;\n\nexport type ThreadManagerRuntime = Readonly<{\n path: ThreadManagerRuntimePath;\n getState(): ThreadManagerState;\n\n rename(threadId: string, newTitle: string): Promise<void>;\n archive(threadId: string): Promise<void>;\n unarchive(threadId: string): Promise<void>;\n delete(threadId: string): Promise<void>;\n\n subscribe(callback: () => void): Unsubscribe;\n}>;\n\nconst getThreadManagerState = (\n threadManager: ThreadManagerRuntimeCore,\n): ThreadManagerState => {\n return {\n threads: threadManager.threads,\n archivedThreads: threadManager.archivedThreads,\n };\n};\n\nconst THREAD_MANAGER_PATH = {\n ref: \"threadManager\",\n};\n\nexport type ThreadManagerRuntimeCoreBinding = ThreadManagerRuntimeCore;\n\nexport class ThreadManagerRuntimeImpl implements ThreadManagerRuntime {\n public get path() {\n return THREAD_MANAGER_PATH;\n }\n\n private _getState;\n constructor(private _core: ThreadManagerRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n path: THREAD_MANAGER_PATH,\n getState: () => getThreadManagerState(_core),\n subscribe: (callback) => _core.subscribe(callback),\n });\n\n this._getState = stateBinding.getState.bind(stateBinding);\n }\n\n public getState(): ThreadManagerState {\n return this._getState();\n }\n\n public rename(threadId: string, newTitle: string): Promise<void> {\n return this._core.rename(threadId, newTitle);\n }\n\n public archive(threadId: string): Promise<void> {\n return this._core.archive(threadId);\n }\n\n public unarchive(threadId: string): Promise<void> {\n return this._core.unarchive(threadId);\n }\n\n public delete(threadId: string): Promise<void> {\n return this._core.delete(threadId);\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n return this._core.subscribe(callback);\n }\n}\n","import { AssistantRuntimeCore } from \"../runtimes/core/AssistantRuntimeCore\";\nimport { NestedSubscriptionSubject } from \"./subscribable/NestedSubscriptionSubject\";\nimport { ModelConfigProvider } from \"../types/ModelConfigTypes\";\nimport {\n ThreadRuntime,\n ThreadRuntimeCoreBinding,\n ThreadRuntimeImpl,\n} from \"./ThreadRuntime\";\nimport { Unsubscribe } from \"../types\";\nimport {\n ThreadManagerRuntime,\n ThreadManagerRuntimeImpl,\n} from \"./ThreadManagerRuntime\";\n\nexport type AssistantRuntime = {\n thread: ThreadRuntime;\n threadManager: ThreadManagerRuntime;\n\n switchToNewThread(): void;\n\n switchToThread(threadId: string): void;\n /**\n * @deprecated Use `switchToNewThread` instead. This will be removed in 0.6.0.\n */\n switchToThread(threadId: string | null): void;\n\n registerModelConfigProvider(provider: ModelConfigProvider): Unsubscribe;\n\n /**\n * @deprecated Thread is now static and never gets updated. This will be removed in 0.6.0.\n */\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport class AssistantRuntimeImpl\n implements\n Omit<AssistantRuntimeCore, \"thread\" | \"threadManager\">,\n AssistantRuntime\n{\n public readonly threadManager;\n\n protected constructor(\n private readonly _core: AssistantRuntimeCore,\n private readonly _thread: ThreadRuntime,\n ) {\n this.threadManager = new ThreadManagerRuntimeImpl(_core.threadManager);\n }\n\n public get thread() {\n return this._thread;\n }\n\n public switchToNewThread() {\n return this._core.threadManager.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 if (threadId === null) return this.switchToNewThread();\n return this._core.threadManager.switchToThread(threadId);\n }\n\n public registerModelConfigProvider(provider: ModelConfigProvider) {\n return this._core.registerModelConfigProvider(provider);\n }\n\n /**\n * @deprecated Thread is now static and never gets updated. This will be removed in 0.6.0.\n */\n public subscribe() {\n return () => {};\n }\n\n protected static createMainThreadRuntime(\n _core: AssistantRuntimeCore,\n CustomThreadRuntime: new (\n binding: ThreadRuntimeCoreBinding,\n ) => ThreadRuntime = ThreadRuntimeImpl,\n ) {\n return new CustomThreadRuntime(\n new NestedSubscriptionSubject({\n path: {\n ref: \"threads.main\",\n threadSelector: { type: \"main\" },\n },\n getState: () => _core.threadManager.mainThread,\n subscribe: (callback) => _core.threadManager.subscribe(callback),\n }),\n );\n }\n\n public static create(\n _core: AssistantRuntimeCore,\n CustomThreadRuntime: new (\n binding: ThreadRuntimeCoreBinding,\n ) => ThreadRuntime = ThreadRuntimeImpl,\n ) {\n return new AssistantRuntimeImpl(\n _core,\n AssistantRuntimeImpl.createMainThreadRuntime(_core, CustomThreadRuntime),\n ) as AssistantRuntime;\n }\n}\n","import { LanguageModelV1Message } from \"@ai-sdk/provider\";\nimport { CoreMessage, ToolCallContentPart } from \"../../../types\";\n\ntype fromLanguageModelMessagesOptions = {\n mergeSteps: boolean;\n};\n\nexport const fromLanguageModelMessages = (\n lm: LanguageModelV1Message[],\n { mergeSteps }: 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 (mergeSteps) {\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\n/**\n * @deprecated `streamUtils` will be replaced with `assistant-stream` once it is ready.\n */\nexport const streamUtils = {\n streamPartEncoderStream,\n streamPartDecoderStream,\n};\n","import { LocalRuntimeOptions, useLocalRuntime } from \"..\";\nimport { useState } from \"react\";\nimport { EdgeChatAdapterOptions, EdgeChatAdapter } from \"./EdgeChatAdapter\";\nimport { splitLocalRuntimeOptions } from \"../local/LocalRuntimeOptions\";\n\nexport type EdgeRuntimeOptions = EdgeChatAdapterOptions & LocalRuntimeOptions;\n\nexport const useEdgeRuntime = (options: EdgeRuntimeOptions) => {\n const { localRuntimeOptions, otherOptions } =\n splitLocalRuntimeOptions(options);\n const [adapter] = useState(() => new EdgeChatAdapter(otherOptions));\n return useLocalRuntime(adapter, localRuntimeOptions);\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.ToolCallDelta &&\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 { toolCallId: id, toolName: name } = value;\n toolCallNames.set(id, name);\n currentToolCall = { id, name, argsText: \"\" };\n\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId: id,\n toolName: name,\n argsTextDelta: \"\",\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallDelta: {\n const { toolCallId, argsTextDelta } = value;\n\n const toolName = toolCallNames.get(toolCallId)!;\n if (currentToolCall?.id === toolCallId) {\n currentToolCall.argsText += argsTextDelta;\n }\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId,\n toolName,\n argsTextDelta: argsTextDelta,\n });\n break;\n }\n case AssistantStreamChunkType.ToolCallResult: {\n controller.enqueue({\n type: \"tool-result\",\n toolCallType: \"function\",\n toolCallId: value.toolCallId,\n toolName: toolCallNames.get(value.toolCallId)!,\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\n case AssistantStreamChunkType.ToolCall: {\n const { toolCallId, toolName, args } = value;\n const argsText = JSON.stringify(args);\n controller.enqueue({\n type: \"tool-call-delta\",\n toolCallType: \"function\",\n toolCallId,\n toolName,\n argsTextDelta: argsText,\n });\n controller.enqueue({\n type: \"tool-call\",\n toolCallType: \"function\",\n toolCallId: toolCallId,\n toolName: toolName,\n args: argsText,\n });\n break;\n }\n\n case AssistantStreamChunkType.StepFinish: {\n controller.enqueue({\n type: \"step-finish\",\n ...value,\n });\n break;\n }\n\n // TODO\n case AssistantStreamChunkType.Data:\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.ok) {\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 { CoreMessage } from \"../../types\";\nimport { AttachmentAdapter } from \"../attachment/AttachmentAdapter\";\nimport { FeedbackAdapter } from \"../feedback/FeedbackAdapter\";\nimport { SpeechSynthesisAdapter } from \"../speech/SpeechAdapterTypes\";\nimport { ChatModelAdapter } from \"./ChatModelAdapter\";\n\nexport type LocalRuntimeOptionsBase = {\n maxSteps?: number | undefined;\n /**\n * @deprecated Use `maxSteps` (which is `maxToolRoundtrips` + 1; if you set `maxToolRoundtrips` to 2, set `maxSteps` to 3) instead. This field will be removed in v0.6.\n */\n maxToolRoundtrips?: number | undefined;\n adapters: {\n chatModel: ChatModelAdapter;\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n };\n};\n\n// TODO align LocalRuntimeOptions with LocalRuntimeOptionsBase\nexport type LocalRuntimeOptions = Omit<LocalRuntimeOptionsBase, \"adapters\"> & {\n initialMessages?: readonly CoreMessage[] | undefined;\n adapters?: Omit<LocalRuntimeOptionsBase[\"adapters\"], \"chatModel\"> | undefined;\n};\n\nexport const splitLocalRuntimeOptions = <T extends LocalRuntimeOptions>(\n options: T,\n) => {\n const { initialMessages, maxToolRoundtrips, maxSteps, adapters, ...rest } =\n options;\n\n return {\n localRuntimeOptions: {\n initialMessages,\n maxToolRoundtrips,\n maxSteps,\n adapters,\n },\n otherOptions: rest,\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 { AttachmentAdapter } from \"../attachment\";\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 protected getAttachmentAdapter() {\n return this.runtime.adapters?.attachments;\n }\n\n private _nonTextParts;\n private _previousText;\n private _parentId;\n constructor(\n private runtime: Omit<ThreadRuntimeCore, \"composer\"> & {\n adapters?: { attachments?: AttachmentAdapter | undefined } | undefined;\n },\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 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 type {\n ModelConfigProvider,\n AppendMessage,\n Unsubscribe,\n} from \"../../types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/MessageRepository\";\nimport { DefaultThreadComposerRuntimeCore } from \"../composer/DefaultThreadComposerRuntimeCore\";\nimport {\n AddToolResultOptions,\n ThreadSuggestion,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n SpeechState,\n RuntimeCapabilities,\n SubmittedFeedback,\n ThreadRuntimeEventType,\n} from \"../core/ThreadRuntimeCore\";\nimport { DefaultEditComposerRuntimeCore } from \"../composer/DefaultEditComposerRuntimeCore\";\nimport { SpeechSynthesisAdapter } from \"../speech\";\nimport { FeedbackAdapter } from \"../feedback/FeedbackAdapter\";\nimport { AttachmentAdapter } from \"../attachment\";\nimport { getThreadMessageText } from \"../../utils/getThreadMessageText\";\n\ntype BaseThreadAdapters = {\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n attachments?: AttachmentAdapter | undefined;\n};\n\nexport abstract class BaseThreadRuntimeCore implements ThreadRuntimeCore {\n private _subscriptions = new Set<() => void>();\n\n protected readonly repository = new MessageRepository();\n public abstract get adapters(): BaseThreadAdapters | undefined;\n\n public abstract get threadId(): string;\n public abstract get isDisabled(): boolean;\n public abstract get suggestions(): readonly ThreadSuggestion[];\n public abstract get extras(): unknown;\n\n public abstract get capabilities(): RuntimeCapabilities;\n public abstract append(message: AppendMessage): void;\n public abstract startRun(parentId: string | null): void;\n public abstract addToolResult(options: AddToolResultOptions): void;\n public abstract cancelRun(): void;\n\n public get messages() {\n return this.repository.getMessages();\n }\n\n public readonly composer = new DefaultThreadComposerRuntimeCore(this);\n\n constructor(private configProvider: ModelConfigProvider) {}\n\n public getModelConfig() {\n return this.configProvider.getModelConfig();\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 getMessageById(messageId: string) {\n return this.repository.getMessage(messageId);\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 protected _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n\n public _notifyEventSubscribers(event: ThreadRuntimeEventType) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n for (const callback of subscribers) callback();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private _submittedFeedback: Record<string, SubmittedFeedback> = {};\n\n public getSubmittedFeedback(messageId: string) {\n return this._submittedFeedback[messageId];\n }\n\n public submitFeedback({ messageId, type }: SubmitFeedbackOptions) {\n const adapter = this.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 this._submittedFeedback[messageId] = { type };\n this._notifySubscribers();\n }\n\n private _stopSpeaking: Unsubscribe | undefined;\n public speech: SpeechState | undefined;\n\n public speak(messageId: string) {\n const adapter = this.adapters?.speech;\n if (!adapter) throw new Error(\"Speech adapter not configured\");\n\n const { message } = this.repository.getMessage(messageId);\n\n this._stopSpeaking?.();\n\n const utterance = adapter.speak(getThreadMessageText(message));\n const unsub = utterance.subscribe(() => {\n if (utterance.status.type === \"ended\") {\n this._stopSpeaking = undefined;\n this.speech = undefined;\n } else {\n this.speech = { messageId, status: utterance.status };\n }\n this._notifySubscribers();\n });\n\n this.speech = { messageId, status: utterance.status };\n this._notifySubscribers();\n\n this._stopSpeaking = () => {\n utterance.cancel();\n unsub();\n this.speech = undefined;\n this._stopSpeaking = undefined;\n };\n }\n\n public stopSpeaking() {\n if (!this._stopSpeaking) throw new Error(\"No message is being spoken\");\n this._stopSpeaking();\n this._notifySubscribers();\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 private _eventSubscribers = new Map<string, Set<() => void>>();\n\n public unstable_on(event: ThreadRuntimeEventType, callback: () => void) {\n if (event === \"model-config-update\") {\n return this.configProvider.subscribe?.(callback) ?? (() => {});\n }\n\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n this._eventSubscribers.set(event, new Set([callback]));\n } else {\n subscribers.add(callback);\n }\n\n return () => {\n const subscribers = this._eventSubscribers.get(event)!;\n subscribers.delete(callback);\n };\n }\n}\n","import { generateId } from \"../../internal\";\nimport type {\n ModelConfigProvider,\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types\";\nimport { fromCoreMessage } from \"../edge\";\nimport type { ChatModelRunResult } from \"./ChatModelAdapter\";\nimport { shouldContinue } from \"./shouldContinue\";\nimport { LocalRuntimeOptionsBase } from \"./LocalRuntimeOptions\";\nimport {\n AddToolResultOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n} from \"../core/ThreadRuntimeCore\";\nimport { BaseThreadRuntimeCore } from \"../core/BaseThreadRuntimeCore\";\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n edit: true,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n attachments: false,\n feedback: false,\n };\n\n private abortController: AbortController | null = null;\n\n public readonly isDisabled = false;\n public readonly suggestions: readonly ThreadSuggestion[] = [];\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n configProvider: ModelConfigProvider,\n public readonly threadId: string,\n options: LocalRuntimeOptionsBase,\n ) {\n super(configProvider);\n\n this._options = options;\n }\n\n private _options: LocalRuntimeOptionsBase;\n\n public get extras() {\n return undefined;\n }\n\n public setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n public 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 this._notifyEventSubscribers(\"run-start\");\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 initialSteps = message.metadata?.steps;\n const initalCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps || m.metadata?.roundtrips;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\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 ...(steps ? { roundtrips: steps } : undefined),\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(steps ? { roundtrips: steps, steps } : 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 maxSteps = this._options.maxSteps\n ? this._options.maxSteps\n : (this._options.maxToolRoundtrips ?? 1) + 1;\n\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\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.adapters.chatModel.run({\n messages,\n abortSignal: this.abortController.signal,\n config: this.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 public cancelRun() {\n this.abortController?.abort();\n this.abortController = null;\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","import type { Unsubscribe } from \"../../types\";\nimport {\n ThreadManagerMetadata,\n ThreadManagerRuntimeCore,\n} from \"../core/ThreadManagerRuntimeCore\";\nimport { ExportedMessageRepository } from \"../utils/MessageRepository\";\nimport { generateId } from \"../../utils/idUtils\";\nimport { LocalThreadRuntimeCore } from \"./LocalThreadRuntimeCore\";\n\nexport type LocalThreadData = {\n data: ExportedMessageRepository;\n metadata: ThreadManagerMetadata;\n isArchived: boolean;\n};\n\nexport type LocalThreadFactory = (\n threadId: string,\n data: ExportedMessageRepository,\n) => LocalThreadRuntimeCore;\n\nexport class LocalThreadManagerRuntimeCore implements ThreadManagerRuntimeCore {\n private _threadData = new Map<string, LocalThreadData>();\n\n private _threads: readonly ThreadManagerMetadata[] = [];\n private _archivedThreads: readonly ThreadManagerMetadata[] = [];\n\n public get threads() {\n return this._threads;\n }\n\n public get archivedThreads() {\n return this._archivedThreads;\n }\n\n private _mainThread: LocalThreadRuntimeCore;\n\n public get mainThread(): LocalThreadRuntimeCore {\n return this._mainThread;\n }\n\n constructor(private _threadFactory: LocalThreadFactory) {\n const threadId = generateId();\n this._threadData.set(threadId, {\n data: { messages: [] },\n metadata: { threadId },\n isArchived: false,\n });\n this._threads = [{ threadId }];\n this._mainThread = this._threadFactory(threadId, { messages: [] });\n }\n\n public switchToThread(threadId: string): void {\n if (this._mainThread.threadId === threadId) return;\n\n const data = this._threadData.get(threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n const thread = this._threadFactory(threadId, data.data);\n this._performThreadSwitch(thread);\n }\n\n public switchToNewThread(): void {\n const threadId = generateId();\n this._threadData.set(threadId, {\n data: { messages: [] },\n metadata: { threadId },\n isArchived: false,\n });\n this._threads = [{ threadId }];\n const thread = this._threadFactory(threadId, { messages: [] });\n this._performThreadSwitch(thread);\n }\n\n private _performThreadSwitch(newThreadCore: LocalThreadRuntimeCore) {\n const data = this._threadData.get(this._mainThread.threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n const exprt = this._mainThread.export();\n data.data = exprt;\n\n this._mainThread._notifyEventSubscribers(\"switched-away\");\n this._mainThread = newThreadCore;\n newThreadCore._notifyEventSubscribers(\"switched-to\");\n\n this._notifySubscribers();\n }\n\n private _performMoveOp(\n threadId: string,\n operation: \"archive\" | \"unarchive\" | \"delete\",\n ) {\n const data = this._threadData.get(threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n if (operation === \"archive\" && data.isArchived) return;\n if (operation === \"unarchive\" && !data.isArchived) return;\n\n if (operation === \"archive\") {\n data.isArchived = true;\n this._archivedThreads = [...this._archivedThreads, data.metadata];\n }\n if (operation === \"unarchive\") {\n data.isArchived = false;\n this._threads = [...this._threads, data.metadata];\n }\n if (operation === \"delete\") {\n this._threadData.delete(threadId);\n }\n\n if (\n operation === \"archive\" ||\n (operation === \"delete\" && data.isArchived)\n ) {\n this._archivedThreads = this._archivedThreads.filter(\n (t) => t.threadId !== threadId,\n );\n }\n\n if (\n operation === \"unarchive\" ||\n (operation === \"delete\" && !data.isArchived)\n ) {\n this._threads = this._threads.filter((t) => t.threadId !== threadId);\n }\n\n this._notifySubscribers();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const data = this._threadData.get(threadId);\n if (!data) throw new Error(\"Thread not found\");\n\n data.metadata = {\n ...data.metadata,\n title: newTitle,\n };\n\n const threadList = data.isArchived ? this.archivedThreads : this.threads;\n const idx = threadList.findIndex((t) => t.threadId === threadId);\n const updatedThreadList = threadList.toSpliced(idx, 1, data.metadata);\n if (data.isArchived) {\n this._archivedThreads = updatedThreadList;\n } else {\n this._threads = updatedThreadList;\n }\n this._notifySubscribers();\n }\n\n public async archive(threadId: string): Promise<void> {\n this._performMoveOp(threadId, \"archive\");\n }\n\n public async unarchive(threadId: string): Promise<void> {\n this._performMoveOp(threadId, \"unarchive\");\n }\n\n public async delete(threadId: string): Promise<void> {\n this._performMoveOp(threadId, \"delete\");\n }\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 _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n","import type { CoreMessage } from \"../../types/AssistantTypes\";\nimport { BaseAssistantRuntimeCore } from \"../core/BaseAssistantRuntimeCore\";\nimport { LocalThreadRuntimeCore } from \"./LocalThreadRuntimeCore\";\nimport { LocalRuntimeOptionsBase } from \"./LocalRuntimeOptions\";\nimport { fromCoreMessages } from \"../edge/converters/fromCoreMessage\";\nimport { LocalThreadManagerRuntimeCore } from \"./LocalThreadManagerRuntimeCore\";\nimport { ExportedMessageRepository } from \"../utils/MessageRepository\";\n\nconst getExportFromInitialMessages = (\n initialMessages: readonly CoreMessage[],\n): ExportedMessageRepository => {\n const messages = fromCoreMessages(initialMessages);\n return {\n messages: messages.map((m, idx) => ({\n parentId: messages[idx - 1]?.id ?? null,\n message: m,\n })),\n };\n};\n\nexport class LocalRuntimeCore extends BaseAssistantRuntimeCore {\n public readonly threadManager;\n\n private _options: LocalRuntimeOptionsBase;\n\n constructor(\n options: LocalRuntimeOptionsBase,\n initialMessages?: CoreMessage[],\n ) {\n super();\n\n this._options = options;\n\n this.threadManager = new LocalThreadManagerRuntimeCore((threadId, data) => {\n const thread = new LocalThreadRuntimeCore(\n this._proxyConfigProvider,\n threadId,\n this._options,\n );\n thread.import(data);\n return thread;\n });\n\n if (initialMessages) {\n this.threadManager.mainThread.import(\n getExportFromInitialMessages(initialMessages),\n );\n }\n }\n\n public setOptions(options: LocalRuntimeOptionsBase) {\n this._options = options;\n\n this.threadManager.mainThread.setOptions(options);\n }\n\n public reset({\n initialMessages,\n }: {\n initialMessages?: readonly CoreMessage[] | undefined;\n } = {}) {\n this.threadManager.switchToNewThread();\n if (!initialMessages) return;\n\n this.threadManager.mainThread.import(\n getExportFromInitialMessages(initialMessages),\n );\n }\n}\n","import { useEffect, useMemo, useState } from \"react\";\nimport { ExternalStoreRuntimeCore } from \"./ExternalStoreRuntimeCore\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { AssistantRuntimeImpl } from \"../../api/AssistantRuntime\";\nimport { ThreadRuntimeImpl } from \"../../api/ThreadRuntime\";\n\nexport const useExternalStoreRuntime = <T,>(store: ExternalStoreAdapter<T>) => {\n const [runtime] = useState(() => new ExternalStoreRuntimeCore(store));\n\n useEffect(() => {\n runtime.setStore(store);\n });\n\n return useMemo(\n () => AssistantRuntimeImpl.create(runtime, ThreadRuntimeImpl),\n [runtime],\n );\n};\n","import type { Unsubscribe } from \"../../types\";\nimport { ExternalStoreThreadRuntimeCore } from \"./ExternalStoreThreadRuntimeCore\";\nimport { ThreadManagerRuntimeCore } from \"../core/ThreadManagerRuntimeCore\";\nimport { ExternalStoreThreadManagerAdapter } from \"./ExternalStoreAdapter\";\n\nexport type ExternalStoreThreadFactory = (\n threadId: string,\n) => ExternalStoreThreadRuntimeCore;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst DEFAULT_THREAD_ID = \"DEFAULT_THREAD_ID\";\n\nexport class ExternalStoreThreadManagerRuntimeCore\n implements ThreadManagerRuntimeCore\n{\n public get threads() {\n return this.adapter.threads ?? EMPTY_ARRAY;\n }\n\n public get archivedThreads() {\n return this.adapter.archivedThreads ?? EMPTY_ARRAY;\n }\n\n private _mainThread: ExternalStoreThreadRuntimeCore;\n\n public get mainThread() {\n return this._mainThread;\n }\n\n constructor(\n private adapter: ExternalStoreThreadManagerAdapter = {},\n private threadFactory: ExternalStoreThreadFactory,\n ) {\n this._mainThread = this.threadFactory(DEFAULT_THREAD_ID);\n }\n\n public setAdapter(adapter: ExternalStoreThreadManagerAdapter) {\n const previousAdapter = this.adapter;\n this.adapter = adapter;\n\n const newThreadId = adapter.threadId ?? DEFAULT_THREAD_ID;\n const newThreads = adapter.threads ?? EMPTY_ARRAY;\n const newArchivedThreads = adapter.archivedThreads ?? EMPTY_ARRAY;\n\n if (\n previousAdapter.threadId === newThreadId &&\n previousAdapter.threads === newThreads &&\n previousAdapter.archivedThreads === newArchivedThreads\n ) {\n return;\n }\n\n if (previousAdapter.threadId !== newThreadId) {\n this._mainThread._notifyEventSubscribers(\"switched-away\");\n this._mainThread = this.threadFactory(newThreadId);\n this._mainThread._notifyEventSubscribers(\"switched-to\");\n }\n\n this._notifySubscribers();\n }\n\n public switchToThread(threadId: string): void {\n if (this._mainThread?.threadId === threadId) return;\n const onSwitchToThread = this.adapter.onSwitchToThread;\n if (!onSwitchToThread)\n throw new Error(\n \"External store adapter does not support switching to thread\",\n );\n onSwitchToThread(threadId);\n }\n\n public switchToNewThread(): void {\n const onSwitchToNewThread = this.adapter.onSwitchToNewThread;\n if (!onSwitchToNewThread)\n throw new Error(\n \"External store adapter does not support switching to new thread\",\n );\n\n onSwitchToNewThread();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const onRename = this.adapter.onRename;\n if (!onRename)\n throw new Error(\"External store adapter does not support renaming\");\n\n onRename(threadId, newTitle);\n }\n\n public async archive(threadId: string): Promise<void> {\n const onArchive = this.adapter.onArchive;\n if (!onArchive)\n throw new Error(\"External store adapter does not support archiving\");\n\n onArchive(threadId);\n }\n\n public async unarchive(threadId: string): Promise<void> {\n const onUnarchive = this.adapter.onUnarchive;\n if (!onUnarchive)\n throw new Error(\"External store adapter does not support unarchiving\");\n\n onUnarchive(threadId);\n }\n\n public async delete(threadId: string): Promise<void> {\n const onDelete = this.adapter.onDelete;\n if (!onDelete)\n throw new Error(\"External store adapter does not support deleting\");\n\n onDelete(threadId);\n }\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 _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n","import { ThreadMessage } from \"../../types\";\n\nexport const symbolInnerMessage = Symbol(\"innerMessage\");\n\nexport type ExternalStoreThreadMessage<T> = ThreadMessage & {\n [symbolInnerMessage]?: T;\n};\n\nexport const getExternalStoreMessage = <T,>(message: ThreadMessage) => {\n return (message as ExternalStoreThreadMessage<T>)[symbolInnerMessage];\n};\n","import { ThreadMessage } from \"../../types\";\n\nexport type ConverterCallback<TIn> = (\n cache: ThreadMessage | undefined,\n message: TIn,\n idx: number,\n) => ThreadMessage;\n\nexport class ThreadMessageConverter {\n private readonly cache = new WeakMap<WeakKey, ThreadMessage>();\n\n convertMessages<TIn extends WeakKey>(\n messages: TIn[],\n converter: ConverterCallback<TIn>,\n ): ThreadMessage[] {\n return messages.map((m, idx) => {\n const cached = this.cache.get(m);\n const newMessage = converter(cached, m, idx);\n this.cache.set(m, newMessage);\n return newMessage;\n });\n }\n}\n","import { MessageStatus } from \"../../types\";\n\nconst AUTO_STATUS_RUNNING = Object.freeze({ type: \"running\" });\nconst AUTO_STATUS_COMPLETE = Object.freeze({\n type: \"complete\",\n reason: \"unknown\",\n});\n\nexport const isAutoStatus = (status: MessageStatus) =>\n status === AUTO_STATUS_RUNNING || status === AUTO_STATUS_COMPLETE;\n\nexport const getAutoStatus = (isLast: boolean, isRunning: boolean) =>\n isLast && isRunning ? AUTO_STATUS_RUNNING : AUTO_STATUS_COMPLETE;\n","import {\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, ThreadSuggestion } from \"../core\";\n\nimport { AppendMessage, ModelConfigProvider, ThreadMessage } 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 {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../core/ThreadRuntimeCore\";\nimport { BaseThreadRuntimeCore } from \"../core/BaseThreadRuntimeCore\";\n\nconst EMPTY_ARRAY = Object.freeze([]);\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\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\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 speech: false,\n attachments: false,\n feedback: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n public threadId!: string;\n private _messages!: ThreadMessage[];\n public isDisabled!: boolean;\n\n public override get messages() {\n return this._messages;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n configProvider: ModelConfigProvider,\n threadId: string,\n store: ExternalStoreAdapter<any>,\n ) {\n super(configProvider);\n this.threadId = threadId;\n this.setStore(store);\n }\n\n public setStore(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\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.extras = store.extras;\n this.suggestions = store.suggestions ?? EMPTY_ARRAY;\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 speech: this._store.adapters?.speech !== 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 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 override 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 private updateMessages = (messages: ThreadMessage[]) => {\n this._store.setMessages?.(\n messages.flatMap(getExternalStoreMessage).filter((m) => m != null),\n );\n };\n}\n","import { BaseAssistantRuntimeCore } from \"../../internal\";\nimport { ExternalStoreThreadManagerRuntimeCore } from \"./ExternalStoreThreadManagementAdapter\";\nimport { ExternalStoreAdapter } from \"./ExternalStoreAdapter\";\nimport { ExternalStoreThreadRuntimeCore } from \"./ExternalStoreThreadRuntimeCore\";\n\nconst getThreadManagerAdapter = (store: ExternalStoreAdapter<any>) => {\n return {\n threadId: store.threadId,\n onSwitchToNewThread: store.onSwitchToNewThread,\n onSwitchToThread: store.onSwitchToThread,\n ...store.adapters?.threadManager,\n };\n};\n\nexport class ExternalStoreRuntimeCore extends BaseAssistantRuntimeCore {\n public readonly threadManager;\n\n private _store: ExternalStoreAdapter<any>;\n\n constructor(store: ExternalStoreAdapter<any>) {\n super();\n this._store = store;\n this.threadManager = new ExternalStoreThreadManagerRuntimeCore(\n getThreadManagerAdapter(store),\n (threadId) =>\n new ExternalStoreThreadRuntimeCore(\n this._proxyConfigProvider,\n threadId,\n this._store,\n ),\n );\n }\n\n public setStore(store: ExternalStoreAdapter<any>) {\n this._store = store;\n this.threadManager.setAdapter(getThreadManagerAdapter(store));\n this.threadManager.mainThread.setStore(store);\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\";\nimport { splitLocalRuntimeOptions } from \"../local/LocalRuntimeOptions\";\n\nexport type DangerousInBrowserRuntimeOptions =\n DangerousInBrowserAdapterOptions & LocalRuntimeOptions;\n\nexport const useDangerousInBrowserRuntime = (\n options: DangerousInBrowserRuntimeOptions,\n) => {\n const { localRuntimeOptions, otherOptions } =\n splitLocalRuntimeOptions(options);\n const [adapter] = useState(() => new DangerousInBrowserAdapter(otherOptions));\n return useLocalRuntime(adapter, localRuntimeOptions);\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 { SpeechSynthesisAdapter } from \"./SpeechAdapterTypes\";\n\nexport class WebSpeechSynthesisAdapter implements SpeechSynthesisAdapter {\n speak(text: string): SpeechSynthesisAdapter.Utterance {\n const utterance = new SpeechSynthesisUtterance(text);\n\n const subscribers = 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 subscribers.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 subscribe: (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 subscribers.add(callback);\n return () => {\n subscribers.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 | undefined;\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 welcome?: {\n message?: string | undefined;\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 | undefined;\n\n assistantAvatar?: AvatarProps | undefined;\n\n welcome?: ThreadWelcomeConfig | undefined;\n assistantMessage?: AssistantMessageConfig | undefined;\n userMessage?: UserMessageConfig | undefined;\n\n branchPicker?: BranchPickerConfig | undefined;\n\n composer?: ComposerConfig | undefined;\n\n strings?: StringsConfig | undefined;\n\n tools?: AssistantToolUI[] | undefined; // TODO add AssistantTool support\n\n components?:\n | {\n Composer?: ComponentType | undefined;\n ThreadWelcome?: ComponentType | undefined;\n }\n | undefined;\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 speechSupported = useThread((t) => t.capabilities.speech);\n return allowSpeak && (!ensureCapability || speechSupported);\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\nnamespace AssistantActionBarCopy {\n export type Element = ActionBarPrimitive.Copy.Element;\n export type Props = Partial<TooltipIconButtonProps> & {\n copiedDuration?: number | undefined;\n };\n}\n\nconst AssistantActionBarCopy = forwardRef<\n AssistantActionBarCopy.Element,\n AssistantActionBarCopy.Props\n>(({ copiedDuration, ...props }, ref) => {\n const {\n strings: {\n assistantMessage: { copy: { tooltip = \"Copy\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n return (\n <ActionBarPrimitive.Copy copiedDuration={copiedDuration} 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\nnamespace AssistantActionBarSpeak {\n export type Element = ActionBarPrimitive.Speak.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarSpeak = forwardRef<\n AssistantActionBarSpeak.Element,\n AssistantActionBarSpeak.Props\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\nnamespace AssistantActionBarStopSpeaking {\n export type Element = ActionBarPrimitive.StopSpeaking.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarStopSpeaking = forwardRef<\n AssistantActionBarStopSpeaking.Element,\n AssistantActionBarStopSpeaking.Props\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\nnamespace AssistantActionBarReload {\n export type Element = ActionBarPrimitive.Reload.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarReload = forwardRef<\n AssistantActionBarReload.Element,\n AssistantActionBarReload.Props\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\nnamespace AssistantActionBarFeedbackPositive {\n export type Element = ActionBarPrimitive.FeedbackPositive.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarFeedbackPositive = forwardRef<\n AssistantActionBarFeedbackPositive.Element,\n AssistantActionBarFeedbackPositive.Props\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\nnamespace AssistantActionBarFeedbackNegative {\n export type Element = ActionBarPrimitive.FeedbackNegative.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantActionBarFeedbackNegative = forwardRef<\n AssistantActionBarFeedbackNegative.Element,\n AssistantActionBarFeedbackNegative.Props\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 } 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\n/**\n * @deprecated Use `AssistantMessage.Content.Props` instead. This will be removed in 0.6.\n */\nexport type AssistantMessageContentProps = AssistantMessageContent.Props;\n\nnamespace AssistantMessageContent {\n export type Element = HTMLDivElement;\n export type Props = MessagePrimitive.Content.Props &\n ComponentPropsWithoutRef<\"div\">;\n}\n\nconst AssistantMessageContent = forwardRef<\n AssistantMessageContent.Element,\n AssistantMessageContent.Props\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\nnamespace BranchPickerPrevious {\n export type Element = BranchPickerPrimitive.Previous.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst BranchPickerPrevious = forwardRef<\n BranchPickerPrevious.Element,\n BranchPickerPrevious.Props\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\nnamespace BranchPickerState {\n export type Element = HTMLSpanElement;\n export type Props = ComponentPropsWithoutRef<\"span\">;\n}\n\nconst BranchPickerState = forwardRef<\n BranchPickerState.Element,\n BranchPickerState.Props\n>((props, ref) => {\n return (\n <BranchPickerStateWrapper {...props} ref={ref}>\n <BranchPickerPrimitive.Number /> / <BranchPickerPrimitive.Count />\n </BranchPickerStateWrapper>\n );\n});\n\nBranchPickerState.displayName = \"BranchPickerState\";\n\nnamespace BranchPickerNext {\n export type Element = BranchPickerPrimitive.Next.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst BranchPickerNext = forwardRef<\n BranchPickerNext.Element,\n BranchPickerNext.Props\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 { AssistantModalPrimitive } 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\nnamespace AssistantModalRoot {\n export type Props = AssistantModalPrimitive.Root.Props &\n ThreadConfigProviderProps;\n}\n\nconst AssistantModalRoot: FC<AssistantModalRoot.Props> = ({\n config,\n ...props\n}) => {\n return (\n <ThreadConfigProvider config={config}>\n <AssistantModalPrimitive.Root {...props} />\n </ThreadConfigProvider>\n );\n};\n\nAssistantModalRoot.displayName = \"AssistantModalRoot\";\n\nnamespace AssistantModalTrigger {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AssistantModalTrigger = forwardRef<\n AssistantModalTrigger.Element,\n AssistantModalTrigger.Props\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\nnamespace AssistantModalButton {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps> & {\n \"data-state\"?: \"open\" | \"closed\";\n };\n}\n\nconst AssistantModalButton = forwardRef<\n AssistantModalButton.Element,\n AssistantModalButton.Props\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 } from \"../primitives\";\nimport { useThread } from \"../context\";\n\nconst Thread: FC<ThreadConfig> = (config) => {\n const {\n components: {\n Composer: ComposerComponent = Composer,\n ThreadWelcome: ThreadWelcomeComponent = ThreadWelcome,\n } = {},\n } = config;\n return (\n <ThreadRoot config={config}>\n <ThreadViewport>\n <ThreadWelcomeComponent />\n <ThreadMessages />\n <ThreadFollowupSuggestions />\n <ThreadViewportFooter>\n <ThreadScrollToBottom />\n <ComposerComponent />\n </ThreadViewportFooter>\n </ThreadViewport>\n </ThreadRoot>\n );\n};\n\n/**\n * @deprecated Use `Thread.Root.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadRootProps = ThreadRoot.Props;\n\nnamespace ThreadRoot {\n export type Element = HTMLDivElement;\n export type Props = ThreadPrimitive.Root.Props & ThreadConfigProviderProps;\n}\n\nconst ThreadRootStyled = withDefaults(ThreadPrimitive.Root, {\n className: \"aui-root aui-thread-root\",\n});\n\nconst ThreadRoot = forwardRef<ThreadRoot.Element, ThreadRoot.Props>(\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 unstable_flexGrowDiv?: boolean;\n components?: {\n UserMessage?: ComponentType | undefined;\n EditComposer?: ComponentType | undefined;\n AssistantMessage?: ComponentType | undefined;\n SystemMessage?: ComponentType | undefined;\n };\n}> = ({ components, unstable_flexGrowDiv: flexGrowDiv = true, ...rest }) => {\n return (\n <>\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 {flexGrowDiv && (\n <ThreadPrimitive.If empty={false}>\n <div style={{ flexGrow: 1 }} />\n </ThreadPrimitive.If>\n )}\n </>\n );\n};\n\nThreadMessages.displayName = \"ThreadMessages\";\n\nconst ThreadFollowupSuggestions: FC = () => {\n const suggestions = useThread((t) => t.suggestions);\n\n return (\n <ThreadPrimitive.If empty={false} running={false}>\n <div className=\"aui-thread-followup-suggestions\">\n {suggestions?.map((suggestion, idx) => (\n <ThreadPrimitive.Suggestion\n key={idx}\n className=\"aui-thread-followup-suggestion\"\n prompt={suggestion.prompt}\n method=\"replace\"\n autoSend\n >\n {suggestion.prompt}\n </ThreadPrimitive.Suggestion>\n ))}\n </div>\n </ThreadPrimitive.If>\n );\n};\n\nconst ThreadScrollToBottomIconButton = withDefaults(TooltipIconButton, {\n variant: \"outline\",\n className: \"aui-thread-scroll-to-bottom\",\n});\n\nnamespace ThreadScrollToBottom {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ThreadScrollToBottom = forwardRef<\n ThreadScrollToBottom.Element,\n ThreadScrollToBottom.Props\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 FollowupSuggestions: ThreadFollowupSuggestions,\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 Attachment from \"./attachment\";\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\nnamespace ComposerInput {\n export type Element = HTMLTextAreaElement;\n export type Props = ComponentPropsWithoutRef<typeof ComposerInputStyled>;\n}\n\n/**\n * @deprecated Use `ComposerInput.Props` instead. This will be removed in 0.6.\n */\nexport type ComposerInputProps = ComposerInput.Props;\n\nconst ComposerInput = forwardRef<ComposerInput.Element, ComposerInput.Props>(\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\nnamespace ComposerAttachments {\n export type Props = Partial<ComposerPrimitive.Attachments.Props>;\n}\n\nconst ComposerAttachments: FC<ComposerAttachments.Props> = ({ components }) => {\n return (\n <ComposerAttachmentsContainer>\n <ComposerPrimitive.Attachments\n components={{\n ...components,\n Attachment: components?.Attachment ?? Attachment,\n }}\n />\n </ComposerAttachmentsContainer>\n );\n};\n\nconst ComposerAttachButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-attach\",\n});\n\nnamespace ComposerAddAttachment {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ComposerAddAttachment = forwardRef<\n ComposerAddAttachment.Element,\n ComposerAddAttachment.Props\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\nnamespace ComposerSend {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ComposerSend = forwardRef<ComposerSend.Element, ComposerSend.Props>(\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);\n\nComposerSend.displayName = \"ComposerSend\";\n\nconst ComposerCancelButton = withDefaults(TooltipIconButton, {\n variant: \"default\",\n className: \"aui-composer-cancel\",\n});\n\nnamespace ComposerCancel {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst ComposerCancel = forwardRef<ComposerCancel.Element, ComposerCancel.Props>(\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);\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 {\n forwardRef,\n PropsWithChildren,\n useEffect,\n useState,\n type FC,\n} from \"react\";\nimport { CircleXIcon, FileIcon } 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 { AttachmentPrimitive } from \"../primitives\";\nimport { useAttachment } from \"../context/react/AttachmentContext\";\nimport {\n AvatarImage,\n AvatarRoot,\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"./base\";\nimport { Dialog, DialogTrigger, DialogContent } from \"./base/dialog\";\nimport { AvatarFallback } from \"@radix-ui/react-avatar\";\n\nconst AttachmentRoot = withDefaults(AttachmentPrimitive.Root, {\n className: \"aui-attachment-root\",\n});\n\nAttachmentRoot.displayName = \"AttachmentRoot\";\n\nconst useFileSrc = (file: File | undefined) => {\n const [src, setSrc] = useState<string | undefined>(undefined);\n\n useEffect(() => {\n if (!file) {\n setSrc(undefined);\n return;\n }\n\n const objectUrl = URL.createObjectURL(file);\n setSrc(objectUrl);\n\n return () => {\n URL.revokeObjectURL(objectUrl);\n };\n }, [file]);\n\n return src;\n};\n\nconst useAttachmentSrc = () => {\n const { file, src } = useAttachment((a): { file?: File; src?: string } => {\n if (a.type !== \"image\") return {};\n if (a.file) return { file: a.file };\n const src = a.content?.filter((c) => c.type === \"image\")[0]?.image;\n if (!src) return {};\n return { src };\n });\n\n return useFileSrc(file) ?? src;\n};\n\ntype AttachmentPreviewProps = {\n src: string;\n};\n\nconst AttachmentPreview: FC<AttachmentPreviewProps> = ({ src }) => {\n const [isLoaded, setIsLoaded] = useState(false);\n\n return (\n // eslint-disable-next-line @next/next/no-img-element\n <img\n src={src}\n style={{\n width: \"auto\",\n height: \"auto\",\n maxWidth: \"75dvh\",\n maxHeight: \"75dvh\",\n display: isLoaded ? \"block\" : \"none\",\n overflow: \"clip\",\n }}\n onLoad={() => setIsLoaded(true)}\n alt=\"Image Preview\"\n />\n );\n};\n\nconst AttachmentPreviewDialog: FC<PropsWithChildren> = ({ children }) => {\n const src = useAttachmentSrc();\n\n if (!src) return children;\n\n return (\n <Dialog>\n <DialogTrigger className=\"aui-attachment-preview-trigger\" asChild>\n {children}\n </DialogTrigger>\n <DialogContent>\n <AttachmentPreview src={src} />\n </DialogContent>\n </Dialog>\n );\n};\n\nconst AttachmentThumb: FC = () => {\n const isImage = useAttachment((a) => a.type === \"image\");\n const src = useAttachmentSrc();\n return (\n <AvatarRoot className=\"aui-attachment-thumb\">\n <AvatarFallback delayMs={isImage ? 200 : 0}>\n <FileIcon />\n </AvatarFallback>\n <AvatarImage src={src}></AvatarImage>\n </AvatarRoot>\n );\n};\n\nconst Attachment: FC = () => {\n const canRemove = useAttachment((a) => a.source !== \"message\");\n const typeLabel = useAttachment((a) => {\n const type = a.type;\n switch (type) {\n case \"image\":\n return \"Image\";\n case \"document\":\n return \"Document\";\n case \"file\":\n return \"File\";\n default:\n const _exhaustiveCheck: never = type;\n throw new Error(`Unknown attachment type: ${_exhaustiveCheck}`);\n }\n });\n return (\n <Tooltip>\n <AttachmentPreviewDialog>\n <TooltipTrigger asChild>\n <AttachmentRoot>\n <AttachmentThumb />\n <div className=\"aui-attachment-text\">\n <p className=\"aui-attachment-name\">\n <AttachmentPrimitive.Name />\n </p>\n <p className=\"aui-attachment-type\">{typeLabel}</p>\n </div>\n {canRemove && <AttachmentRemove />}\n </AttachmentRoot>\n </TooltipTrigger>\n </AttachmentPreviewDialog>\n <TooltipContent side=\"top\">\n <AttachmentPrimitive.Name />\n </TooltipContent>\n </Tooltip>\n );\n};\n\nAttachment.displayName = \"Attachment\";\n\nnamespace AttachmentRemove {\n export type Element = HTMLButtonElement;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst AttachmentRemove = forwardRef<\n AttachmentRemove.Element,\n AttachmentRemove.Props\n>((props, ref) => {\n const {\n strings: {\n composer: { removeAttachment: { tooltip = \"Remove file\" } = {} } = {},\n } = {},\n } = useThreadConfig();\n\n return (\n <AttachmentPrimitive.Remove asChild>\n <TooltipIconButton\n tooltip={tooltip}\n className=\"aui-attachment-remove\"\n side=\"top\"\n {...props}\n ref={ref}\n >\n {props.children ?? <CircleXIcon />}\n </TooltipIconButton>\n </AttachmentPrimitive.Remove>\n );\n});\n\nAttachmentRemove.displayName = \"AttachmentRemove\";\n\nconst exports = {\n Root: AttachmentRoot,\n Remove: AttachmentRemove,\n};\n\nexport default Object.assign(Attachment, exports) as typeof Attachment &\n typeof exports;\n","\"use client\";\n\nimport * as React from \"react\";\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\";\n\nimport classNames from \"classnames\";\n\nconst Dialog = DialogPrimitive.Root;\n\nconst DialogTrigger = DialogPrimitive.Trigger;\n\nconst DialogPortal = DialogPrimitive.Portal;\n\nconst DialogClose = DialogPrimitive.Close;\n\nconst DialogOverlay = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Overlay>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Overlay\n ref={ref}\n className={classNames(\"aui-dialog-overlay\", className)}\n {...props}\n />\n));\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName;\n\nconst DialogContent = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n <DialogPortal>\n <DialogOverlay />\n <DialogPrimitive.Content\n ref={ref}\n className={classNames(\"aui-dialog-content\", className)}\n {...props}\n >\n {children}\n {/* <DialogPrimitive.Close className=\"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none\">\n <XIcon className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </DialogPrimitive.Close> */}\n </DialogPrimitive.Content>\n </DialogPortal>\n));\nDialogContent.displayName = DialogPrimitive.Content.displayName;\n\n// const DialogHeader = ({\n// className,\n// ...props\n// }: React.HTMLAttributes<HTMLDivElement>) => (\n// <div\n// className={classNames(\n// \"flex flex-col space-y-1.5 text-center sm:text-left\",\n// className,\n// )}\n// {...props}\n// />\n// );\n// DialogHeader.displayName = \"DialogHeader\";\n\n// const DialogFooter = ({\n// className,\n// ...props\n// }: React.HTMLAttributes<HTMLDivElement>) => (\n// <div\n// className={classNames(\n// \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n// className,\n// )}\n// {...props}\n// />\n// );\n// DialogFooter.displayName = \"DialogFooter\";\n\n// const DialogTitle = React.forwardRef<\n// React.ElementRef<typeof DialogPrimitive.Title>,\n// React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n// >(({ className, ...props }, ref) => (\n// <DialogPrimitive.Title\n// ref={ref}\n// className={classNames(\n// \"text-lg font-semibold leading-none tracking-tight\",\n// className,\n// )}\n// {...props}\n// />\n// ));\n// DialogTitle.displayName = DialogPrimitive.Title.displayName;\n\n// const DialogDescription = React.forwardRef<\n// React.ElementRef<typeof DialogPrimitive.Description>,\n// React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n// >(({ className, ...props }, ref) => (\n// <DialogPrimitive.Description\n// ref={ref}\n// className={classNames(\"text-muted-foreground text-sm\", className)}\n// {...props}\n// />\n// ));\n// DialogDescription.displayName = DialogPrimitive.Description.displayName;\n\nexport {\n Dialog,\n DialogPortal,\n DialogOverlay,\n DialogTrigger,\n DialogClose,\n DialogContent,\n // DialogHeader,\n // DialogFooter,\n // DialogTitle,\n // DialogDescription,\n};\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\";\nimport { useThread } from \"../context\";\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\nnamespace ThreadWelcomeRoot {\n export type Element = HTMLDivElement;\n export type Props = ComponentPropsWithoutRef<\"div\">;\n}\n\nconst ThreadWelcomeRoot = forwardRef<\n ThreadWelcomeRoot.Element,\n ThreadWelcomeRoot.Props\n>((props, ref) => {\n return (\n <ThreadPrimitive.Empty>\n <ThreadWelcomeRootStyled {...props} ref={ref} />\n </ThreadPrimitive.Empty>\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\n/**\n * @deprecated Use `ThreadWelcome.Message.Props` instead. This will be removed in 0.6.\n */\nexport type ThreadWelcomeMessageProps = ThreadWelcomeMessage.Props;\n\nnamespace ThreadWelcomeMessage {\n export type Element = HTMLParagraphElement;\n export type Props = Omit<\n ComponentPropsWithoutRef<typeof ThreadWelcomeMessageStyled>,\n \"children\"\n > & { message?: string | undefined };\n}\n\nconst ThreadWelcomeMessage = forwardRef<\n ThreadWelcomeMessage.Element,\n ThreadWelcomeMessage.Props\n>(({ message: messageProp, ...rest }, ref) => {\n const {\n welcome: { message } = {},\n strings: {\n welcome: { message: defaultMessage = \"How can I help you today?\" } = {},\n } = {},\n } = useThreadConfig();\n return (\n <ThreadWelcomeMessageStyled {...rest} ref={ref}>\n {messageProp ?? message ?? defaultMessage}\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 prompt={prompt} method=\"replace\" autoSend>\n <span className=\"aui-thread-welcome-suggestion-text\">\n {text ?? prompt}\n </span>\n </ThreadWelcomeSuggestionStyled>\n );\n};\n\nconst ThreadWelcomeSuggestions: FC = () => {\n const suggestions2 = useThread((t) => t.suggestions);\n const { welcome: { suggestions } = {} } = useThreadConfig();\n\n const finalSuggestions = suggestions2.length ? suggestions2 : suggestions;\n\n return (\n <ThreadWelcomeSuggestionContainer>\n {finalSuggestions?.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 } from \"../primitives\";\nimport Attachment from \"./attachment\";\n\nconst UserMessage: FC = () => {\n return (\n <UserMessageRoot>\n <UserMessageAttachments />\n {/* TODO this is temporary until we place the UserActionBar in a better place */}\n <MessagePrimitive.If hasContent>\n <UserActionBar />\n <UserMessageContent />\n </MessagePrimitive.If>\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\n/**\n * @deprecated Use `UserMessage.Content.Props` instead. This will be removed in 0.6.\n */\nexport type UserMessageContentProps = UserMessageContent.Props;\n\nnamespace UserMessageContent {\n export type Element = HTMLDivElement;\n export type Props = MessagePrimitive.Content.Props &\n ComponentPropsWithoutRef<\"div\">;\n}\n\nconst UserMessageContent = forwardRef<\n UserMessageContent.Element,\n UserMessageContent.Props\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\nUserMessageContent.displayName = \"UserMessageContent\";\n\nconst UserMessageAttachmentsContainer = withDefaults(\"div\", {\n className: \"aui-user-message-attachments\",\n});\n\n/**\n * @deprecated Use `UserMessage.Attachments.Props` instead. This will be removed in 0.6.\n */\nexport type UserMessageAttachmentsProps = UserMessageAttachments.Props;\n\nnamespace UserMessageAttachments {\n export type Props = Partial<MessagePrimitive.Attachments.Props>;\n}\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 ?? Attachment,\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\nnamespace UserActionBarEdit {\n export type Element = ActionBarPrimitive.Edit.Element;\n export type Props = Partial<TooltipIconButtonProps>;\n}\n\nconst UserActionBarEdit = forwardRef<\n UserActionBarEdit.Element,\n UserActionBarEdit.Props\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 { 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\nnamespace EditComposerCancel {\n export type Element = HTMLButtonElement;\n export type Props = Partial<ButtonProps>;\n}\n\nconst EditComposerCancel = forwardRef<\n EditComposerCancel.Element,\n EditComposerCancel.Props\n>((props, ref) => {\n const {\n strings: { editComposer: { cancel: { label = \"Cancel\" } = {} } = {} } = {},\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\nEditComposerCancel.displayName = \"EditComposerCancel\";\n\nnamespace EditComposerSend {\n export type Element = HTMLButtonElement;\n export type Props = Partial<ButtonProps>;\n}\n\nconst EditComposerSend = forwardRef<\n EditComposerSend.Element,\n EditComposerSend.Props\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\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"]}