@assistant-ui/core 0.2.10 → 0.2.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/attachment.d.ts.map +1 -1
- package/dist/adapters/attachment.js +22 -12
- package/dist/adapters/attachment.js.map +1 -1
- package/dist/adapters/directive-formatter.js.map +1 -1
- package/dist/adapters/speech.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/internal.js +1 -1
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/frame/provider.js.map +1 -1
- package/dist/model-context/registry.js.map +1 -1
- package/dist/model-context/types.js.map +1 -1
- package/dist/react/AssistantProvider.js +1 -1
- package/dist/react/AssistantRuntimeProvider.d.ts +1 -1
- package/dist/react/AssistantRuntimeProvider.d.ts.map +1 -1
- package/dist/react/AssistantRuntimeProvider.js +1 -1
- package/dist/react/RuntimeAdapter.js +4 -2
- package/dist/react/RuntimeAdapter.js.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
- package/dist/react/client/DataRenderers.d.ts.map +1 -1
- package/dist/react/client/DataRenderers.js +6 -5
- package/dist/react/client/DataRenderers.js.map +1 -1
- package/dist/react/client/Interactables.d.ts.map +1 -1
- package/dist/react/client/Interactables.js +30 -29
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/Tools.d.ts.map +1 -1
- package/dist/react/client/Tools.js +10 -9
- package/dist/react/client/Tools.js.map +1 -1
- package/dist/react/index.d.ts +5 -4
- package/dist/react/index.js +3 -2
- package/dist/react/model-context/define-mcp-toolkit.js.map +1 -1
- package/dist/react/model-context/define-toolkit.d.ts +9 -12
- package/dist/react/model-context/define-toolkit.d.ts.map +1 -1
- package/dist/react/model-context/define-toolkit.js +1 -1
- package/dist/react/model-context/define-toolkit.js.map +1 -1
- package/dist/react/model-context/external-tool.d.ts +14 -0
- package/dist/react/model-context/external-tool.d.ts.map +1 -0
- package/dist/react/model-context/external-tool.js +17 -0
- package/dist/react/model-context/external-tool.js.map +1 -0
- package/dist/react/model-context/human-tool.d.ts +27 -0
- package/dist/react/model-context/human-tool.d.ts.map +1 -0
- package/dist/react/model-context/human-tool.js +30 -0
- package/dist/react/model-context/human-tool.js.map +1 -0
- package/dist/react/model-context/toolbox.d.ts +3 -3
- package/dist/react/model-context/toolbox.js.map +1 -1
- package/dist/react/model-context/useAssistantContext.js +1 -1
- package/dist/react/model-context/useAssistantContext.js.map +1 -1
- package/dist/react/model-context/useAssistantDataUI.js +1 -1
- package/dist/react/model-context/useAssistantDataUI.js.map +1 -1
- package/dist/react/model-context/useAssistantInstructions.js +1 -1
- package/dist/react/model-context/useAssistantInstructions.js.map +1 -1
- package/dist/react/model-context/useAssistantInteractable.js +1 -1
- package/dist/react/model-context/useAssistantInteractable.js.map +1 -1
- package/dist/react/model-context/useAssistantTool.js +1 -1
- package/dist/react/model-context/useAssistantTool.js.map +1 -1
- package/dist/react/model-context/useAssistantToolUI.js +1 -1
- package/dist/react/model-context/useAssistantToolUI.js.map +1 -1
- package/dist/react/model-context/useAuiToolOverrides.js +1 -1
- package/dist/react/model-context/useAuiToolOverrides.js.map +1 -1
- package/dist/react/model-context/useInlineRender.js +1 -1
- package/dist/react/model-context/useInlineRender.js.map +1 -1
- package/dist/react/model-context/useInteractableState.js +1 -1
- package/dist/react/model-context/useInteractableState.js.map +1 -1
- package/dist/react/model-context/useToolArgsStatus.js +1 -1
- package/dist/react/primitive-hooks/useActionBarCopy.js +1 -1
- package/dist/react/primitive-hooks/useActionBarCopy.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarEdit.js +1 -1
- package/dist/react/primitive-hooks/useActionBarEdit.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarFeedback.js +1 -1
- package/dist/react/primitive-hooks/useActionBarFeedback.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarReload.js +1 -1
- package/dist/react/primitive-hooks/useActionBarReload.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarSpeak.js +1 -1
- package/dist/react/primitive-hooks/useActionBarSpeak.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarStopSpeaking.js +1 -1
- package/dist/react/primitive-hooks/useActionBarStopSpeaking.js.map +1 -1
- package/dist/react/primitive-hooks/useBranchPickerNext.js +1 -1
- package/dist/react/primitive-hooks/useBranchPickerNext.js.map +1 -1
- package/dist/react/primitive-hooks/useBranchPickerPrevious.js +1 -1
- package/dist/react/primitive-hooks/useBranchPickerPrevious.js.map +1 -1
- package/dist/react/primitive-hooks/useComposerAddAttachment.js +1 -1
- package/dist/react/primitive-hooks/useComposerAddAttachment.js.map +1 -1
- package/dist/react/primitive-hooks/useComposerCancel.js +1 -1
- package/dist/react/primitive-hooks/useComposerCancel.js.map +1 -1
- package/dist/react/primitive-hooks/useComposerDictate.js +1 -1
- package/dist/react/primitive-hooks/useComposerDictate.js.map +1 -1
- package/dist/react/primitive-hooks/useComposerSend.js +1 -1
- package/dist/react/primitive-hooks/useComposerSend.js.map +1 -1
- package/dist/react/primitive-hooks/useEditComposerCancel.js +1 -1
- package/dist/react/primitive-hooks/useEditComposerCancel.js.map +1 -1
- package/dist/react/primitive-hooks/useEditComposerSend.js +1 -1
- package/dist/react/primitive-hooks/useEditComposerSend.js.map +1 -1
- package/dist/react/primitive-hooks/useMessageBranching.js +1 -1
- package/dist/react/primitive-hooks/useMessageBranching.js.map +1 -1
- package/dist/react/primitive-hooks/useMessageReload.js +1 -1
- package/dist/react/primitive-hooks/useMessageReload.js.map +1 -1
- package/dist/react/primitive-hooks/useSuggestionTrigger.js +1 -1
- package/dist/react/primitive-hooks/useSuggestionTrigger.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadListItemArchive.js +1 -1
- package/dist/react/primitive-hooks/useThreadListItemArchive.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadListItemDelete.js +1 -1
- package/dist/react/primitive-hooks/useThreadListItemDelete.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadListItemTrigger.js +1 -1
- package/dist/react/primitive-hooks/useThreadListItemTrigger.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadListItemUnarchive.js +1 -1
- package/dist/react/primitive-hooks/useThreadListItemUnarchive.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadListLoadMore.js +1 -1
- package/dist/react/primitive-hooks/useThreadListLoadMore.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadListNew.js +1 -1
- package/dist/react/primitive-hooks/useThreadListNew.js.map +1 -1
- package/dist/react/primitive-hooks/useVoice.js +1 -1
- package/dist/react/primitive-hooks/useVoice.js.map +1 -1
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.d.ts +1 -1
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js +1 -1
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js.map +1 -1
- package/dist/react/primitives/composer/ComposerAttachments.js +1 -1
- package/dist/react/primitives/composer/ComposerAttachments.js.map +1 -1
- package/dist/react/primitives/composer/ComposerQueue.js +1 -1
- package/dist/react/primitives/composer/ComposerQueue.js.map +1 -1
- package/dist/react/primitives/generativeUI/GenerativeUI.js +1 -1
- package/dist/react/primitives/generativeUI/GenerativeUI.js.map +1 -1
- package/dist/react/primitives/message/MessageAttachments.js +1 -1
- package/dist/react/primitives/message/MessageAttachments.js.map +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.js +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
- package/dist/react/primitives/message/MessageParts.d.ts +1 -1
- package/dist/react/primitives/message/MessageParts.js +1 -1
- package/dist/react/primitives/message/MessageParts.js.map +1 -1
- package/dist/react/primitives/message/MessageQuote.js +1 -1
- package/dist/react/primitives/part/PartMessages.d.ts +2 -2
- package/dist/react/primitives/part/PartMessages.js +3 -3
- package/dist/react/primitives/part/PartMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.js +1 -1
- package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadSuggestions.js +1 -1
- package/dist/react/primitives/thread/ThreadSuggestions.js.map +1 -1
- package/dist/react/primitives/threadList/ThreadListItems.js +1 -1
- package/dist/react/primitives/threadList/ThreadListItems.js.map +1 -1
- package/dist/react/providers/AttachmentByIndexProvider.js.map +1 -1
- package/dist/react/providers/ChainOfThoughtByIndicesProvider.js.map +1 -1
- package/dist/react/providers/ChainOfThoughtPartByIndexProvider.js.map +1 -1
- package/dist/react/providers/MessageByIndexProvider.js.map +1 -1
- package/dist/react/providers/PartByIndexProvider.js.map +1 -1
- package/dist/react/providers/QueueItemByIndexProvider.js.map +1 -1
- package/dist/react/providers/ReadonlyThreadProvider.js +1 -1
- package/dist/react/providers/ReadonlyThreadProvider.js.map +1 -1
- package/dist/react/providers/SuggestionByIndexProvider.js.map +1 -1
- package/dist/react/providers/TextMessagePartProvider.d.ts.map +1 -1
- package/dist/react/providers/TextMessagePartProvider.js +4 -3
- package/dist/react/providers/TextMessagePartProvider.js.map +1 -1
- package/dist/react/providers/ThreadListItemByIndexProvider.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts +7 -0
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +7 -0
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/RuntimeAdapterProvider.js +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js.map +1 -1
- package/dist/react/runtimes/createMessageConverter.d.ts +2 -2
- package/dist/react/runtimes/createMessageConverter.d.ts.map +1 -1
- package/dist/react/runtimes/createMessageConverter.js.map +1 -1
- package/dist/react/runtimes/external-message-converter.d.ts +4 -3
- package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
- package/dist/react/runtimes/external-message-converter.js +1 -1
- package/dist/react/runtimes/external-message-converter.js.map +1 -1
- package/dist/react/runtimes/useExternalStoreRuntime.js +1 -1
- package/dist/react/runtimes/useExternalStoreSharedOptions.js +1 -1
- package/dist/react/runtimes/useLocalRuntime.d.ts +2 -1
- package/dist/react/runtimes/useLocalRuntime.d.ts.map +1 -1
- package/dist/react/runtimes/useLocalRuntime.js +4 -3
- package/dist/react/runtimes/useLocalRuntime.js.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
- package/dist/react/utils/groupParts.d.ts +1 -1
- package/dist/react/utils/groupParts.js.map +1 -1
- package/dist/runtime/api/attachment-runtime.js.map +1 -1
- package/dist/runtime/api/composer-runtime.d.ts +8 -2
- package/dist/runtime/api/composer-runtime.d.ts.map +1 -1
- package/dist/runtime/api/composer-runtime.js +14 -0
- package/dist/runtime/api/composer-runtime.js.map +1 -1
- package/dist/runtime/api/message-part-runtime.js.map +1 -1
- package/dist/runtime/api/message-runtime.js +1 -1
- package/dist/runtime/api/message-runtime.js.map +1 -1
- package/dist/runtime/api/thread-list-item-runtime.js.map +1 -1
- package/dist/runtime/api/thread-runtime.d.ts +7 -0
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts +4 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +7 -1
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.d.ts +4 -0
- package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.js +17 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
- package/dist/runtime/interfaces/composer-runtime-core.d.ts +6 -1
- package/dist/runtime/interfaces/composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/interfaces/thread-runtime-core.d.ts +4 -0
- package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/queue/external-thread-queue-adapter.d.ts +20 -0
- package/dist/runtime/queue/external-thread-queue-adapter.d.ts.map +1 -0
- package/dist/runtime/queue/external-thread-queue-adapter.js +0 -0
- package/dist/runtime/queue/message-queue.d.ts +20 -0
- package/dist/runtime/queue/message-queue.d.ts.map +1 -0
- package/dist/runtime/queue/message-queue.js +97 -0
- package/dist/runtime/queue/message-queue.js.map +1 -0
- package/dist/runtime/utils/message-repository.js.map +1 -1
- package/dist/runtime/utils/thread-message-like.js.map +1 -1
- package/dist/runtimes/external-store/external-store-adapter.d.ts +3 -1
- package/dist/runtimes/external-store/external-store-adapter.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-runtime-core.js.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +4 -0
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js +20 -2
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/local/local-runtime-core.js.map +1 -1
- package/dist/runtimes/local/local-runtime-options.d.ts +5 -0
- package/dist/runtimes/local/local-runtime-options.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts +7 -0
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +45 -0
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts +3 -0
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js +3 -0
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js.map +1 -1
- package/dist/runtimes/remote-thread-list/empty-thread-core.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/empty-thread-core.js +3 -0
- package/dist/runtimes/remote-thread-list/empty-thread-core.js.map +1 -1
- package/dist/runtimes/remote-thread-list/remote-thread-state.js.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
- package/dist/store/clients/chain-of-thought-client.d.ts.map +1 -1
- package/dist/store/clients/chain-of-thought-client.js +6 -5
- package/dist/store/clients/chain-of-thought-client.js.map +1 -1
- package/dist/store/clients/model-context-client.d.ts.map +1 -1
- package/dist/store/clients/model-context-client.js +6 -5
- package/dist/store/clients/model-context-client.js.map +1 -1
- package/dist/store/clients/no-op-composer-client.d.ts.map +1 -1
- package/dist/store/clients/no-op-composer-client.js +4 -3
- package/dist/store/clients/no-op-composer-client.js.map +1 -1
- package/dist/store/clients/runtime-adapter.d.ts.map +1 -1
- package/dist/store/clients/runtime-adapter.js +7 -6
- package/dist/store/clients/runtime-adapter.js.map +1 -1
- package/dist/store/clients/suggestions.d.ts.map +1 -1
- package/dist/store/clients/suggestions.js +7 -6
- package/dist/store/clients/suggestions.js.map +1 -1
- package/dist/store/clients/thread-message-client.d.ts.map +1 -1
- package/dist/store/clients/thread-message-client.js +13 -12
- package/dist/store/clients/thread-message-client.js.map +1 -1
- package/dist/store/index.d.ts +1 -1
- package/dist/store/runtime-clients/attachment-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/attachment-runtime-client.js +3 -3
- package/dist/store/runtime-clients/attachment-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.d.ts +12 -5
- package/dist/store/runtime-clients/composer-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.js +32 -16
- package/dist/store/runtime-clients/composer-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/message-part-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/message-part-runtime-client.js +3 -3
- package/dist/store/runtime-clients/message-part-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/message-runtime-client.d.ts +6 -3
- package/dist/store/runtime-clients/message-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/message-runtime-client.js +17 -16
- package/dist/store/runtime-clients/message-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js +8 -7
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-list-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-runtime-client.js +11 -10
- package/dist/store/runtime-clients/thread-list-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.js +15 -14
- package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/useSubscribable.d.ts +7 -0
- package/dist/store/runtime-clients/useSubscribable.d.ts.map +1 -0
- package/dist/store/runtime-clients/useSubscribable.js +16 -0
- package/dist/store/runtime-clients/useSubscribable.js.map +1 -0
- package/dist/store/scope-registration.d.ts +1 -1
- package/dist/store/scopes/composer.d.ts +1 -1
- package/dist/store/scopes/queue-item.d.ts +2 -1
- package/dist/store/scopes/queue-item.d.ts.map +1 -1
- package/dist/store/scopes/queue-item.js +6 -0
- package/dist/store/scopes/queue-item.js.map +1 -0
- package/dist/store/scopes/thread.d.ts +1 -1
- package/dist/store/scopes/threads.d.ts +1 -1
- package/dist/types/message.d.ts +2 -1
- package/dist/types/message.d.ts.map +1 -1
- package/dist/types/message.js.map +1 -1
- package/dist/utils/composite-context-provider.d.ts +1 -1
- package/dist/utils/composite-context-provider.js +3 -1
- package/dist/utils/composite-context-provider.js.map +1 -1
- package/dist/utils/json/is-json.js.map +1 -1
- package/dist/utils/text.js.map +1 -1
- package/package.json +14 -10
- package/src/adapters/attachment.ts +24 -4
- package/src/index.ts +8 -0
- package/src/react/RuntimeAdapter.ts +6 -4
- package/src/react/client/DataRenderers.ts +48 -42
- package/src/react/client/Interactables.ts +263 -267
- package/src/react/client/Tools.ts +122 -129
- package/src/react/index.ts +3 -1
- package/src/react/model-context/define-toolkit.test.ts +14 -7
- package/src/react/model-context/define-toolkit.ts +18 -19
- package/src/react/model-context/external-tool.ts +16 -0
- package/src/react/model-context/{hitl.ts → human-tool.ts} +13 -8
- package/src/react/model-context/toolbox.ts +3 -3
- package/src/react/primitives/message/MessageGroupedParts.tsx +1 -1
- package/src/react/primitives/part/PartMessages.tsx +2 -2
- package/src/react/providers/TextMessagePartProvider.tsx +31 -32
- package/src/react/runtimes/createMessageConverter.ts +2 -1
- package/src/react/runtimes/external-message-converter.ts +5 -3
- package/src/react/runtimes/useLocalRuntime.ts +2 -0
- package/src/runtime/api/composer-runtime.ts +26 -0
- package/src/runtime/base/base-composer-runtime-core.ts +11 -0
- package/src/runtime/base/default-thread-composer-runtime-core.ts +22 -0
- package/src/runtime/interfaces/composer-runtime-core.ts +7 -0
- package/src/runtime/interfaces/thread-runtime-core.ts +5 -0
- package/src/runtime/queue/external-thread-queue-adapter.ts +14 -0
- package/src/runtime/queue/message-queue.ts +128 -0
- package/src/runtimes/external-store/external-store-adapter.ts +3 -0
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +31 -2
- package/src/runtimes/local/local-runtime-options.ts +6 -0
- package/src/runtimes/local/local-thread-runtime-core.ts +70 -0
- package/src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts +4 -0
- package/src/runtimes/remote-thread-list/empty-thread-core.ts +4 -0
- package/src/store/clients/chain-of-thought-client.ts +24 -25
- package/src/store/clients/model-context-client.ts +22 -19
- package/src/store/clients/no-op-composer-client.ts +69 -66
- package/src/store/clients/runtime-adapter.ts +9 -6
- package/src/store/clients/suggestions.ts +41 -40
- package/src/store/clients/thread-message-client.ts +127 -132
- package/src/store/runtime-clients/attachment-runtime-client.ts +7 -3
- package/src/store/runtime-clients/composer-runtime-client.ts +142 -113
- package/src/store/runtime-clients/message-part-runtime-client.ts +16 -14
- package/src/store/runtime-clients/message-runtime-client.ts +124 -122
- package/src/store/runtime-clients/thread-list-item-runtime-client.ts +44 -45
- package/src/store/runtime-clients/thread-list-runtime-client.ts +83 -80
- package/src/store/runtime-clients/thread-runtime-client.ts +113 -119
- package/src/store/runtime-clients/{tap-subscribable.ts → useSubscribable.ts} +4 -4
- package/src/store/scopes/queue-item.ts +2 -0
- package/src/tests/attachment-adapters.test.ts +86 -0
- package/src/tests/external-store-thread-runtime-core.test.ts +125 -0
- package/src/tests/message-queue.test.ts +168 -0
- package/src/types/message.ts +2 -0
- package/src/utils/composite-context-provider.ts +3 -1
- package/dist/react/model-context/hitl.d.ts +0 -23
- package/dist/react/model-context/hitl.d.ts.map +0 -1
- package/dist/react/model-context/hitl.js +0 -26
- package/dist/react/model-context/hitl.js.map +0 -1
- package/dist/store/runtime-clients/tap-subscribable.d.ts +0 -7
- package/dist/store/runtime-clients/tap-subscribable.d.ts.map +0 -1
- package/dist/store/runtime-clients/tap-subscribable.js +0 -16
- package/dist/store/runtime-clients/tap-subscribable.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-runtime.js","names":[],"sources":["../../../src/runtime/api/message-runtime.ts"],"sourcesContent":["import type { SpeechState } from \"../interfaces/thread-runtime-core\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type {\n ToolCallMessagePartStatus,\n ThreadMessage,\n ThreadAssistantMessagePart,\n ThreadUserMessagePart,\n} from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { MessagePartStatus, RunConfig } from \"../../types/message\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n SKIP_UPDATE,\n ShallowMemoizeSubject,\n} from \"../../subscribable/subscribable\";\nimport {\n type AttachmentRuntime,\n type AttachmentState,\n MessageAttachmentRuntimeImpl,\n} from \"./attachment-runtime\";\nimport {\n type EditComposerRuntime,\n EditComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport {\n type MessagePartRuntime,\n MessagePartRuntimeImpl,\n type MessagePartState,\n} from \"./message-part-runtime\";\nimport type { MessageRuntimePath } from \"./paths\";\nimport type { ThreadRuntimeCoreBinding } from \"./thread-runtime\";\nimport type { MessageStateBinding } from \"./bindings\";\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({\n type: \"complete\",\n});\n\nexport const toMessagePartStatus = (\n message: ThreadMessage,\n partIndex: number,\n part: ThreadUserMessagePart | ThreadAssistantMessagePart,\n): ToolCallMessagePartStatus => {\n if (message.role !== \"assistant\") return COMPLETE_STATUS;\n\n if (part.type === \"tool-call\") {\n if (!part.result) {\n return message.status as ToolCallMessagePartStatus;\n } else {\n return COMPLETE_STATUS;\n }\n }\n\n const isLastPart = partIndex === Math.max(0, message.content.length - 1);\n if (message.status.type === \"requires-action\") return COMPLETE_STATUS;\n return isLastPart ? (message.status as MessagePartStatus) : COMPLETE_STATUS;\n};\n\nconst getMessagePartState = (\n message: MessageState,\n partIndex: number,\n): MessagePartState | SKIP_UPDATE => {\n const part = message.content[partIndex];\n if (!part) {\n return SKIP_UPDATE;\n }\n\n // if the message part is the same, don't update\n const status = toMessagePartStatus(message, partIndex, part);\n return Object.freeze({\n ...part,\n ...{ [symbolInnerMessage]: (part as any)[symbolInnerMessage] },\n status,\n });\n};\n\nexport type MessageState = ThreadMessage & {\n readonly parentId: string | null;\n /** The position of this message in the thread (0 for first message) */\n readonly index: number;\n readonly isLast: boolean;\n\n readonly branchNumber: number;\n readonly branchCount: number;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n};\n\nexport type { MessageStateBinding } from \"./bindings\";\n\ntype ReloadConfig = {\n runConfig?: RunConfig;\n};\n\nexport type MessageRuntime = {\n readonly path: MessageRuntimePath;\n\n readonly composer: EditComposerRuntime;\n\n getState(): MessageState;\n reload(config?: ReloadConfig): 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 getMessagePartByIndex(idx: number): MessagePartRuntime;\n getMessagePartByToolCallId(toolCallId: string): MessagePartRuntime;\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: this._getEditComposerRuntimeCore,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n () => this._threadBinding.getState().beginEdit(this._core.getState().id),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.reload = this.reload.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.getMessagePartByIndex = this.getMessagePartByIndex.bind(this);\n this.getMessagePartByToolCallId =\n this.getMessagePartByToolCallId.bind(this);\n this.getAttachmentByIndex = this.getAttachmentByIndex.bind(this);\n this.unstable_getCopyText = this.unstable_getCopyText.bind(this);\n this.speak = this.speak.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.submitFeedback = this.submitFeedback.bind(this);\n this.switchToBranch = this.switchToBranch.bind(this);\n }\n\n public readonly composer;\n\n private _getEditComposerRuntimeCore = () => {\n return this._threadBinding\n .getState()\n .getEditComposer(this._core.getState().id);\n };\n\n public getState() {\n return this._core.getState();\n }\n\n public reload(reloadConfig: ReloadConfig = {}) {\n const editComposerRuntimeCore = this._getEditComposerRuntimeCore();\n const composerRuntimeCore =\n editComposerRuntimeCore ?? this._threadBinding.getState().composer;\n const composer = editComposerRuntimeCore ?? composerRuntimeCore;\n\n const { runConfig = composer.runConfig } = reloadConfig;\n const state = this._core.getState();\n if (state.role !== \"assistant\")\n throw new Error(\"Can only reload assistant messages\");\n\n this._threadBinding.getState().startRun({\n parentId: state.parentId,\n sourceId: state.id,\n runConfig,\n });\n }\n\n public speak() {\n const state = this._core.getState();\n return this._threadBinding.getState().speak(state.id);\n }\n\n public stopSpeaking() {\n const state = this._core.getState();\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 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 (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 getMessagePartByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message part index must be >= 0\");\n return new MessagePartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}${this.path.ref}.content[${idx}]`,\n messagePartSelector: { type: \"index\", index: idx },\n },\n getState: () => {\n return getMessagePartState(this.getState(), idx);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n this._threadBinding,\n );\n }\n\n public getMessagePartByToolCallId(toolCallId: string) {\n return new MessagePartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref:\n this.path.ref +\n `${this.path.ref}.content[toolCallId=${JSON.stringify(toolCallId)}]`,\n messagePartSelector: { 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 getMessagePartState(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 source: \"message\",\n } satisfies AttachmentState & { source: \"message\" };\n },\n subscribe: (callback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AU,UAAU,EAAE;IACpE,qBAAqB;KAAE,MAAM;KAAc;IAAW;GACxD;GACA,gBAAgB;IACd,MAAM,QAAQ,KAAK,MAAM,SAAS;IAClC,MAAM,MAAM,MAAM,QAAQ,WACvB,SACC,KAAK,SAAS,eAAe,KAAK,eAAe,UACrD;IACA,IAAI,QAAQ,IAAI,OAAO;IACvB,OAAO,oBAAoB,OAAO,GAAG;GACvC;GACA,YAAY,aAAa,KAAK,MAAM,UAAU,QAAQ;EACxD,CAAC,GACD,KAAK,OACL,KAAK,cACP;CACF;CAEA,qBAA4B,KAAa;EACvC,OAAO,IAAI,6BACT,IAAI,sBAAsB;GACxB,MAAM;IACJ,GAAG,KAAK;IACR,KAAK,GAAG,KAAK,KAAK,MAAM,KAAK,KAAK,IAAI,eAAe,IAAI;IACzD,kBAAkB;IAClB,oBAAoB;KAAE,MAAM;KAAS,OAAO;IAAI;GAClD;GACA,gBAAgB;IAEd,MAAM,aADc,KAAK,SAAS,EAAE,cACH;IACjC,IAAI,CAAC,YAAY,OAAO;IAExB,OAAO;KACL,GAAG;KACH,QAAQ;IACV;GACF;GACA,YAAY,aAAa,KAAK,MAAM,UAAU,QAAQ;EACxD,CAAC,CACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"message-runtime.js","names":[],"sources":["../../../src/runtime/api/message-runtime.ts"],"sourcesContent":["import type { SpeechState } from \"../interfaces/thread-runtime-core\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type {\n ToolCallMessagePartStatus,\n ThreadMessage,\n ThreadAssistantMessagePart,\n ThreadUserMessagePart,\n} from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { MessagePartStatus, RunConfig } from \"../../types/message\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n SKIP_UPDATE,\n ShallowMemoizeSubject,\n} from \"../../subscribable/subscribable\";\nimport {\n type AttachmentRuntime,\n type AttachmentState,\n MessageAttachmentRuntimeImpl,\n} from \"./attachment-runtime\";\nimport {\n type EditComposerRuntime,\n EditComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport {\n type MessagePartRuntime,\n MessagePartRuntimeImpl,\n type MessagePartState,\n} from \"./message-part-runtime\";\nimport type { MessageRuntimePath } from \"./paths\";\nimport type { ThreadRuntimeCoreBinding } from \"./thread-runtime\";\nimport type { MessageStateBinding } from \"./bindings\";\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({\n type: \"complete\",\n});\n\nexport const toMessagePartStatus = (\n message: ThreadMessage,\n partIndex: number,\n part: ThreadUserMessagePart | ThreadAssistantMessagePart,\n): ToolCallMessagePartStatus => {\n if (message.role !== \"assistant\") return COMPLETE_STATUS;\n\n if (part.type === \"tool-call\") {\n if (!part.result) {\n return message.status as ToolCallMessagePartStatus;\n } else {\n return COMPLETE_STATUS;\n }\n }\n\n const isLastPart = partIndex === Math.max(0, message.content.length - 1);\n if (message.status.type === \"requires-action\") return COMPLETE_STATUS;\n return isLastPart ? (message.status as MessagePartStatus) : COMPLETE_STATUS;\n};\n\nconst getMessagePartState = (\n message: MessageState,\n partIndex: number,\n): MessagePartState | SKIP_UPDATE => {\n const part = message.content[partIndex];\n if (!part) {\n return SKIP_UPDATE;\n }\n\n // if the message part is the same, don't update\n const status = toMessagePartStatus(message, partIndex, part);\n return Object.freeze({\n ...part,\n ...{ [symbolInnerMessage]: (part as any)[symbolInnerMessage] },\n status,\n });\n};\n\nexport type MessageState = ThreadMessage & {\n readonly parentId: string | null;\n /** The position of this message in the thread (0 for first message) */\n readonly index: number;\n readonly isLast: boolean;\n\n readonly branchNumber: number;\n readonly branchCount: number;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n};\n\nexport type { MessageStateBinding } from \"./bindings\";\n\ntype ReloadConfig = {\n runConfig?: RunConfig;\n};\n\nexport type MessageRuntime = {\n readonly path: MessageRuntimePath;\n\n readonly composer: EditComposerRuntime;\n\n getState(): MessageState;\n reload(config?: ReloadConfig): 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 getMessagePartByIndex(idx: number): MessagePartRuntime;\n getMessagePartByToolCallId(toolCallId: string): MessagePartRuntime;\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: this._getEditComposerRuntimeCore,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n () => this._threadBinding.getState().beginEdit(this._core.getState().id),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.reload = this.reload.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.getMessagePartByIndex = this.getMessagePartByIndex.bind(this);\n this.getMessagePartByToolCallId =\n this.getMessagePartByToolCallId.bind(this);\n this.getAttachmentByIndex = this.getAttachmentByIndex.bind(this);\n this.unstable_getCopyText = this.unstable_getCopyText.bind(this);\n this.speak = this.speak.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.submitFeedback = this.submitFeedback.bind(this);\n this.switchToBranch = this.switchToBranch.bind(this);\n }\n\n public readonly composer;\n\n private _getEditComposerRuntimeCore = () => {\n return this._threadBinding\n .getState()\n .getEditComposer(this._core.getState().id);\n };\n\n public getState() {\n return this._core.getState();\n }\n\n public reload(reloadConfig: ReloadConfig = {}) {\n const editComposerRuntimeCore = this._getEditComposerRuntimeCore();\n const composerRuntimeCore =\n editComposerRuntimeCore ?? this._threadBinding.getState().composer;\n const composer = editComposerRuntimeCore ?? composerRuntimeCore;\n\n const { runConfig = composer.runConfig } = reloadConfig;\n const state = this._core.getState();\n if (state.role !== \"assistant\")\n throw new Error(\"Can only reload assistant messages\");\n\n this._threadBinding.getState().startRun({\n parentId: state.parentId,\n sourceId: state.id,\n runConfig,\n });\n }\n\n public speak() {\n const state = this._core.getState();\n return this._threadBinding.getState().speak(state.id);\n }\n\n public stopSpeaking() {\n const state = this._core.getState();\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 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 (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 getMessagePartByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message part index must be >= 0\");\n return new MessagePartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}${this.path.ref}.content[${idx}]`,\n messagePartSelector: { type: \"index\", index: idx },\n },\n getState: () => {\n return getMessagePartState(this.getState(), idx);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n this._threadBinding,\n );\n }\n\n public getMessagePartByToolCallId(toolCallId: string) {\n return new MessagePartRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n ref:\n this.path.ref +\n `${this.path.ref}.content[toolCallId=${JSON.stringify(toolCallId)}]`,\n messagePartSelector: { 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 getMessagePartState(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 source: \"message\",\n } satisfies AttachmentState & { source: \"message\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n );\n }\n}\n"],"mappings":";;;;;;;AAkCA,MAAM,kBAAqC,OAAO,OAAO,EACvD,MAAM,WACR,CAAC;AAED,MAAa,uBACX,SACA,WACA,SAC8B;CAC9B,IAAI,QAAQ,SAAS,aAAa,OAAO;CAEzC,IAAI,KAAK,SAAS,aAChB,IAAI,CAAC,KAAK,QACR,OAAO,QAAQ;MAEf,OAAO;CAIX,MAAM,aAAa,cAAc,KAAK,IAAI,GAAG,QAAQ,QAAQ,SAAS,CAA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C;GACA,YAAY,aAAa,KAAK,MAAM,UAAU,QAAQ;EACxD,CAAC,GACD,KAAK,OACL,KAAK,cACP;CACF;CAEA,qBAA4B,KAAa;EACvC,OAAO,IAAI,6BACT,IAAI,sBAAsB;GACxB,MAAM;IACJ,GAAG,KAAK;IACR,KAAK,GAAG,KAAK,KAAK,MAAM,KAAK,KAAK,IAAI,eAAe,IAAI;IACzD,kBAAkB;IAClB,oBAAoB;KAAE,MAAM;KAAS,OAAO;IAAI;GAClD;GACA,gBAAgB;IAEd,MAAM,aADc,KAAK,SAAS,CAAC,CAAC,cACH;IACjC,IAAI,CAAC,YAAY,OAAO;IAExB,OAAO;KACL,GAAG;KACH,QAAQ;IACV;GACF;GACA,YAAY,aAAa,KAAK,MAAM,UAAU,QAAQ;EACxD,CAAC,CACH;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-list-item-runtime.js","names":[],"sources":["../../../src/runtime/api/thread-list-item-runtime.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport type { ThreadListItemRuntimePath } from \"./paths\";\nimport type { ThreadListRuntimeCoreBinding } from \"./thread-list-runtime\";\n\nexport type ThreadListItemEventPayload = {\n /**\n * @deprecated State-derivable. Compare `s.threads.mainThreadId` against the\n * item's `s.threadListItem.id` via `useAuiState` instead. Kept for backward\n * compatibility.\n */\n switchedTo: Record<string, never>;\n /**\n * @deprecated State-derivable. Compare `s.threads.mainThreadId` against the\n * item's `s.threadListItem.id` via `useAuiState` instead. Kept for backward\n * compatibility.\n */\n switchedAway: Record<string, never>;\n};\n\nexport type ThreadListItemEventType = keyof ThreadListItemEventPayload;\n\nexport type ThreadListItemEventCallback<E extends ThreadListItemEventType> = (\n payload: ThreadListItemEventPayload[E],\n) => void;\n\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { ThreadListItemStatus } from \"../interfaces/thread-list-runtime-core\";\n\nexport type { ThreadListItemState, ThreadListItemStatus };\n\nexport type ThreadListItemRuntime = {\n readonly path: ThreadListItemRuntimePath;\n getState(): ThreadListItemState;\n\n initialize(): Promise<{ remoteId: string; externalId: string | undefined }>;\n generateTitle(): Promise<void>;\n\n switchTo(options?: { unarchive?: boolean }): Promise<void>;\n rename(newTitle: string): Promise<void>;\n updateCustom(custom: Record<string, unknown> | undefined): Promise<void>;\n archive(): Promise<void>;\n unarchive(): Promise<void>;\n delete(): Promise<void>;\n\n detach(): void;\n\n subscribe(callback: () => void): Unsubscribe;\n\n unstable_on<E extends ThreadListItemEventType>(\n event: E,\n callback: ThreadListItemEventCallback<E>,\n ): Unsubscribe;\n\n __internal_getRuntime(): ThreadListItemRuntime;\n};\n\nexport type ThreadListItemStateBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport class ThreadListItemRuntimeImpl implements ThreadListItemRuntime {\n public get path() {\n return this._core.path;\n }\n\n constructor(\n private _core: ThreadListItemStateBinding,\n private _threadListBinding: ThreadListRuntimeCoreBinding,\n ) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.switchTo = this.switchTo.bind(this);\n this.rename = this.rename.bind(this);\n this.updateCustom = this.updateCustom.bind(this);\n this.archive = this.archive.bind(this);\n this.unarchive = this.unarchive.bind(this);\n this.delete = this.delete.bind(this);\n this.initialize = this.initialize.bind(this);\n this.generateTitle = this.generateTitle.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getState = this.getState.bind(this);\n this.detach = this.detach.bind(this);\n }\n\n public getState(): ThreadListItemState {\n return this._core.getState();\n }\n\n public switchTo(options?: { unarchive?: boolean }): Promise<void> {\n const state = this._core.getState();\n return this._threadListBinding.switchToThread(state.id, options);\n }\n\n public rename(newTitle: string): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.rename(state.id, newTitle);\n }\n\n public updateCustom(\n custom: Record<string, unknown> | undefined,\n ): Promise<void> {\n const state = this._core.getState();\n if (!this._threadListBinding.updateCustom) {\n throw new Error(\n \"Thread list runtime does not support updating custom metadata\",\n );\n }\n\n return this._threadListBinding.updateCustom(state.id, custom);\n }\n\n public archive(): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.archive(state.id);\n }\n\n public unarchive(): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.unarchive(state.id);\n }\n\n public delete(): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.delete(state.id);\n }\n\n public initialize(): Promise<{\n remoteId: string;\n externalId: string | undefined;\n }> {\n const state = this._core.getState();\n return this._threadListBinding.initialize(state.id);\n }\n\n public generateTitle(): Promise<void> {\n const state = this._core.getState();\n return this._threadListBinding.generateTitle(state.id);\n }\n\n public unstable_on<E extends ThreadListItemEventType>(\n event: E,\n callback: ThreadListItemEventCallback<E>,\n ) {\n let prevIsMain = this._core.getState().isMain;\n let prevThreadId = this._core.getState().id;\n return this.subscribe(() => {\n const currentState = this._core.getState();\n const newIsMain = currentState.isMain;\n const newThreadId = currentState.id;\n if (prevIsMain === newIsMain && prevThreadId === newThreadId) return;\n prevIsMain = newIsMain;\n prevThreadId = newThreadId;\n\n if (event === \"switchedTo\" && !newIsMain) return;\n if (event === \"switchedAway\" && newIsMain) return;\n (callback as (payload?: unknown) => void)({});\n });\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n return this._core.subscribe(callback);\n }\n\n public detach(): void {\n const state = this._core.getState();\n\n this._threadListBinding.detach(state.id);\n }\n\n public __internal_getRuntime(): ThreadListItemRuntime {\n return this;\n }\n}\n"],"mappings":";AA8DA,IAAa,4BAAb,MAAwE;CAM5D;CACA;CANV,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM;CACpB;CAEA,YACE,OACA,oBACA;EAFQ,KAAA,QAAA;EACA,KAAA,qBAAA;EAER,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;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AChD;CAEA,aAGG;EACD,MAAM,QAAQ,KAAK,MAAM,SAAS;EAClC,OAAO,KAAK,mBAAmB,WAAW,MAAM,EAAE;CACpD;CAEA,gBAAsC;EACpC,MAAM,QAAQ,KAAK,MAAM,SAAS;EAClC,OAAO,KAAK,mBAAmB,cAAc,MAAM,EAAE;CACvD;CAEA,YACE,OACA,UACA;EACA,IAAI,aAAa,KAAK,MAAM,SAAS,
|
|
1
|
+
{"version":3,"file":"thread-list-item-runtime.js","names":[],"sources":["../../../src/runtime/api/thread-list-item-runtime.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport type { ThreadListItemRuntimePath } from \"./paths\";\nimport type { ThreadListRuntimeCoreBinding } from \"./thread-list-runtime\";\n\nexport type ThreadListItemEventPayload = {\n /**\n * @deprecated State-derivable. Compare `s.threads.mainThreadId` against the\n * item's `s.threadListItem.id` via `useAuiState` instead. Kept for backward\n * compatibility.\n */\n switchedTo: Record<string, never>;\n /**\n * @deprecated State-derivable. Compare `s.threads.mainThreadId` against the\n * item's `s.threadListItem.id` via `useAuiState` instead. Kept for backward\n * compatibility.\n */\n switchedAway: Record<string, never>;\n};\n\nexport type ThreadListItemEventType = keyof ThreadListItemEventPayload;\n\nexport type ThreadListItemEventCallback<E extends ThreadListItemEventType> = (\n payload: ThreadListItemEventPayload[E],\n) => void;\n\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { ThreadListItemStatus } from \"../interfaces/thread-list-runtime-core\";\n\nexport type { ThreadListItemState, ThreadListItemStatus };\n\nexport type ThreadListItemRuntime = {\n readonly path: ThreadListItemRuntimePath;\n getState(): ThreadListItemState;\n\n initialize(): Promise<{ remoteId: string; externalId: string | undefined }>;\n generateTitle(): Promise<void>;\n\n switchTo(options?: { unarchive?: boolean }): Promise<void>;\n rename(newTitle: string): Promise<void>;\n updateCustom(custom: Record<string, unknown> | undefined): Promise<void>;\n archive(): Promise<void>;\n unarchive(): Promise<void>;\n delete(): Promise<void>;\n\n detach(): void;\n\n subscribe(callback: () => void): Unsubscribe;\n\n unstable_on<E extends ThreadListItemEventType>(\n event: E,\n callback: ThreadListItemEventCallback<E>,\n ): Unsubscribe;\n\n __internal_getRuntime(): ThreadListItemRuntime;\n};\n\nexport type ThreadListItemStateBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport class ThreadListItemRuntimeImpl implements ThreadListItemRuntime {\n public get path() {\n return this._core.path;\n }\n\n constructor(\n private _core: ThreadListItemStateBinding,\n private _threadListBinding: ThreadListRuntimeCoreBinding,\n ) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.switchTo = this.switchTo.bind(this);\n this.rename = this.rename.bind(this);\n this.updateCustom = this.updateCustom.bind(this);\n this.archive = this.archive.bind(this);\n this.unarchive = this.unarchive.bind(this);\n this.delete = this.delete.bind(this);\n this.initialize = this.initialize.bind(this);\n this.generateTitle = this.generateTitle.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getState = this.getState.bind(this);\n this.detach = this.detach.bind(this);\n }\n\n public getState(): ThreadListItemState {\n return this._core.getState();\n }\n\n public switchTo(options?: { unarchive?: boolean }): Promise<void> {\n const state = this._core.getState();\n return this._threadListBinding.switchToThread(state.id, options);\n }\n\n public rename(newTitle: string): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.rename(state.id, newTitle);\n }\n\n public updateCustom(\n custom: Record<string, unknown> | undefined,\n ): Promise<void> {\n const state = this._core.getState();\n if (!this._threadListBinding.updateCustom) {\n throw new Error(\n \"Thread list runtime does not support updating custom metadata\",\n );\n }\n\n return this._threadListBinding.updateCustom(state.id, custom);\n }\n\n public archive(): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.archive(state.id);\n }\n\n public unarchive(): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.unarchive(state.id);\n }\n\n public delete(): Promise<void> {\n const state = this._core.getState();\n\n return this._threadListBinding.delete(state.id);\n }\n\n public initialize(): Promise<{\n remoteId: string;\n externalId: string | undefined;\n }> {\n const state = this._core.getState();\n return this._threadListBinding.initialize(state.id);\n }\n\n public generateTitle(): Promise<void> {\n const state = this._core.getState();\n return this._threadListBinding.generateTitle(state.id);\n }\n\n public unstable_on<E extends ThreadListItemEventType>(\n event: E,\n callback: ThreadListItemEventCallback<E>,\n ) {\n let prevIsMain = this._core.getState().isMain;\n let prevThreadId = this._core.getState().id;\n return this.subscribe(() => {\n const currentState = this._core.getState();\n const newIsMain = currentState.isMain;\n const newThreadId = currentState.id;\n if (prevIsMain === newIsMain && prevThreadId === newThreadId) return;\n prevIsMain = newIsMain;\n prevThreadId = newThreadId;\n\n if (event === \"switchedTo\" && !newIsMain) return;\n if (event === \"switchedAway\" && newIsMain) return;\n (callback as (payload?: unknown) => void)({});\n });\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n return this._core.subscribe(callback);\n }\n\n public detach(): void {\n const state = this._core.getState();\n\n this._threadListBinding.detach(state.id);\n }\n\n public __internal_getRuntime(): ThreadListItemRuntime {\n return this;\n }\n}\n"],"mappings":";AA8DA,IAAa,4BAAb,MAAwE;CAM5D;CACA;CANV,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM;CACpB;CAEA,YACE,OACA,oBACA;EAFQ,KAAA,QAAA;EACA,KAAA,qBAAA;EAER,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;EACvC,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,eAAe,KAAK,aAAa,KAAK,IAAI;EAC/C,KAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;EACrC,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;EACzC,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,aAAa,KAAK,WAAW,KAAK,IAAI;EAC3C,KAAK,gB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C;EACvC,IAAI,eAAe,KAAK,MAAM,SAAS,CAAC,CAAC;EACzC,OAAO,KAAK,gBAAgB;GAC1B,MAAM,eAAe,KAAK,MAAM,SAAS;GACzC,MAAM,YAAY,aAAa;GAC/B,MAAM,cAAc,aAAa;GACjC,IAAI,eAAe,aAAa,iBAAiB,aAAa;GAC9D,aAAa;GACb,eAAe;GAEf,IAAI,UAAU,gBAAgB,CAAC,WAAW;GAC1C,IAAI,UAAU,kBAAkB,WAAW;GAC3C,SAA0C,CAAC,CAAC;EAC9C,CAAC;CACH;CAEA,UAAiB,UAAmC;EAClD,OAAO,KAAK,MAAM,UAAU,QAAQ;CACtC;CAEA,SAAsB;EACpB,MAAM,QAAQ,KAAK,MAAM,SAAS;EAElC,KAAK,mBAAmB,OAAO,MAAM,EAAE;CACzC;CAEA,wBAAsD;EACpD,OAAO;CACT;AACF"}
|
|
@@ -6,6 +6,7 @@ import { ChatModelRunOptions, ChatModelRunResult } from "../utils/chat-model-ada
|
|
|
6
6
|
import { ThreadMessageLike } from "../utils/thread-message-like.js";
|
|
7
7
|
import { ExportedMessageRepository } from "../utils/message-repository.js";
|
|
8
8
|
import { QuoteInfo } from "../../types/quote.js";
|
|
9
|
+
import { QueueItemState } from "../../store/scopes/queue-item.js";
|
|
9
10
|
import { ComposerRuntimeEventCallback, ComposerRuntimeEventType, DictationState, EditComposerRuntimeCore, SendOptions } from "../interfaces/composer-runtime-core.js";
|
|
10
11
|
import { AddToolResultOptions, RespondToToolApprovalOptions, ResumeRunConfig, ResumeToolCallOptions, RuntimeCapabilities, SpeechState, StartRunConfig, SubmitFeedbackOptions, ThreadRuntimeCore, ThreadRuntimeEventCallback, ThreadRuntimeEventType, ThreadSuggestion, VoiceSessionState } from "../interfaces/thread-runtime-core.js";
|
|
11
12
|
import { ThreadListItemRuntimePath, ThreadRuntimePath } from "./paths.js";
|
|
@@ -219,6 +220,9 @@ declare class ThreadRuntimeImpl implements ThreadRuntime {
|
|
|
219
220
|
clearAttachments: () => Promise<void>;
|
|
220
221
|
send: (options?: SendOptions) => void;
|
|
221
222
|
cancel: () => void;
|
|
223
|
+
queue: readonly QueueItemState[];
|
|
224
|
+
steerQueueItem: (queueItemId: string) => void;
|
|
225
|
+
removeQueueItem: (queueItemId: string) => void;
|
|
222
226
|
dictation: DictationState | undefined;
|
|
223
227
|
startDictation: () => void;
|
|
224
228
|
stopDictation: () => void;
|
|
@@ -227,6 +231,9 @@ declare class ThreadRuntimeImpl implements ThreadRuntime {
|
|
|
227
231
|
}>;
|
|
228
232
|
getEditComposer: (messageId: string) => EditComposerRuntimeCore | undefined;
|
|
229
233
|
beginEdit: (messageId: string) => void;
|
|
234
|
+
getQueueItems?: () => readonly QueueItemState[];
|
|
235
|
+
steerQueueItem?: (queueItemId: string) => void;
|
|
236
|
+
removeQueueItem?: (queueItemId: string) => void;
|
|
230
237
|
speech: SpeechState | undefined;
|
|
231
238
|
voice: VoiceSessionState | undefined;
|
|
232
239
|
capabilities: Readonly<RuntimeCapabilities>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;KA8CY,oBAAA;EACV,QAAA;EACA,QAAA;EACA,SAAA,GAAY,SAAS;AAAA;AAAA,KAGX,qBAAA,GAAwB,oBAAA;EAClC,MAAA,IACE,OAAA,EAAS,mBAAA,KACN,cAAA,CAAe,kBAAA;AAAA;AAAA,KAoBV,mBAAA;EAGN,QAAA;EACA,QAAA;EACA,IAAA,GAAO,aAAA;EACP,OAAA,EAAS,aAAA;EACT,WAAA,GAAc,aAAA;EACd,QAAA,GAAW,aAAA;EACX,SAAA,GAAY,IAAA;EACZ,SAAA,GAAY,aAAA;EACZ,QAAA;AAAA;AAAA,KAiCM,wBAAA,GAA2B,qBAA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AA;EAsB7B,cAAA,CAAe,SAAA,WAAiB,kBAAA;EAAA,QAW/B,kBAAA;EAAA,QA2CA,0BAAA;EAKD,WAAA,WAAsB,sBAAA,EAC3B,KAAA,EAAO,CAAA,EACP,QAAA,EAAU,0BAAA,CAA2B,CAAA,IACpC,WAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.js","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n const lastMessage = runtime.messages.at(-1);\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning:\n runtime.isRunning ??\n (lastMessage?.role !== \"assistant\"\n ? false\n : lastMessage.status.type === \"running\"),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(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 connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => {\n sub1();\n sub2();\n };\n },\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}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\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 public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\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 reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(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}.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 index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${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; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n}\n"],"mappings":";;;;;AA0DA,MAAM,qBAAqB,YAAoD;CAC7E,OAAO;EACL,UAAU,QAAQ,YAAY;EAC9B,UAAU,QAAQ,YAAY;EAC9B,WAAW,QAAQ,aAAa,CAAC;EACjC,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;CACrD;AACF;AAEA,MAAM,oBAAoB,YAAkD;CAC1E,OAAO;EACL,UAAU,QAAQ,YAAY;EAC9B,UAAU,QAAQ,YAAY;EAC9B,WAAW,QAAQ,aAAa,CAAC;CACnC;AACF;AAgBA,MAAM,mBACJ,UACA,YACkB;CAClB,IAAI,OAAO,YAAY,UACrB,OAAO;EACL,2BAAW,IAAI,KAAK;EACpB,UAAU,SAAS,GAAG,EAAE,GAAG,MAAM;EACjC,UAAU;EACV,WAAW,CAAC;EACZ,MAAM;EACN,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;EACzC,aAAa,CAAC;EACd,UAAU,EAAE,QAAQ,CAAC,EAAE;CACzB;CAGF,OAAO;EACL,WAAW,QAAQ,6BAAa,IAAI,KAAK;EACzC,UAAU,QAAQ,YAAY,SAAS,GAAG,EAAE,GAAG,MAAM;EACrD,UAAU,QAAQ,YAAY;EAC9B,MAAM,QAAQ,QAAQ;EACtB,SAAS,QAAQ;EACjB,aAAa,QAAQ,eAAe,CAAC;EACrC,UAAU,QAAQ,YAAY,EAAE,QAAQ,CAAC,EAAE;EAC3C,WAAW,QAAQ,aAAa,CAAC;EACjC,UAAU,QAAQ;CACpB;AACF;AA8EA,MAAa,kBACX,SACA,wBACgB;CAChB,MAAM,cAAc,QAAQ,SAAS,GAAG,EAAE;CAC1C,OAAO,OAAO,OAAO;EACnB,UAAU,oBAAoB;EAC9B,UAAU;EACV,cAAc,QAAQ;EACtB,YAAY,QAAQ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ime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n const lastMessage = runtime.messages.at(-1);\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning:\n runtime.isRunning ??\n (lastMessage?.role !== \"assistant\"\n ? false\n : lastMessage.status.type === \"running\"),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(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 connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => {\n sub1();\n sub2();\n };\n },\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}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\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 public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\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 reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(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}.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 index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${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; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n}\n"],"mappings":";;;;;AA0DA,MAAM,qBAAqB,YAAoD;CAC7E,OAAO;EACL,UAAU,QAAQ,YAAY;EAC9B,UAAU,QAAQ,YAAY;EAC9B,WAAW,QAAQ,aAAa,CAAC;EACjC,GAAI,QAAQ,SAAS,EAA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AG,KAAK,KAAK,IAAI,sBAAsB,KAAK,UAAU,SAAS,EAAE;GACtE,iBAAiB;IAAE,MAAM;IAAwB;GAAU;EAC7D,SACM,KAAK,eAAe,SAAS,CAAC,CAAC,eAAe,SAAS,CAC/D;CACF;CAEA,mBACE,MACA,UAGA;EACA,OAAO,IAAI,mBACT,IAAI,sBAAsB;GACxB;GACA,gBAAgB;IACd,MAAM,EAAE,SAAS,UAAU,UAAU,SAAS,KAAK,CAAC;IAEpD,MAAM,EAAE,UAAU,QAAQ,gBACxB,KAAK,eAAe,SAAS;IAE/B,IAAI,CAAC,WAAW,aAAa,KAAA,KAAa,UAAU,KAAA,GAClD,OAAO;IAIT,MAAM,WAFS,KAAK,eAAe,SAEb,CAAC,CAAC,YAAY,QAAQ,EAAE;IAE9C,OAAO;KACL,GAAG;MACG,qBAAsB,QAAgB;KAE5C;KACA,QAAQ,SAAS,GAAG,EAAE,CAAC,EAAE,OAAO,QAAQ;KACxC;KAEA,cAAc,SAAS,QAAQ,QAAQ,EAAE,IAAI;KAC7C,aAAa,SAAS;KAEtB,QACE,aAAa,cAAc,QAAQ,KAAK,cAAc,KAAA;IAC1D;GACF;GACA,YAAY,aAAa,KAAK,eAAe,UAAU,QAAQ;EACjE,CAAC,GACD,KAAK,cACP;CACF;CAEA,6CAAqC,IAAI,IAGvC;CAEF,YACE,OACA,UACa;EACb,IAAI,UAAU,KAAK,2BAA2B,IAAI,KAAK;EACvD,IAAI,CAAC,SAAS;GACZ,UAAU,IAAI,yBAAiD;IAC7D;IACA,SAAS,KAAK;GAChB,CAAC;GACD,KAAK,2BAA2B,IAAI,OAAO,OAAO;EACpD;EACA,OAAO,QAAQ,UAAU,QAAuC;CAClE;AACF"}
|
|
@@ -3,6 +3,7 @@ import { Attachment, CreateAttachment } from "../../types/attachment.js";
|
|
|
3
3
|
import { AttachmentAdapter } from "../../adapters/attachment.js";
|
|
4
4
|
import { DictationAdapter } from "../../adapters/speech.js";
|
|
5
5
|
import { QuoteInfo } from "../../types/quote.js";
|
|
6
|
+
import { QueueItemState } from "../../store/scopes/queue-item.js";
|
|
6
7
|
import { ComposerRuntimeCore, ComposerRuntimeEventCallback, ComposerRuntimeEventPayload, ComposerRuntimeEventType, DictationState, SendOptions } from "../interfaces/composer-runtime-core.js";
|
|
7
8
|
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
8
9
|
|
|
@@ -36,6 +37,9 @@ declare abstract class BaseComposerRuntimeCore extends BaseSubscribable implemen
|
|
|
36
37
|
clearAttachments(): Promise<void>;
|
|
37
38
|
send(options?: SendOptions): Promise<void>;
|
|
38
39
|
cancel(): void;
|
|
40
|
+
get queue(): readonly QueueItemState[];
|
|
41
|
+
steerQueueItem(_queueItemId: string): void;
|
|
42
|
+
removeQueueItem(_queueItemId: string): void;
|
|
39
43
|
protected abstract handleSend(message: Omit<AppendMessage, "parentId" | "sourceId">, options?: SendOptions): void;
|
|
40
44
|
protected abstract handleCancel(): void;
|
|
41
45
|
addAttachment(fileOrAttachment: File | CreateAttachment): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":";;;;;;;;;;uBAkCsB,uBAAA,SACZ,gBAAA,YACG,mBAAA;EAAA,SAEK,SAAA;EAAA,mBAEG,oBAAA,IAAwB,iBAAA;EAAA,mBACxB,mBAAA,IAAuB,gBAAA;EAAA,IAE/B,gBAAA;EAAA,QAIH,YAAA;EAAA,IACG,WAAA,aAAW,UAAA;EAAA,UAIZ,cAAA,CAAe,KAAA,WAAgB,UAAA;EAAA,aAKrB,SAAA;EAAA,aACA,OAAA;EAAA,IAET,OAAA;EAAA,QAIH,KAAA;EAAA,IAEJ,IAAA;EAAA,QAII,KAAA;EAAA,IAEJ,IAAA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ccept } from "../../adapters/attachment.js";
|
|
3
|
+
import { EMPTY_QUEUE_ITEMS } from "../../store/scopes/queue-item.js";
|
|
3
4
|
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
4
5
|
//#region src/runtime/base/base-composer-runtime-core.ts
|
|
5
6
|
const isAttachmentComplete = (a) => a.status.type === "complete";
|
|
@@ -123,6 +124,11 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
123
124
|
cancel() {
|
|
124
125
|
this.handleCancel();
|
|
125
126
|
}
|
|
127
|
+
get queue() {
|
|
128
|
+
return EMPTY_QUEUE_ITEMS;
|
|
129
|
+
}
|
|
130
|
+
steerQueueItem(_queueItemId) {}
|
|
131
|
+
removeQueueItem(_queueItemId) {}
|
|
126
132
|
async addAttachment(fileOrAttachment) {
|
|
127
133
|
if (!(fileOrAttachment instanceof File)) {
|
|
128
134
|
const adapter = this.getAttachmentAdapter();
|
|
@@ -161,7 +167,7 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
161
167
|
const adapter = this.getAttachmentAdapter();
|
|
162
168
|
if (!adapter) {
|
|
163
169
|
const message = "Attachments are not supported";
|
|
164
|
-
const err = new Error(message);
|
|
170
|
+
const err = /* @__PURE__ */ new Error(message);
|
|
165
171
|
this._safeEmitAttachmentAddError("no-adapter", message, void 0, err);
|
|
166
172
|
throw err;
|
|
167
173
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-composer-runtime-core.js","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"sourcesContent":["import type {\n Attachment,\n CompleteAttachment,\n CreateAttachment,\n PendingAttachment,\n} from \"../../types/attachment\";\nimport type { MessageRole, AppendMessage } from \"../../types/message\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\nimport {\n type AttachmentAdapter,\n fileMatchesAccept,\n} from \"../../adapters/attachment\";\nimport type {\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n SendOptions,\n} from \"../interfaces/composer-runtime-core\";\nimport type { DictationAdapter } from \"../../adapters/speech\";\nimport { generateId } from \"../../utils/id\";\n\nconst isAttachmentComplete = (a: Attachment): a is CompleteAttachment =>\n a.status.type === \"complete\";\n\nexport abstract class BaseComposerRuntimeCore\n extends BaseSubscribable\n implements ComposerRuntimeCore\n{\n public readonly isEditing = true;\n\n protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n protected abstract getDictationAdapter(): DictationAdapter | undefined;\n\n public get attachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\n\n private _attachments: readonly Attachment[] = [];\n public get attachments() {\n return this._attachments;\n }\n\n protected setAttachments(value: readonly Attachment[]) {\n this._attachments = value;\n this._notifySubscribers();\n }\n\n public abstract get canCancel(): boolean;\n public abstract get canSend(): 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 private _role: MessageRole = \"user\";\n\n get role() {\n return this._role;\n }\n\n private _runConfig: RunConfig = {};\n\n get runConfig() {\n return this._runConfig;\n }\n\n private _quote: QuoteInfo | undefined = undefined;\n\n get quote() {\n return this._quote;\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n if (this._quote === quote) return;\n\n this._quote = quote;\n this._notifySubscribers();\n }\n\n public setText(value: string) {\n if (this._text === value) return;\n\n this._text = value;\n if (this._dictation) {\n this._dictationBaseText = value;\n this._currentInterimText = \"\";\n const { status, inputDisabled } = this._dictation;\n this._dictation = inputDisabled ? { status, inputDisabled } : { status };\n }\n this._notifySubscribers();\n }\n\n public setRole(role: MessageRole) {\n if (this._role === role) return;\n\n this._role = role;\n this._notifySubscribers();\n }\n\n public setRunConfig(runConfig: RunConfig) {\n if (this._runConfig === runConfig) return;\n\n this._runConfig = runConfig;\n this._notifySubscribers();\n }\n\n private _emptyTextAndAttachments() {\n this._attachments = [];\n this._text = \"\";\n this._notifySubscribers();\n }\n\n private async _onClearAttachments() {\n const adapter = this.getAttachmentAdapter();\n if (adapter) {\n const pending = this._attachments.filter((a) => !isAttachmentComplete(a));\n await Promise.all(pending.map((a) => adapter.remove(a)));\n }\n }\n\n public async reset() {\n if (\n this._attachments.length === 0 &&\n this._text === \"\" &&\n this._role === \"user\" &&\n Object.keys(this._runConfig).length === 0 &&\n this._quote === undefined\n ) {\n return;\n }\n\n this._role = \"user\";\n this._runConfig = {};\n this._quote = undefined;\n\n const task = this._onClearAttachments();\n this._emptyTextAndAttachments();\n await task;\n }\n\n public async clearAttachments() {\n const task = this._onClearAttachments();\n this.setAttachments([]);\n\n await task;\n }\n\n public async send(options?: SendOptions) {\n if (!this.canSend) return;\n\n if (this._dictationSession) {\n this._dictationSession.cancel();\n this._cleanupDictation();\n }\n\n const adapter = this.getAttachmentAdapter();\n const attachments =\n this.attachments.length > 0\n ? Promise.all(\n this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n if (!adapter) throw new Error(\"Attachments are not supported\");\n const result = await adapter.send(a);\n return result as CompleteAttachment;\n }),\n )\n : [];\n\n const text = this.text;\n const quote = this._quote;\n this._quote = undefined;\n this._emptyTextAndAttachments();\n\n const message: Omit<AppendMessage, \"parentId\" | \"sourceId\"> = {\n createdAt: new Date(),\n role: this.role,\n content: text ? [{ type: \"text\", text }] : [],\n attachments: await attachments,\n runConfig: this.runConfig,\n metadata: { custom: { ...(quote ? { quote } : {}) } },\n };\n\n this.handleSend(message, options);\n this._notifyEventSubscribers(\"send\", {});\n }\n\n public cancel() {\n this.handleCancel();\n }\n\n protected abstract handleSend(\n message: Omit<AppendMessage, \"parentId\" | \"sourceId\">,\n options?: SendOptions,\n ): void;\n protected abstract handleCancel(): void;\n\n async addAttachment(fileOrAttachment: File | CreateAttachment) {\n if (!(fileOrAttachment instanceof File)) {\n const adapter = this.getAttachmentAdapter();\n if (\n adapter &&\n !fileMatchesAccept(\n {\n name: fileOrAttachment.name,\n type: fileOrAttachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.contentType || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\n \"not-accepted\",\n message,\n undefined,\n err,\n );\n throw err;\n }\n\n const a: CompleteAttachment = {\n id: fileOrAttachment.id ?? generateId(),\n type: fileOrAttachment.type ?? \"document\",\n name: fileOrAttachment.name,\n contentType: fileOrAttachment.contentType,\n content: fileOrAttachment.content,\n status: { type: \"complete\" },\n };\n this._attachments = [...this._attachments, a];\n this._notifySubscribers();\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n return;\n }\n\n const upsertAttachment = (a: PendingAttachment) => {\n const idx = this._attachments.findIndex(\n (attachment) => attachment.id === a.id,\n );\n if (idx !== -1)\n this._attachments = [\n ...this._attachments.slice(0, idx),\n a,\n ...this._attachments.slice(idx + 1),\n ];\n else {\n this._attachments = [...this._attachments, a];\n }\n\n this._notifySubscribers();\n };\n\n const adapter = this.getAttachmentAdapter();\n if (!adapter) {\n const message = \"Attachments are not supported\";\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"no-adapter\", message, undefined, err);\n throw err;\n }\n\n if (\n !fileMatchesAccept(\n { name: fileOrAttachment.name, type: fileOrAttachment.type },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.type || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"not-accepted\", message, undefined, err);\n throw err;\n }\n\n let lastAttachment: PendingAttachment | undefined;\n try {\n const promiseOrGenerator = adapter.add({ file: fileOrAttachment });\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n lastAttachment = r;\n upsertAttachment(r);\n }\n } else {\n lastAttachment = await promiseOrGenerator;\n upsertAttachment(lastAttachment);\n }\n } catch (e) {\n if (lastAttachment) {\n upsertAttachment({\n ...lastAttachment,\n status: { type: \"incomplete\", reason: \"error\" },\n });\n }\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n e instanceof Error ? e.message : String(e),\n lastAttachment?.id,\n e instanceof Error ? e : undefined,\n );\n throw e;\n }\n\n const hasError =\n lastAttachment?.status.type === \"incomplete\" &&\n lastAttachment.status.reason === \"error\";\n if (hasError) {\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n \"Attachment upload did not complete successfully.\",\n lastAttachment?.id,\n );\n } else {\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n }\n }\n\n private _safeEmitAttachmentAddError(\n reason: AttachmentAddErrorReason,\n message: string,\n attachmentId?: string,\n error?: Error,\n ) {\n try {\n this._notifyEventSubscribers(\"attachmentAddError\", {\n reason,\n message,\n ...(attachmentId !== undefined && { attachmentId }),\n ...(error !== undefined && { error }),\n });\n } catch (subscriberError) {\n console.error(\n \"[assistant-ui] attachmentAddError subscriber threw:\",\n subscriberError,\n );\n }\n }\n\n async removeAttachment(attachmentId: string) {\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 if (!isAttachmentComplete(attachment)) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n await adapter.remove(attachment);\n }\n\n this._attachments = this._attachments.filter((a) => a.id !== attachmentId);\n this._notifySubscribers();\n }\n\n private _dictation: DictationState | undefined;\n private _dictationSession: DictationAdapter.Session | undefined;\n private _dictationUnsubscribes: Unsubscribe[] = [];\n private _dictationBaseText = \"\";\n private _currentInterimText = \"\";\n private _dictationSessionIdCounter = 0;\n private _activeDictationSessionId: number | undefined;\n private _isCleaningDictation = false;\n\n public get dictation(): DictationState | undefined {\n return this._dictation;\n }\n\n private _isActiveSession(\n sessionId: number,\n session: DictationAdapter.Session,\n ): boolean {\n return (\n this._activeDictationSessionId === sessionId &&\n this._dictationSession === session\n );\n }\n\n public startDictation(): void {\n const adapter = this.getDictationAdapter();\n if (!adapter) {\n throw new Error(\"Dictation adapter not configured\");\n }\n\n if (this._dictationSession) {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n const oldSession = this._dictationSession;\n oldSession.stop().catch(() => {});\n this._dictationSession = undefined;\n }\n\n const inputDisabled = adapter.disableInputDuringDictation ?? false;\n\n this._dictationBaseText = this._text;\n this._currentInterimText = \"\";\n\n const session = adapter.listen();\n this._dictationSession = session;\n const sessionId = ++this._dictationSessionIdCounter;\n this._activeDictationSessionId = sessionId;\n this._dictation = { status: session.status, inputDisabled };\n this._notifySubscribers();\n\n const unsubSpeech = session.onSpeech((result) => {\n if (!this._isActiveSession(sessionId, session)) return;\n const isFinal = result.isFinal !== false;\n\n const needsSeparator =\n this._dictationBaseText &&\n !this._dictationBaseText.endsWith(\" \") &&\n result.transcript;\n const separator = needsSeparator ? \" \" : \"\";\n\n if (isFinal) {\n this._dictationBaseText =\n this._dictationBaseText + separator + result.transcript;\n this._currentInterimText = \"\";\n this._text = this._dictationBaseText;\n\n if (this._dictation) {\n const { transcript: _, ...rest } = this._dictation;\n this._dictation = rest;\n }\n this._notifySubscribers();\n } else {\n this._currentInterimText = separator + result.transcript;\n this._text = this._dictationBaseText + this._currentInterimText;\n\n if (this._dictation) {\n this._dictation = {\n ...this._dictation,\n transcript: result.transcript,\n };\n }\n this._notifySubscribers();\n }\n });\n this._dictationUnsubscribes.push(unsubSpeech);\n\n const unsubStart = session.onSpeechStart(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n this._dictation = {\n status: { type: \"running\" },\n inputDisabled,\n ...(this._dictation?.transcript && {\n transcript: this._dictation.transcript,\n }),\n };\n this._notifySubscribers();\n });\n this._dictationUnsubscribes.push(unsubStart);\n\n const unsubEnd = session.onSpeechEnd(() => {\n this._cleanupDictation({ sessionId });\n });\n this._dictationUnsubscribes.push(unsubEnd);\n\n const statusInterval = setInterval(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n if (session.status.type === \"ended\") {\n this._cleanupDictation({ sessionId });\n }\n }, 100);\n this._dictationUnsubscribes.push(() => clearInterval(statusInterval));\n }\n\n public stopDictation(): void {\n if (!this._dictationSession) return;\n\n const session = this._dictationSession;\n const sessionId = this._activeDictationSessionId;\n session.stop().finally(() => {\n this._cleanupDictation({ sessionId });\n });\n }\n\n private _cleanupDictation(options?: { sessionId: number | undefined }): void {\n const isStaleSession =\n options?.sessionId !== undefined &&\n options.sessionId !== this._activeDictationSessionId;\n if (isStaleSession || this._isCleaningDictation) return;\n\n this._isCleaningDictation = true;\n try {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n this._dictationSession = undefined;\n this._activeDictationSessionId = undefined;\n this._dictation = undefined;\n this._dictationBaseText = \"\";\n this._currentInterimText = \"\";\n this._notifySubscribers();\n } finally {\n this._isCleaningDictation = false;\n }\n }\n\n private _eventSubscribers = new Map<\n ComposerRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n protected _notifyEventSubscribers<E extends ComposerRuntimeEventType>(\n event: E,\n payload: ComposerRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n for (const callback of subscribers) callback(payload);\n }\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;AA2BA,MAAM,wBAAwB,MAC5B,EAAE,OAAO,SAAS;AAEpB,IAAsB,0BAAtB,cACU,iBAEV;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C3B,IAAI,CAAC,KAAK,mBAAmB;EAE7B,MAAM,UAAU,KAAK;EACrB,MAAM,YAAY,KAAK;EACvB,QAAQ,KAAK,EAAE,cAAc;GAC3B,KAAK,kBAAkB,EAAE,UAAU,CAAC;EACtC,CAAC;CACH;CAEA,kBAA0B,SAAmD;EAI3E,IAFE,SAAS,cAAc,KAAA,KACvB,QAAQ,cAAc,KAAK,6BACP,KAAK,sBAAsB;EAEjD,KAAK,uBAAuB;EAC5B,IAAI;GACF,KAAK,MAAM,SAAS,KAAK,wBACvB,MAAM;GAER,KAAK,yBAAyB,CAAC;GAC/B,KAAK,oBAAoB,KAAA;GACzB,KAAK,4BAA4B,KAAA;GACjC,KAAK,aAAa,KAAA;GAClB,KAAK,qBAAqB;GAC1B,KAAK,sBAAsB;GAC3B,KAAK,mBAAmB;EAC1B,UAAU;GACR,KAAK,uBAAuB;EAC9B;CACF;CAEA,oCAA4B,IAAI,IAG9B;CAEF,wBACE,OACA,SACA;EACA,MAAM,cAAc,KAAK,kBAAkB,IAAI,KAAK;EACpD,IAAI,CAAC,aAAa;EAElB,KAAK,MAAM,YAAY,aAAa,SAAS,OAAO;CACtD;CAEA,YACE,OACA,UACA;EACA,MAAM,UAAU;EAChB,IAAI,cAAc,KAAK,kBAAkB,IAAI,KAAK;EAClD,IAAI,CAAC,aAAa;GAChB,8BAAc,IAAI,IAAI;GACtB,KAAK,kBAAkB,IAAI,OAAO,WAAW;EAC/C;EACA,YAAY,IAAI,OAAO;EAEvB,aAAa;GACX,KAAK,kBAAkB,IAAI,KAAK,GAAG,OAAO,OAAO;EACnD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base-composer-runtime-core.js","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"sourcesContent":["import type {\n Attachment,\n CompleteAttachment,\n CreateAttachment,\n PendingAttachment,\n} from \"../../types/attachment\";\nimport type { MessageRole, AppendMessage } from \"../../types/message\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\nimport {\n type AttachmentAdapter,\n fileMatchesAccept,\n} from \"../../adapters/attachment\";\nimport type {\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n SendOptions,\n} from \"../interfaces/composer-runtime-core\";\nimport type { DictationAdapter } from \"../../adapters/speech\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport { generateId } from \"../../utils/id\";\n\nconst isAttachmentComplete = (a: Attachment): a is CompleteAttachment =>\n a.status.type === \"complete\";\n\nexport abstract class BaseComposerRuntimeCore\n extends BaseSubscribable\n implements ComposerRuntimeCore\n{\n public readonly isEditing = true;\n\n protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n protected abstract getDictationAdapter(): DictationAdapter | undefined;\n\n public get attachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\n\n private _attachments: readonly Attachment[] = [];\n public get attachments() {\n return this._attachments;\n }\n\n protected setAttachments(value: readonly Attachment[]) {\n this._attachments = value;\n this._notifySubscribers();\n }\n\n public abstract get canCancel(): boolean;\n public abstract get canSend(): 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 private _role: MessageRole = \"user\";\n\n get role() {\n return this._role;\n }\n\n private _runConfig: RunConfig = {};\n\n get runConfig() {\n return this._runConfig;\n }\n\n private _quote: QuoteInfo | undefined = undefined;\n\n get quote() {\n return this._quote;\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n if (this._quote === quote) return;\n\n this._quote = quote;\n this._notifySubscribers();\n }\n\n public setText(value: string) {\n if (this._text === value) return;\n\n this._text = value;\n if (this._dictation) {\n this._dictationBaseText = value;\n this._currentInterimText = \"\";\n const { status, inputDisabled } = this._dictation;\n this._dictation = inputDisabled ? { status, inputDisabled } : { status };\n }\n this._notifySubscribers();\n }\n\n public setRole(role: MessageRole) {\n if (this._role === role) return;\n\n this._role = role;\n this._notifySubscribers();\n }\n\n public setRunConfig(runConfig: RunConfig) {\n if (this._runConfig === runConfig) return;\n\n this._runConfig = runConfig;\n this._notifySubscribers();\n }\n\n private _emptyTextAndAttachments() {\n this._attachments = [];\n this._text = \"\";\n this._notifySubscribers();\n }\n\n private async _onClearAttachments() {\n const adapter = this.getAttachmentAdapter();\n if (adapter) {\n const pending = this._attachments.filter((a) => !isAttachmentComplete(a));\n await Promise.all(pending.map((a) => adapter.remove(a)));\n }\n }\n\n public async reset() {\n if (\n this._attachments.length === 0 &&\n this._text === \"\" &&\n this._role === \"user\" &&\n Object.keys(this._runConfig).length === 0 &&\n this._quote === undefined\n ) {\n return;\n }\n\n this._role = \"user\";\n this._runConfig = {};\n this._quote = undefined;\n\n const task = this._onClearAttachments();\n this._emptyTextAndAttachments();\n await task;\n }\n\n public async clearAttachments() {\n const task = this._onClearAttachments();\n this.setAttachments([]);\n\n await task;\n }\n\n public async send(options?: SendOptions) {\n if (!this.canSend) return;\n\n if (this._dictationSession) {\n this._dictationSession.cancel();\n this._cleanupDictation();\n }\n\n const adapter = this.getAttachmentAdapter();\n const attachments =\n this.attachments.length > 0\n ? Promise.all(\n this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n if (!adapter) throw new Error(\"Attachments are not supported\");\n const result = await adapter.send(a);\n return result as CompleteAttachment;\n }),\n )\n : [];\n\n const text = this.text;\n const quote = this._quote;\n this._quote = undefined;\n this._emptyTextAndAttachments();\n\n const message: Omit<AppendMessage, \"parentId\" | \"sourceId\"> = {\n createdAt: new Date(),\n role: this.role,\n content: text ? [{ type: \"text\", text }] : [],\n attachments: await attachments,\n runConfig: this.runConfig,\n metadata: { custom: { ...(quote ? { quote } : {}) } },\n };\n\n this.handleSend(message, options);\n this._notifyEventSubscribers(\"send\", {});\n }\n\n public cancel() {\n this.handleCancel();\n }\n\n public get queue(): readonly QueueItemState[] {\n return EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(_queueItemId: string): void {}\n public removeQueueItem(_queueItemId: string): void {}\n\n protected abstract handleSend(\n message: Omit<AppendMessage, \"parentId\" | \"sourceId\">,\n options?: SendOptions,\n ): void;\n protected abstract handleCancel(): void;\n\n async addAttachment(fileOrAttachment: File | CreateAttachment) {\n if (!(fileOrAttachment instanceof File)) {\n const adapter = this.getAttachmentAdapter();\n if (\n adapter &&\n !fileMatchesAccept(\n {\n name: fileOrAttachment.name,\n type: fileOrAttachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.contentType || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\n \"not-accepted\",\n message,\n undefined,\n err,\n );\n throw err;\n }\n\n const a: CompleteAttachment = {\n id: fileOrAttachment.id ?? generateId(),\n type: fileOrAttachment.type ?? \"document\",\n name: fileOrAttachment.name,\n contentType: fileOrAttachment.contentType,\n content: fileOrAttachment.content,\n status: { type: \"complete\" },\n };\n this._attachments = [...this._attachments, a];\n this._notifySubscribers();\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n return;\n }\n\n const upsertAttachment = (a: PendingAttachment) => {\n const idx = this._attachments.findIndex(\n (attachment) => attachment.id === a.id,\n );\n if (idx !== -1)\n this._attachments = [\n ...this._attachments.slice(0, idx),\n a,\n ...this._attachments.slice(idx + 1),\n ];\n else {\n this._attachments = [...this._attachments, a];\n }\n\n this._notifySubscribers();\n };\n\n const adapter = this.getAttachmentAdapter();\n if (!adapter) {\n const message = \"Attachments are not supported\";\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"no-adapter\", message, undefined, err);\n throw err;\n }\n\n if (\n !fileMatchesAccept(\n { name: fileOrAttachment.name, type: fileOrAttachment.type },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.type || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"not-accepted\", message, undefined, err);\n throw err;\n }\n\n let lastAttachment: PendingAttachment | undefined;\n try {\n const promiseOrGenerator = adapter.add({ file: fileOrAttachment });\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n lastAttachment = r;\n upsertAttachment(r);\n }\n } else {\n lastAttachment = await promiseOrGenerator;\n upsertAttachment(lastAttachment);\n }\n } catch (e) {\n if (lastAttachment) {\n upsertAttachment({\n ...lastAttachment,\n status: { type: \"incomplete\", reason: \"error\" },\n });\n }\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n e instanceof Error ? e.message : String(e),\n lastAttachment?.id,\n e instanceof Error ? e : undefined,\n );\n throw e;\n }\n\n const hasError =\n lastAttachment?.status.type === \"incomplete\" &&\n lastAttachment.status.reason === \"error\";\n if (hasError) {\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n \"Attachment upload did not complete successfully.\",\n lastAttachment?.id,\n );\n } else {\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n }\n }\n\n private _safeEmitAttachmentAddError(\n reason: AttachmentAddErrorReason,\n message: string,\n attachmentId?: string,\n error?: Error,\n ) {\n try {\n this._notifyEventSubscribers(\"attachmentAddError\", {\n reason,\n message,\n ...(attachmentId !== undefined && { attachmentId }),\n ...(error !== undefined && { error }),\n });\n } catch (subscriberError) {\n console.error(\n \"[assistant-ui] attachmentAddError subscriber threw:\",\n subscriberError,\n );\n }\n }\n\n async removeAttachment(attachmentId: string) {\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 if (!isAttachmentComplete(attachment)) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n await adapter.remove(attachment);\n }\n\n this._attachments = this._attachments.filter((a) => a.id !== attachmentId);\n this._notifySubscribers();\n }\n\n private _dictation: DictationState | undefined;\n private _dictationSession: DictationAdapter.Session | undefined;\n private _dictationUnsubscribes: Unsubscribe[] = [];\n private _dictationBaseText = \"\";\n private _currentInterimText = \"\";\n private _dictationSessionIdCounter = 0;\n private _activeDictationSessionId: number | undefined;\n private _isCleaningDictation = false;\n\n public get dictation(): DictationState | undefined {\n return this._dictation;\n }\n\n private _isActiveSession(\n sessionId: number,\n session: DictationAdapter.Session,\n ): boolean {\n return (\n this._activeDictationSessionId === sessionId &&\n this._dictationSession === session\n );\n }\n\n public startDictation(): void {\n const adapter = this.getDictationAdapter();\n if (!adapter) {\n throw new Error(\"Dictation adapter not configured\");\n }\n\n if (this._dictationSession) {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n const oldSession = this._dictationSession;\n oldSession.stop().catch(() => {});\n this._dictationSession = undefined;\n }\n\n const inputDisabled = adapter.disableInputDuringDictation ?? false;\n\n this._dictationBaseText = this._text;\n this._currentInterimText = \"\";\n\n const session = adapter.listen();\n this._dictationSession = session;\n const sessionId = ++this._dictationSessionIdCounter;\n this._activeDictationSessionId = sessionId;\n this._dictation = { status: session.status, inputDisabled };\n this._notifySubscribers();\n\n const unsubSpeech = session.onSpeech((result) => {\n if (!this._isActiveSession(sessionId, session)) return;\n const isFinal = result.isFinal !== false;\n\n const needsSeparator =\n this._dictationBaseText &&\n !this._dictationBaseText.endsWith(\" \") &&\n result.transcript;\n const separator = needsSeparator ? \" \" : \"\";\n\n if (isFinal) {\n this._dictationBaseText =\n this._dictationBaseText + separator + result.transcript;\n this._currentInterimText = \"\";\n this._text = this._dictationBaseText;\n\n if (this._dictation) {\n const { transcript: _, ...rest } = this._dictation;\n this._dictation = rest;\n }\n this._notifySubscribers();\n } else {\n this._currentInterimText = separator + result.transcript;\n this._text = this._dictationBaseText + this._currentInterimText;\n\n if (this._dictation) {\n this._dictation = {\n ...this._dictation,\n transcript: result.transcript,\n };\n }\n this._notifySubscribers();\n }\n });\n this._dictationUnsubscribes.push(unsubSpeech);\n\n const unsubStart = session.onSpeechStart(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n this._dictation = {\n status: { type: \"running\" },\n inputDisabled,\n ...(this._dictation?.transcript && {\n transcript: this._dictation.transcript,\n }),\n };\n this._notifySubscribers();\n });\n this._dictationUnsubscribes.push(unsubStart);\n\n const unsubEnd = session.onSpeechEnd(() => {\n this._cleanupDictation({ sessionId });\n });\n this._dictationUnsubscribes.push(unsubEnd);\n\n const statusInterval = setInterval(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n if (session.status.type === \"ended\") {\n this._cleanupDictation({ sessionId });\n }\n }, 100);\n this._dictationUnsubscribes.push(() => clearInterval(statusInterval));\n }\n\n public stopDictation(): void {\n if (!this._dictationSession) return;\n\n const session = this._dictationSession;\n const sessionId = this._activeDictationSessionId;\n session.stop().finally(() => {\n this._cleanupDictation({ sessionId });\n });\n }\n\n private _cleanupDictation(options?: { sessionId: number | undefined }): void {\n const isStaleSession =\n options?.sessionId !== undefined &&\n options.sessionId !== this._activeDictationSessionId;\n if (isStaleSession || this._isCleaningDictation) return;\n\n this._isCleaningDictation = true;\n try {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n this._dictationSession = undefined;\n this._activeDictationSessionId = undefined;\n this._dictation = undefined;\n this._dictationBaseText = \"\";\n this._currentInterimText = \"\";\n this._notifySubscribers();\n } finally {\n this._isCleaningDictation = false;\n }\n }\n\n private _eventSubscribers = new Map<\n ComposerRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n protected _notifyEventSubscribers<E extends ComposerRuntimeEventType>(\n event: E,\n payload: ComposerRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n for (const callback of subscribers) callback(payload);\n }\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;;AA+BA,MAAM,wBAAwB,MAC5B,EAAE,OAAO,SAAS;AAEpB,IAAsB,0BAAtB,cACU,iBAEV;CACE,YAA4B;CAK5B,IAAW,mBAA2B;EACpC,OAAO,KAAK,qBAAqB,CAAC,EAAE,UAAU;CAChD;CAEA,eAA8C,CAAC;CAC/C,IAAW,cAAc;EACvB,OAAO,KAAK;CACd;CAEA,eAAyB,OAA8B;EACrD,KAAK,eAAe;EACpB,KAAK,mBAAmB;CAC1B;CAKA,IAAW,UAAU;EACnB,OAAO,CAAC,KAAK,KAAK,KAAK,KAAK,CAAC,KAAK,YAAY;CAChD;CAEA,QAAgB;CAEhB,IAAI,OAAO;EACT,OAAO,KAAK;CACd;CAEA,QAA6B;CAE7B,IAAI,OAAO;EACT,OAAO,KAAK;CACd;CAEA,aAAgC,CAAC;CAEjC,IAAI,YAAY;EACd,OAAO,KAAK;CACd;CAEA,SAAwC,KAAA;CAExC,IAAI,QAAQ;EACV,OAAO,KAAK;CACd;CAEA,SAAgB,OAA8B;EAC5C,IAAI,KAAK,WAAW,OAAO;EAE3B,KAAK,SAAS;EACd,KAAK,mBAAmB;CAC1B;CAEA,QAAe,OAAe;EAC5B,IAAI,KAAK,UAAU,OAAO;EAE1B,KAAK,QAAQ;EACb,IAAI,KAAK,YAAY;GACnB,KAAK,qBAAqB;GAC1B,KAAK,sBAAsB;GAC3B,MAAM,EAAE,QAAQ,kBAAkB,KAAK;GACvC,KAAK,aAAa,gBAAgB;IAAE;IAAQ;GAAc,IAAI,EAAE,OAAO;EACzE;EACA,KAAK,mBAAmB;CAC1B;CAEA,QAAe,MAAmB;EAChC,IAAI,KAAK,U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CAAC,aAAa;GAChB,8BAAc,IAAI,IAAI;GACtB,KAAK,kBAAkB,IAAI,OAAO,WAAW;EAC/C;EACA,YAAY,IAAI,OAAO;EAEvB,aAAa;GACX,KAAK,kBAAkB,IAAI,KAAK,CAAC,EAAE,OAAO,OAAO;EACnD;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-thread-runtime-core.js","names":[],"sources":["../../../src/runtime/base/base-thread-runtime-core.ts"],"sourcesContent":["import type {\n AppendMessage,\n ThreadAssistantMessage,\n ThreadMessage,\n} from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport { generateId } from \"../../utils/id\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/message-repository\";\nimport { DefaultThreadComposerRuntimeCore } from \"./default-thread-composer-runtime-core\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n RuntimeCapabilities,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventPayload,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport { DefaultEditComposerRuntimeCore } from \"./default-edit-composer-runtime-core\";\nimport type { SpeechSynthesisAdapter } from \"../../adapters/speech\";\nimport type { FeedbackAdapter } from \"../../adapters/feedback\";\nimport type { AttachmentAdapter } from \"../../adapters/attachment\";\nimport type { RealtimeVoiceAdapter } from \"../../adapters/voice\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\n\ntype BaseThreadAdapters = {\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n attachments?: AttachmentAdapter | undefined;\n voice?: RealtimeVoiceAdapter | undefined;\n};\n\nexport abstract class BaseThreadRuntimeCore implements ThreadRuntimeCore {\n private _subscriptions = new Set<() => void>();\n private _isInitialized = false;\n\n protected readonly repository = new MessageRepository();\n public abstract get adapters(): BaseThreadAdapters | undefined;\n public abstract get isDisabled(): boolean;\n public abstract get isSendDisabled(): boolean;\n public abstract get isLoading(): 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(config: StartRunConfig): void;\n public abstract resumeRun(config: ResumeRunConfig): void;\n public abstract addToolResult(options: AddToolResultOptions): void;\n public abstract resumeToolCall(options: ResumeToolCallOptions): void;\n public abstract respondToToolApproval(\n options: RespondToToolApprovalOptions,\n ): void;\n public abstract cancelRun(): void;\n public abstract exportExternalState(): any;\n public abstract importExternalState(state: any): void;\n\n protected _voiceMessages: ThreadMessage[] = [];\n protected _voiceGeneration = 0;\n private _cachedMergedMessages: readonly ThreadMessage[] | null = null;\n private _cachedVoiceGeneration = -1;\n private _cachedMergedBase: readonly ThreadMessage[] | null = null;\n\n protected _markVoiceMessagesDirty() {\n this._voiceGeneration++;\n this._cachedMergedMessages = null;\n }\n\n protected _getBaseMessages(): readonly ThreadMessage[] {\n return this.repository.getMessages();\n }\n\n public get messages(): readonly ThreadMessage[] {\n if (this._voiceMessages.length === 0) {\n return this._getBaseMessages();\n }\n const base = this._getBaseMessages();\n if (\n this._cachedVoiceGeneration !== this._voiceGeneration ||\n this._cachedMergedBase !== base\n ) {\n this._cachedMergedMessages = [...base, ...this._voiceMessages];\n this._cachedVoiceGeneration = this._voiceGeneration;\n this._cachedMergedBase = base;\n }\n return this._cachedMergedMessages!;\n }\n\n public get state() {\n let mostRecentAssistantMessage: (typeof this.messages)[number] | undefined;\n for (const message of this.messages) {\n if (message.role === \"assistant\") {\n mostRecentAssistantMessage = message;\n }\n }\n\n return mostRecentAssistantMessage?.metadata.unstable_state ?? null;\n }\n\n public readonly composer = new DefaultThreadComposerRuntimeCore(this);\n\n constructor(private readonly _contextProvider: ModelContextProvider) {}\n\n public getModelContext() {\n return this._contextProvider.getModelContext();\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 try {\n return this.repository.getMessage(messageId);\n } catch {\n // Check voice messages\n const baseMessages = this.repository.getMessages();\n const voiceIdx = this._voiceMessages.findIndex((m) => m.id === messageId);\n if (voiceIdx !== -1) {\n const parentId =\n voiceIdx > 0\n ? this._voiceMessages[voiceIdx - 1]!.id\n : (baseMessages.at(-1)?.id ?? null);\n return {\n parentId,\n message: this._voiceMessages[voiceIdx]!,\n index: baseMessages.length + voiceIdx,\n };\n }\n return undefined;\n }\n }\n\n public getBranches(messageId: string): string[] {\n if (this._voiceMessages.some((m) => m.id === messageId)) {\n return [];\n }\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<E extends ThreadRuntimeEventType>(\n event: E,\n payload: ThreadRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n for (const callback of subscribers) callback(payload);\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\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, parentId } = this.repository.getMessage(messageId);\n adapter.submit({ message, type });\n\n if (message.role === \"assistant\") {\n const updatedMessage: ThreadMessage = {\n ...message,\n metadata: {\n ...message.metadata,\n submittedFeedback: { type },\n },\n };\n this.repository.addOrUpdateMessage(parentId, updatedMessage);\n }\n\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 private _voiceSession: RealtimeVoiceAdapter.Session | undefined;\n private _voiceUnsubs: Array<() => void> = [];\n public voice: VoiceSessionState | undefined;\n\n private _voiceVolume = 0;\n private _voiceVolumeSubscribers = new Set<() => void>();\n\n public getVoiceVolume = () => this._voiceVolume;\n\n public subscribeVoiceVolume = (callback: () => void): Unsubscribe => {\n this._voiceVolumeSubscribers.add(callback);\n return () => this._voiceVolumeSubscribers.delete(callback);\n };\n\n public connectVoice() {\n const adapter = this.adapters?.voice;\n if (!adapter) throw new Error(\"Voice adapter not configured\");\n\n this.disconnectVoice();\n\n const session = adapter.connect({});\n this._voiceSession = session;\n const unsubs: Array<() => void> = [];\n\n let currentMode: RealtimeVoiceAdapter.Mode = \"listening\";\n\n this.voice = {\n status: session.status,\n isMuted: session.isMuted,\n mode: currentMode,\n };\n this._voiceVolume = 0;\n this._notifySubscribers();\n\n unsubs.push(\n session.onStatusChange((status) => {\n if (status.type === \"ended\") {\n this._finishVoiceAssistantMessage();\n this._voiceSession = undefined;\n this.voice = undefined;\n } else {\n this.voice = {\n status,\n isMuted: session.isMuted,\n mode: currentMode,\n };\n }\n this._notifySubscribers();\n }),\n );\n\n unsubs.push(\n session.onModeChange((mode) => {\n currentMode = mode;\n if (this.voice) {\n this.voice = { ...this.voice, mode };\n this._notifySubscribers();\n }\n }),\n );\n\n unsubs.push(\n session.onVolumeChange((volume) => {\n this._voiceVolume = volume;\n for (const cb of this._voiceVolumeSubscribers) cb();\n }),\n );\n\n unsubs.push(\n session.onTranscript((transcript) => {\n this._handleVoiceTranscript(transcript);\n }),\n );\n\n this._voiceUnsubs = unsubs;\n }\n\n private _currentAssistantMsg: ThreadAssistantMessage | null = null;\n\n private _handleVoiceTranscript(\n transcript: RealtimeVoiceAdapter.TranscriptItem,\n ) {\n this.ensureInitialized();\n\n if (transcript.role === \"user\") {\n this._finishVoiceAssistantMessage();\n this._currentAssistantMsg = null;\n\n if (transcript.isFinal) {\n this._voiceMessages.push({\n id: generateId(),\n role: \"user\",\n content: [{ type: \"text\", text: transcript.text }],\n metadata: { custom: {} },\n createdAt: new Date(),\n status: { type: \"complete\", reason: \"unknown\" },\n attachments: [],\n });\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n } else {\n if (!this._currentAssistantMsg) {\n this._currentAssistantMsg = {\n id: generateId(),\n role: \"assistant\",\n content: [{ type: \"text\", text: transcript.text }],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n status: { type: \"running\" },\n createdAt: new Date(),\n };\n this._voiceMessages.push(this._currentAssistantMsg);\n } else {\n const idx = this._voiceMessages.indexOf(this._currentAssistantMsg);\n if (idx === -1) return;\n const updated: ThreadAssistantMessage = {\n ...this._currentAssistantMsg,\n content: [{ type: \"text\", text: transcript.text }],\n ...(transcript.isFinal\n ? { status: { type: \"complete\", reason: \"stop\" } }\n : {}),\n };\n this._voiceMessages[idx] = updated;\n this._currentAssistantMsg = updated;\n }\n\n if (transcript.isFinal) {\n this._currentAssistantMsg = null;\n }\n\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n }\n\n private _finishVoiceAssistantMessage() {\n const last = this._voiceMessages.at(-1);\n if (last?.role === \"assistant\" && last.status.type === \"running\") {\n const idx = this._voiceMessages.length - 1;\n this._voiceMessages[idx] = {\n ...(last as ThreadAssistantMessage),\n status: { type: \"complete\", reason: \"stop\" },\n };\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n }\n\n public disconnectVoice() {\n this._finishVoiceAssistantMessage();\n this._currentAssistantMsg = null;\n for (const unsub of this._voiceUnsubs) unsub();\n this._voiceUnsubs = [];\n this._voiceSession?.disconnect();\n this._voiceSession = undefined;\n this.voice = undefined;\n this._voiceVolume = 0;\n for (const cb of this._voiceVolumeSubscribers) cb();\n this._voiceMessages = [];\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n\n public muteVoice() {\n if (!this._voiceSession) throw new Error(\"No active voice session\");\n this._voiceSession.mute();\n this.voice = {\n ...this.voice!,\n isMuted: true,\n };\n this._notifySubscribers();\n }\n\n public unmuteVoice() {\n if (!this._voiceSession) throw new Error(\"No active voice session\");\n this._voiceSession.unmute();\n this.voice = {\n ...this.voice!,\n isMuted: false,\n };\n this._notifySubscribers();\n }\n\n protected ensureInitialized() {\n if (!this._isInitialized) {\n this._isInitialized = true;\n this._notifyEventSubscribers(\"initialize\", {});\n }\n }\n\n public export() {\n return this.repository.export();\n }\n\n public import(data: ExportedMessageRepository) {\n this.ensureInitialized();\n this.repository.clear();\n this.repository.import(data);\n this._notifySubscribers();\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n }\n\n private _eventSubscribers = new Map<\n ThreadRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n if (event === \"modelContextUpdate\") {\n // provider.subscribe is `() => void`; pump the typed empty payload to the user callback.\n return this._contextProvider.subscribe?.(() => wrapped({})) ?? (() => {});\n }\n\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n // `initialize` latches: replay it (deferred) to subscribers that attach\n // after the thread already initialized, mirroring a BehaviorSubject.\n if (event === \"initialize\" && this._isInitialized) {\n queueMicrotask(() => {\n if (subscribers.has(wrapped)) wrapped({});\n });\n }\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;;;AA4CA,IAAsB,wBAAtB,MAAyE;CAqE1C;CApE7B,iCAAyB,IAAI,IAAgB;CAC7C,iBAAyB;CAEzB,aAAgC,IAAI,kBAAkB;CAqBtD,iBAA4C,CAAC;CAC7C,mBAA6B;CAC7B,wBAAiE;CACjE,yBAAiC;CACjC,oBAA6D;CAE7D,0BAAoC;EAClC,KAAK;EACL,KAAK,wBAAwB;CAC/B;CAEA,mBAAuD;EACrD,OAAO,KAAK,WAAW,YAAY;CACrC;CAEA,IAAW,WAAqC;EAC9C,IAAI,KAAK,eAAe,WAAW,GACjC,OAAO,KAAK,iBAAiB;EAE/B,MAAM,OAAO,KAAK,iBAAiB;EACnC,IACE,KAAK,2BAA2B,KAAK,oBACrC,KAAK,sBAAsB,MAC3B;GACA,KAAK,wBAAwB,CAAC,GAAG,MAAM,GAAG,KAAK,cAAc;GAC7D,KAAK,yBAAyB,KAAK;GACnC,KAAK,oBAAoB;EAC3B;EACA,OAAO,KAAK;CACd;CAEA,IAAW,QAAQ;EACjB,IAAI;EACJ,KAAK,MAAM,WAAW,KAAK,UACzB,IAAI,QAAQ,SAAS,aACnB,6BAA6B;EAIjC,OAA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I;EAC3B,KAAK,mBAAmB;CAC1B;CAEA,MAAa,iBAAgD;EAC3D,KAAK,OAAO,0BAA0B,UAAU,mBAAmB,CAAC,CAAC,CAAC;CACxE;CAEA,oCAA4B,IAAI,IAG9B;CAEF,YACE,OACA,UACA;EACA,MAAM,UAAU;EAChB,IAAI,UAAU,sBAEZ,OAAO,KAAK,iBAAiB,kBAAkB,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC;EAGzE,IAAI,cAAc,KAAK,kBAAkB,IAAI,KAAK;EAClD,IAAI,CAAC,aAAa;GAChB,8BAAc,IAAI,IAAI;GACtB,KAAK,kBAAkB,IAAI,OAAO,WAAW;EAC/C;EACA,YAAY,IAAI,OAAO;EAIvB,IAAI,UAAU,gBAAgB,KAAK,gBACjC,qBAAqB;GACnB,IAAI,YAAY,IAAI,OAAO,GAAG,QAAQ,CAAC,CAAC;EAC1C,CAAC;EAGH,aAAa;GACX,KAAK,kBAAkB,IAAI,KAAK,GAAG,OAAO,OAAO;EACnD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base-thread-runtime-core.js","names":[],"sources":["../../../src/runtime/base/base-thread-runtime-core.ts"],"sourcesContent":["import type {\n AppendMessage,\n ThreadAssistantMessage,\n ThreadMessage,\n} from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport { generateId } from \"../../utils/id\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../utils/message-repository\";\nimport { DefaultThreadComposerRuntimeCore } from \"./default-thread-composer-runtime-core\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n SubmitFeedbackOptions,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n RuntimeCapabilities,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventPayload,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport { DefaultEditComposerRuntimeCore } from \"./default-edit-composer-runtime-core\";\nimport type { SpeechSynthesisAdapter } from \"../../adapters/speech\";\nimport type { FeedbackAdapter } from \"../../adapters/feedback\";\nimport type { AttachmentAdapter } from \"../../adapters/attachment\";\nimport type { RealtimeVoiceAdapter } from \"../../adapters/voice\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\n\ntype BaseThreadAdapters = {\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n attachments?: AttachmentAdapter | undefined;\n voice?: RealtimeVoiceAdapter | undefined;\n};\n\nexport abstract class BaseThreadRuntimeCore implements ThreadRuntimeCore {\n private _subscriptions = new Set<() => void>();\n private _isInitialized = false;\n\n protected readonly repository = new MessageRepository();\n public abstract get adapters(): BaseThreadAdapters | undefined;\n public abstract get isDisabled(): boolean;\n public abstract get isSendDisabled(): boolean;\n public abstract get isLoading(): 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(config: StartRunConfig): void;\n public abstract resumeRun(config: ResumeRunConfig): void;\n public abstract addToolResult(options: AddToolResultOptions): void;\n public abstract resumeToolCall(options: ResumeToolCallOptions): void;\n public abstract respondToToolApproval(\n options: RespondToToolApprovalOptions,\n ): void;\n public abstract cancelRun(): void;\n public abstract exportExternalState(): any;\n public abstract importExternalState(state: any): void;\n\n protected _voiceMessages: ThreadMessage[] = [];\n protected _voiceGeneration = 0;\n private _cachedMergedMessages: readonly ThreadMessage[] | null = null;\n private _cachedVoiceGeneration = -1;\n private _cachedMergedBase: readonly ThreadMessage[] | null = null;\n\n protected _markVoiceMessagesDirty() {\n this._voiceGeneration++;\n this._cachedMergedMessages = null;\n }\n\n protected _getBaseMessages(): readonly ThreadMessage[] {\n return this.repository.getMessages();\n }\n\n public get messages(): readonly ThreadMessage[] {\n if (this._voiceMessages.length === 0) {\n return this._getBaseMessages();\n }\n const base = this._getBaseMessages();\n if (\n this._cachedVoiceGeneration !== this._voiceGeneration ||\n this._cachedMergedBase !== base\n ) {\n this._cachedMergedMessages = [...base, ...this._voiceMessages];\n this._cachedVoiceGeneration = this._voiceGeneration;\n this._cachedMergedBase = base;\n }\n return this._cachedMergedMessages!;\n }\n\n public get state() {\n let mostRecentAssistantMessage: (typeof this.messages)[number] | undefined;\n for (const message of this.messages) {\n if (message.role === \"assistant\") {\n mostRecentAssistantMessage = message;\n }\n }\n\n return mostRecentAssistantMessage?.metadata.unstable_state ?? null;\n }\n\n public readonly composer = new DefaultThreadComposerRuntimeCore(this);\n\n constructor(private readonly _contextProvider: ModelContextProvider) {}\n\n public getModelContext() {\n return this._contextProvider.getModelContext();\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 try {\n return this.repository.getMessage(messageId);\n } catch {\n // Check voice messages\n const baseMessages = this.repository.getMessages();\n const voiceIdx = this._voiceMessages.findIndex((m) => m.id === messageId);\n if (voiceIdx !== -1) {\n const parentId =\n voiceIdx > 0\n ? this._voiceMessages[voiceIdx - 1]!.id\n : (baseMessages.at(-1)?.id ?? null);\n return {\n parentId,\n message: this._voiceMessages[voiceIdx]!,\n index: baseMessages.length + voiceIdx,\n };\n }\n return undefined;\n }\n }\n\n public getBranches(messageId: string): string[] {\n if (this._voiceMessages.some((m) => m.id === messageId)) {\n return [];\n }\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<E extends ThreadRuntimeEventType>(\n event: E,\n payload: ThreadRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n for (const callback of subscribers) callback(payload);\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\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, parentId } = this.repository.getMessage(messageId);\n adapter.submit({ message, type });\n\n if (message.role === \"assistant\") {\n const updatedMessage: ThreadMessage = {\n ...message,\n metadata: {\n ...message.metadata,\n submittedFeedback: { type },\n },\n };\n this.repository.addOrUpdateMessage(parentId, updatedMessage);\n }\n\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 private _voiceSession: RealtimeVoiceAdapter.Session | undefined;\n private _voiceUnsubs: Array<() => void> = [];\n public voice: VoiceSessionState | undefined;\n\n private _voiceVolume = 0;\n private _voiceVolumeSubscribers = new Set<() => void>();\n\n public getVoiceVolume = () => this._voiceVolume;\n\n public subscribeVoiceVolume = (callback: () => void): Unsubscribe => {\n this._voiceVolumeSubscribers.add(callback);\n return () => this._voiceVolumeSubscribers.delete(callback);\n };\n\n public connectVoice() {\n const adapter = this.adapters?.voice;\n if (!adapter) throw new Error(\"Voice adapter not configured\");\n\n this.disconnectVoice();\n\n const session = adapter.connect({});\n this._voiceSession = session;\n const unsubs: Array<() => void> = [];\n\n let currentMode: RealtimeVoiceAdapter.Mode = \"listening\";\n\n this.voice = {\n status: session.status,\n isMuted: session.isMuted,\n mode: currentMode,\n };\n this._voiceVolume = 0;\n this._notifySubscribers();\n\n unsubs.push(\n session.onStatusChange((status) => {\n if (status.type === \"ended\") {\n this._finishVoiceAssistantMessage();\n this._voiceSession = undefined;\n this.voice = undefined;\n } else {\n this.voice = {\n status,\n isMuted: session.isMuted,\n mode: currentMode,\n };\n }\n this._notifySubscribers();\n }),\n );\n\n unsubs.push(\n session.onModeChange((mode) => {\n currentMode = mode;\n if (this.voice) {\n this.voice = { ...this.voice, mode };\n this._notifySubscribers();\n }\n }),\n );\n\n unsubs.push(\n session.onVolumeChange((volume) => {\n this._voiceVolume = volume;\n for (const cb of this._voiceVolumeSubscribers) cb();\n }),\n );\n\n unsubs.push(\n session.onTranscript((transcript) => {\n this._handleVoiceTranscript(transcript);\n }),\n );\n\n this._voiceUnsubs = unsubs;\n }\n\n private _currentAssistantMsg: ThreadAssistantMessage | null = null;\n\n private _handleVoiceTranscript(\n transcript: RealtimeVoiceAdapter.TranscriptItem,\n ) {\n this.ensureInitialized();\n\n if (transcript.role === \"user\") {\n this._finishVoiceAssistantMessage();\n this._currentAssistantMsg = null;\n\n if (transcript.isFinal) {\n this._voiceMessages.push({\n id: generateId(),\n role: \"user\",\n content: [{ type: \"text\", text: transcript.text }],\n metadata: { custom: {} },\n createdAt: new Date(),\n status: { type: \"complete\", reason: \"unknown\" },\n attachments: [],\n });\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n } else {\n if (!this._currentAssistantMsg) {\n this._currentAssistantMsg = {\n id: generateId(),\n role: \"assistant\",\n content: [{ type: \"text\", text: transcript.text }],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n status: { type: \"running\" },\n createdAt: new Date(),\n };\n this._voiceMessages.push(this._currentAssistantMsg);\n } else {\n const idx = this._voiceMessages.indexOf(this._currentAssistantMsg);\n if (idx === -1) return;\n const updated: ThreadAssistantMessage = {\n ...this._currentAssistantMsg,\n content: [{ type: \"text\", text: transcript.text }],\n ...(transcript.isFinal\n ? { status: { type: \"complete\", reason: \"stop\" } }\n : {}),\n };\n this._voiceMessages[idx] = updated;\n this._currentAssistantMsg = updated;\n }\n\n if (transcript.isFinal) {\n this._currentAssistantMsg = null;\n }\n\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n }\n\n private _finishVoiceAssistantMessage() {\n const last = this._voiceMessages.at(-1);\n if (last?.role === \"assistant\" && last.status.type === \"running\") {\n const idx = this._voiceMessages.length - 1;\n this._voiceMessages[idx] = {\n ...(last as ThreadAssistantMessage),\n status: { type: \"complete\", reason: \"stop\" },\n };\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n }\n\n public disconnectVoice() {\n this._finishVoiceAssistantMessage();\n this._currentAssistantMsg = null;\n for (const unsub of this._voiceUnsubs) unsub();\n this._voiceUnsubs = [];\n this._voiceSession?.disconnect();\n this._voiceSession = undefined;\n this.voice = undefined;\n this._voiceVolume = 0;\n for (const cb of this._voiceVolumeSubscribers) cb();\n this._voiceMessages = [];\n this._markVoiceMessagesDirty();\n this._notifySubscribers();\n }\n\n public muteVoice() {\n if (!this._voiceSession) throw new Error(\"No active voice session\");\n this._voiceSession.mute();\n this.voice = {\n ...this.voice!,\n isMuted: true,\n };\n this._notifySubscribers();\n }\n\n public unmuteVoice() {\n if (!this._voiceSession) throw new Error(\"No active voice session\");\n this._voiceSession.unmute();\n this.voice = {\n ...this.voice!,\n isMuted: false,\n };\n this._notifySubscribers();\n }\n\n protected ensureInitialized() {\n if (!this._isInitialized) {\n this._isInitialized = true;\n this._notifyEventSubscribers(\"initialize\", {});\n }\n }\n\n public export() {\n return this.repository.export();\n }\n\n public import(data: ExportedMessageRepository) {\n this.ensureInitialized();\n this.repository.clear();\n this.repository.import(data);\n this._notifySubscribers();\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n }\n\n private _eventSubscribers = new Map<\n ThreadRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n if (event === \"modelContextUpdate\") {\n // provider.subscribe is `() => void`; pump the typed empty payload to the user callback.\n return this._contextProvider.subscribe?.(() => wrapped({})) ?? (() => {});\n }\n\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n // `initialize` latches: replay it (deferred) to subscribers that attach\n // after the thread already initialized, mirroring a BehaviorSubject.\n if (event === \"initialize\" && this._isInitialized) {\n queueMicrotask(() => {\n if (subscribers.has(wrapped)) wrapped({});\n });\n }\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;;;AA4CA,IAAsB,wBAAtB,MAAyE;CAqE1C;CApE7B,iCAAyB,IAAI,IAAgB;CAC7C,iBAAyB;CAEzB,aAAgC,IAAI,kBAAkB;CAqBtD,iBAA4C,CAAC;CAC7C,mBAA6B;CAC7B,wBAAiE;CACjE,yBAAiC;CACjC,oBAA6D;CAE7D,0BAAoC;EAClC,KAAK;EACL,KAAK,wBAAwB;CAC/B;CAEA,mBAAuD;EACrD,OAAO,KAAK,WAAW,YAAY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;CAEA,cAAqB;EACnB,IAAI,CAAC,KAAK,eAAe,MAAM,IAAI,MAAM,yBAAyB;EAClE,KAAK,cAAc,OAAO;EAC1B,KAAK,QAAQ;GACX,GAAG,KAAK;GACR,SAAS;EACX;EACA,KAAK,mBAAmB;CAC1B;CAEA,oBAA8B;EAC5B,IAAI,CAAC,KAAK,gBAAgB;GACxB,KAAK,iBAAiB;GACtB,KAAK,wBAAwB,cAAc,CAAC,CAAC;EAC/C;CACF;CAEA,SAAgB;EACd,OAAO,KAAK,WAAW,OAAO;CAChC;CAEA,OAAc,MAAiC;EAC7C,KAAK,kBAAkB;EACvB,KAAK,WAAW,MAAM;EACtB,KAAK,WAAW,OAAO,IAAI;EAC3B,KAAK,mBAAmB;CAC1B;CAEA,MAAa,iBAAgD;EAC3D,KAAK,OAAO,0BAA0B,UAAU,mBAAmB,CAAC,CAAC,CAAC;CACxE;CAEA,oCAA4B,IAAI,IAG9B;CAEF,YACE,OACA,UACA;EACA,MAAM,UAAU;EAChB,IAAI,UAAU,sBAEZ,OAAO,KAAK,iBAAiB,kBAAkB,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC;EAGzE,IAAI,cAAc,KAAK,kBAAkB,IAAI,KAAK;EAClD,IAAI,CAAC,aAAa;GAChB,8BAAc,IAAI,IAAI;GACtB,KAAK,kBAAkB,IAAI,OAAO,WAAW;EAC/C;EACA,YAAY,IAAI,OAAO;EAIvB,IAAI,UAAU,gBAAgB,KAAK,gBACjC,qBAAqB;GACnB,IAAI,YAAY,IAAI,OAAO,GAAG,QAAQ,CAAC,CAAC;EAC1C,CAAC;EAGH,aAAa;GACX,KAAK,kBAAkB,IAAI,KAAK,CAAC,EAAE,OAAO,OAAO;EACnD;CACF;AACF"}
|
|
@@ -2,6 +2,7 @@ import { AppendMessage } from "../../types/message.js";
|
|
|
2
2
|
import { AttachmentAdapter } from "../../adapters/attachment.js";
|
|
3
3
|
import { Unsubscribe } from "../../types/unsubscribe.js";
|
|
4
4
|
import { DictationAdapter } from "../../adapters/speech.js";
|
|
5
|
+
import { QueueItemState } from "../../store/scopes/queue-item.js";
|
|
5
6
|
import { SendOptions, ThreadComposerRuntimeCore } from "../interfaces/composer-runtime-core.js";
|
|
6
7
|
import { ThreadRuntimeCore } from "../interfaces/thread-runtime-core.js";
|
|
7
8
|
import { BaseComposerRuntimeCore } from "./base-composer-runtime-core.js";
|
|
@@ -11,6 +12,9 @@ declare class DefaultThreadComposerRuntimeCore extends BaseComposerRuntimeCore i
|
|
|
11
12
|
private _canCancel;
|
|
12
13
|
get canCancel(): boolean;
|
|
13
14
|
get canSend(): boolean;
|
|
15
|
+
get queue(): readonly QueueItemState[];
|
|
16
|
+
steerQueueItem(queueItemId: string): void;
|
|
17
|
+
removeQueueItem(queueItemId: string): void;
|
|
14
18
|
protected getAttachmentAdapter(): AttachmentAdapter | undefined;
|
|
15
19
|
protected getDictationAdapter(): DictationAdapter | undefined;
|
|
16
20
|
constructor(runtime: Omit<ThreadRuntimeCore, "composer"> & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-thread-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/default-thread-composer-runtime-core.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"default-thread-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/default-thread-composer-runtime-core.ts"],"mappings":";;;;;;;;;cAca,gCAAA,SACH,uBAAA,YACG,yBAAA;EAAA,QAgCD,OAAA;EAAA,QA9BF,UAAA;EAAA,IACG,SAAA;EAAA,IAIA,OAAA;EAAA,IAIS,KAAA,aAAkB,cAAA;EAItB,cAAA,CAAe,WAAA;EAIf,eAAA,CAAgB,WAAA;EAAA,UAItB,oBAAA,IAAoB,iBAAA;EAAA,UAIpB,mBAAA,IAAmB,gBAAA;cAKnB,OAAA,EAAS,IAAA,CAAK,iBAAA;IACpB,QAAA;MAEM,WAAA,GAAc,iBAAA;MACd,SAAA,GAAY,gBAAA;IAAA;EAAA;EASf,OAAA,IAT+B,WAAA;EA8BzB,UAAA,CACX,OAAA,EAAS,IAAA,CAAK,aAAA,4BACd,OAAA,GAAU,WAAA,GAAW,OAAA;EAWV,YAAA,IAAY,OAAA;AAAA"}
|