@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":"external-message-converter.js","names":["unsupportedRole"],"sources":["../../../src/react/runtimes/external-message-converter.ts"],"sourcesContent":["\"use client\";\n\nimport { useMemo } from \"react\";\nimport { ThreadMessageConverter } from \"../../runtimes/external-store/thread-message-converter\";\nimport {\n getExternalStoreMessages,\n symbolInnerMessage,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport type { ToolExecutionStatus } from \"../../runtimes/tool-invocations/ToolInvocationTracker\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { generateErrorMessageId } from \"../../utils/id\";\nimport type {\n ThreadAssistantMessage,\n ThreadMessage,\n ToolCallMessagePart,\n} from \"../../types/message\";\nimport type { MessageTiming } from \"../../types/message\";\n\ntype ThreadMessageLikeContentItem = Exclude<\n ThreadMessageLike[\"content\"],\n string\n>[number];\n\nconst isPendingToolCall = (c: ThreadMessageLikeContentItem): boolean =>\n c.type === \"tool-call\" && c.result === undefined;\n\nconst isInterruptedToolCall = (c: ThreadMessageLikeContentItem): boolean => {\n if (c.type !== \"tool-call\" || c.result !== undefined) return false;\n return (\n c.interrupt != null ||\n (c.approval != null && c.approval.approved === undefined)\n );\n};\n\nexport namespace useExternalMessageConverter {\n export type Message =\n | (ThreadMessageLike & {\n readonly convertConfig?: {\n readonly joinStrategy?: \"concat-content\" | \"none\";\n };\n })\n | {\n role: \"tool\";\n toolCallId: string;\n toolName?: string | undefined;\n result: any;\n artifact?: any;\n isError?: boolean;\n messages?: readonly ThreadMessage[];\n };\n\n export type Metadata = {\n readonly toolStatuses?: Record<string, ToolExecutionStatus>;\n readonly error?: ReadonlyJSONValue;\n readonly messageTiming?: Record<string, MessageTiming>;\n };\n\n export type Callback<T> = (\n message: T,\n metadata: Metadata,\n ) => Message | Message[];\n}\n\ntype CallbackResult<T> = {\n input: T;\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype ChunkResult<T> = {\n inputs: T[];\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\nconst mergeInnerMessages = (existing: object, incoming: object) => ({\n [symbolInnerMessage]: [\n ...((existing as any)[symbolInnerMessage] ?? []),\n ...((incoming as any)[symbolInnerMessage] ?? []),\n ],\n});\n\nconst joinExternalMessages = (\n messages: readonly useExternalMessageConverter.Message[],\n): ThreadMessageLike => {\n const assistantMessage: Mutable<Omit<ThreadMessageLike, \"metadata\">> & {\n content: Exclude<ThreadMessageLike[\"content\"][0], string>[];\n metadata?: Mutable<ThreadMessageLike[\"metadata\"]>;\n } = {\n role: \"assistant\",\n content: [],\n };\n for (const output of messages) {\n if (output.role === \"tool\") {\n const toolCallIdx = assistantMessage.content.findIndex(\n (c) => c.type === \"tool-call\" && c.toolCallId === output.toolCallId,\n );\n // Ignore orphaned tool results so one bad tool message does not\n // prevent rendering the rest of the conversation.\n if (toolCallIdx !== -1) {\n const toolCall = assistantMessage.content[\n toolCallIdx\n ]! as ToolCallMessagePart;\n if (output.toolName !== undefined) {\n if (toolCall.toolName !== output.toolName)\n throw new Error(\n `Tool call name ${output.toolCallId} ${output.toolName} does not match existing tool call ${toolCall.toolName}`,\n );\n }\n assistantMessage.content[toolCallIdx] = {\n ...toolCall,\n ...{\n [symbolInnerMessage]: [\n ...((toolCall as any)[symbolInnerMessage] ?? []),\n output,\n ],\n },\n result: output.result,\n artifact: output.artifact,\n isError: output.isError,\n messages: output.messages,\n };\n }\n } else {\n const role = output.role;\n const content = (\n typeof output.content === \"string\"\n ? [{ type: \"text\" as const, text: output.content }]\n : output.content\n ).map((c) => ({\n ...c,\n ...{ [symbolInnerMessage]: [output] },\n }));\n switch (role) {\n case \"system\":\n case \"user\":\n return {\n ...output,\n content,\n };\n case \"assistant\":\n if (assistantMessage.content.length === 0) {\n assistantMessage.id = output.id;\n assistantMessage.createdAt ??= output.createdAt;\n assistantMessage.status ??= output.status;\n\n if (output.attachments) {\n assistantMessage.attachments = [\n ...(assistantMessage.attachments ?? []),\n ...output.attachments,\n ];\n }\n\n if (output.metadata) {\n assistantMessage.metadata ??= {};\n if (output.metadata.unstable_state) {\n assistantMessage.metadata.unstable_state =\n output.metadata.unstable_state;\n }\n if (output.metadata.unstable_annotations) {\n assistantMessage.metadata.unstable_annotations = [\n ...(assistantMessage.metadata.unstable_annotations ?? []),\n ...output.metadata.unstable_annotations,\n ];\n }\n if (output.metadata.unstable_data) {\n assistantMessage.metadata.unstable_data = [\n ...(assistantMessage.metadata.unstable_data ?? []),\n ...output.metadata.unstable_data,\n ];\n }\n if (output.metadata.steps) {\n assistantMessage.metadata.steps = [\n ...(assistantMessage.metadata.steps ?? []),\n ...output.metadata.steps,\n ];\n }\n if (output.metadata.custom) {\n assistantMessage.metadata.custom = {\n ...(assistantMessage.metadata.custom ?? {}),\n ...output.metadata.custom,\n };\n }\n\n if (output.metadata.timing) {\n assistantMessage.metadata.timing = output.metadata.timing;\n }\n\n if (output.metadata.submittedFeedback) {\n assistantMessage.metadata.submittedFeedback =\n output.metadata.submittedFeedback;\n }\n\n if (output.metadata.isOptimistic) {\n assistantMessage.metadata.isOptimistic = true;\n }\n }\n // TODO keep this in sync\n }\n\n // Add content parts, merging reasoning parts with same parentId\n for (const part of content) {\n if (part.type === \"tool-call\") {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"tool-call\" && c.toolCallId === part.toolCallId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n ...part,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n\n if (\n part.type === \"reasoning\" &&\n \"parentId\" in part &&\n part.parentId\n ) {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"reasoning\" &&\n \"parentId\" in c &&\n c.parentId === part.parentId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n text: `${existing.text}\\n\\n${part.text}`,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n assistantMessage.content.push(part);\n }\n break;\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n }\n }\n return assistantMessage;\n};\n\nconst chunkExternalMessages = <T>(\n callbackResults: CallbackResult<T>[],\n joinStrategy?: \"concat-content\" | \"none\",\n) => {\n const results: ChunkResult<T>[] = [];\n let isAssistant = false;\n let pendingNone = false; // true if the previous assistant message had joinStrategy \"none\"\n let inputs: T[] = [];\n let outputs: useExternalMessageConverter.Message[] = [];\n\n const flush = () => {\n if (outputs.length) {\n results.push({\n inputs,\n outputs,\n });\n }\n inputs = [];\n outputs = [];\n isAssistant = false;\n pendingNone = false;\n };\n\n for (const callbackResult of callbackResults) {\n for (const output of callbackResult.outputs) {\n if (\n (pendingNone && output.role !== \"tool\") ||\n !isAssistant ||\n output.role === \"user\" ||\n output.role === \"system\"\n ) {\n flush();\n }\n isAssistant = output.role === \"assistant\" || output.role === \"tool\";\n\n if (inputs.at(-1) !== callbackResult.input) {\n inputs.push(callbackResult.input);\n }\n outputs.push(output);\n\n if (\n output.role === \"assistant\" &&\n (output.convertConfig?.joinStrategy === \"none\" ||\n joinStrategy === \"none\")\n ) {\n pendingNone = true;\n }\n }\n }\n flush();\n return results;\n};\n\nfunction createErrorAssistantMessage(\n error: ReadonlyJSONValue,\n): ThreadAssistantMessage {\n const msg: ThreadAssistantMessage = {\n id: generateErrorMessageId(),\n role: \"assistant\",\n content: [],\n status: { type: \"incomplete\", reason: \"error\", error },\n createdAt: new Date(),\n metadata: {\n unstable_state: null,\n unstable_annotations: [],\n unstable_data: [],\n custom: {},\n steps: [],\n },\n };\n bindExternalStoreMessage(msg, []);\n return msg;\n}\n\nexport const convertExternalMessages = <T extends WeakKey>(\n messages: T[],\n callback: useExternalMessageConverter.Callback<T>,\n isRunning: boolean,\n metadata: useExternalMessageConverter.Metadata,\n) => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n const output = callback(message, metadata);\n const outputs = Array.isArray(output) ? output : [output];\n const result = { input: message, outputs };\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults);\n\n const result = chunks.map((message, idx) => {\n const isLast = idx === chunks.length - 1;\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? metadata.error : undefined,\n );\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n });\n\n if (metadata.error) {\n const lastMessage = result.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n result.push(createErrorAssistantMessage(metadata.error));\n }\n }\n\n return result;\n};\n\nexport const useExternalMessageConverter = <T extends WeakKey>({\n callback,\n messages,\n isRunning,\n joinStrategy,\n metadata,\n}: {\n callback: useExternalMessageConverter.Callback<T>;\n messages: T[];\n isRunning: boolean;\n joinStrategy?: \"concat-content\" | \"none\" | undefined;\n metadata?: useExternalMessageConverter.Metadata | undefined;\n}) => {\n const state = useMemo(\n () => ({\n metadata: metadata ?? {},\n callback,\n callbackCache: new WeakMap<T, CallbackResult<T>>(),\n chunkCache: new WeakMap<\n useExternalMessageConverter.Message,\n ChunkResult<T>\n >(),\n converterCache: new ThreadMessageConverter(),\n }),\n [callback, metadata],\n );\n\n return useMemo(() => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n let result = state.callbackCache.get(message);\n if (!result) {\n const output = state.callback(message, state.metadata);\n const outputs = Array.isArray(output) ? output : [output];\n result = { input: message, outputs };\n state.callbackCache.set(message, result);\n }\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults, joinStrategy).map(\n (m) => {\n const key = m.outputs[0];\n if (!key) return m;\n\n const cached = state.chunkCache.get(key);\n if (cached && shallowArrayEqual(cached.outputs, m.outputs))\n return cached;\n state.chunkCache.set(key, m);\n return m;\n },\n );\n\n const threadMessages = state.converterCache.convertMessages(\n chunks,\n (cache, message, idx) => {\n const isLast = idx === chunks.length - 1;\n\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? state.metadata.error : undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n ) {\n const inputs = getExternalStoreMessages<T>(cache);\n if (shallowArrayEqual(inputs, message.inputs)) {\n return cache;\n }\n }\n\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n },\n );\n\n bindExternalStoreMessage(threadMessages, messages);\n\n if (state.metadata.error) {\n const lastMessage = threadMessages.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n threadMessages.push(createErrorAssistantMessage(state.metadata.error));\n }\n }\n\n return threadMessages;\n }, [state, messages, isRunning, joinStrategy]);\n};\n\nconst shallowArrayEqual = (a: unknown[], b: unknown[]) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n};\n"],"mappings":";;;;;;;;AA6BA,MAAM,qBAAqB,MACzB,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA;AAEzC,MAAM,yBAAyB,MAA6C;CAC1E,IAAI,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA,GAAW,OAAO;CAC7D,OACE,EAAE,aAAa,QACd,EAAE,YAAY,Q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O;EACT,CACF;EAEA,yBAAyB,gBAAgB,QAAQ;EAEjD,IAAI,MAAM,SAAS,OAAO;GACxB,MAAM,cAAc,eAAe,GAAG,EAAE;GACxC,IAAI,CAAC,eAAe,YAAY,SAAS,aACvC,eAAe,KAAK,4BAA4B,MAAM,SAAS,KAAK,CAAC;EAEzE;EAEA,OAAO;CACT,GAAG;EAAC;EAAO;EAAU;EAAW;CAAY,CAAC;AAC/C;AAEA,MAAM,qBAAqB,GAAc,MAAiB;CACxD,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,IAAI,EAAE,OAAO,EAAE,IAAI,OAAO;CAE5B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"external-message-converter.js","names":["unsupportedRole"],"sources":["../../../src/react/runtimes/external-message-converter.ts"],"sourcesContent":["\"use client\";\n\nimport { useMemo } from \"react\";\nimport { ThreadMessageConverter } from \"../../runtimes/external-store/thread-message-converter\";\nimport {\n getExternalStoreMessages,\n symbolInnerMessage,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport type { ToolExecutionStatus } from \"../../runtimes/tool-invocations/ToolInvocationTracker\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { generateErrorMessageId } from \"../../utils/id\";\nimport type {\n ThreadAssistantMessage,\n ThreadMessage,\n ToolCallMessagePart,\n} from \"../../types/message\";\nimport type { MessageTiming } from \"../../types/message\";\n\nexport type JoinStrategy = \"concat-content\" | \"none\";\n\ntype ThreadMessageLikeContentItem = Exclude<\n ThreadMessageLike[\"content\"],\n string\n>[number];\n\nconst isPendingToolCall = (c: ThreadMessageLikeContentItem): boolean =>\n c.type === \"tool-call\" && c.result === undefined;\n\nconst isInterruptedToolCall = (c: ThreadMessageLikeContentItem): boolean => {\n if (c.type !== \"tool-call\" || c.result !== undefined) return false;\n return (\n c.interrupt != null ||\n (c.approval != null && c.approval.approved === undefined)\n );\n};\n\nexport namespace useExternalMessageConverter {\n export type Message =\n | (ThreadMessageLike & {\n readonly convertConfig?: {\n readonly joinStrategy?: JoinStrategy;\n };\n })\n | {\n role: \"tool\";\n toolCallId: string;\n toolName?: string | undefined;\n result: any;\n artifact?: any;\n isError?: boolean;\n messages?: readonly ThreadMessage[];\n };\n\n export type Metadata = {\n readonly toolStatuses?: Record<string, ToolExecutionStatus>;\n readonly error?: ReadonlyJSONValue;\n readonly messageTiming?: Record<string, MessageTiming>;\n };\n\n export type Callback<T> = (\n message: T,\n metadata: Metadata,\n ) => Message | Message[];\n}\n\ntype CallbackResult<T> = {\n input: T;\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype ChunkResult<T> = {\n inputs: T[];\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\nconst mergeInnerMessages = (existing: object, incoming: object) => ({\n [symbolInnerMessage]: [\n ...((existing as any)[symbolInnerMessage] ?? []),\n ...((incoming as any)[symbolInnerMessage] ?? []),\n ],\n});\n\nconst joinExternalMessages = (\n messages: readonly useExternalMessageConverter.Message[],\n): ThreadMessageLike => {\n const assistantMessage: Mutable<Omit<ThreadMessageLike, \"metadata\">> & {\n content: Exclude<ThreadMessageLike[\"content\"][0], string>[];\n metadata?: Mutable<ThreadMessageLike[\"metadata\"]>;\n } = {\n role: \"assistant\",\n content: [],\n };\n for (const output of messages) {\n if (output.role === \"tool\") {\n const toolCallIdx = assistantMessage.content.findIndex(\n (c) => c.type === \"tool-call\" && c.toolCallId === output.toolCallId,\n );\n // Ignore orphaned tool results so one bad tool message does not\n // prevent rendering the rest of the conversation.\n if (toolCallIdx !== -1) {\n const toolCall = assistantMessage.content[\n toolCallIdx\n ]! as ToolCallMessagePart;\n if (output.toolName !== undefined) {\n if (toolCall.toolName !== output.toolName)\n throw new Error(\n `Tool call name ${output.toolCallId} ${output.toolName} does not match existing tool call ${toolCall.toolName}`,\n );\n }\n assistantMessage.content[toolCallIdx] = {\n ...toolCall,\n ...{\n [symbolInnerMessage]: [\n ...((toolCall as any)[symbolInnerMessage] ?? []),\n output,\n ],\n },\n result: output.result,\n artifact: output.artifact,\n isError: output.isError,\n messages: output.messages,\n };\n }\n } else {\n const role = output.role;\n const content = (\n typeof output.content === \"string\"\n ? [{ type: \"text\" as const, text: output.content }]\n : output.content\n ).map((c) => ({\n ...c,\n ...{ [symbolInnerMessage]: [output] },\n }));\n switch (role) {\n case \"system\":\n case \"user\":\n return {\n ...output,\n content,\n };\n case \"assistant\":\n if (assistantMessage.content.length === 0) {\n assistantMessage.id = output.id;\n assistantMessage.createdAt ??= output.createdAt;\n assistantMessage.status ??= output.status;\n\n if (output.attachments) {\n assistantMessage.attachments = [\n ...(assistantMessage.attachments ?? []),\n ...output.attachments,\n ];\n }\n\n if (output.metadata) {\n assistantMessage.metadata ??= {};\n if (output.metadata.unstable_state) {\n assistantMessage.metadata.unstable_state =\n output.metadata.unstable_state;\n }\n if (output.metadata.unstable_annotations) {\n assistantMessage.metadata.unstable_annotations = [\n ...(assistantMessage.metadata.unstable_annotations ?? []),\n ...output.metadata.unstable_annotations,\n ];\n }\n if (output.metadata.unstable_data) {\n assistantMessage.metadata.unstable_data = [\n ...(assistantMessage.metadata.unstable_data ?? []),\n ...output.metadata.unstable_data,\n ];\n }\n if (output.metadata.steps) {\n assistantMessage.metadata.steps = [\n ...(assistantMessage.metadata.steps ?? []),\n ...output.metadata.steps,\n ];\n }\n if (output.metadata.custom) {\n assistantMessage.metadata.custom = {\n ...(assistantMessage.metadata.custom ?? {}),\n ...output.metadata.custom,\n };\n }\n\n if (output.metadata.timing) {\n assistantMessage.metadata.timing = output.metadata.timing;\n }\n\n if (output.metadata.submittedFeedback) {\n assistantMessage.metadata.submittedFeedback =\n output.metadata.submittedFeedback;\n }\n\n if (output.metadata.isOptimistic) {\n assistantMessage.metadata.isOptimistic = true;\n }\n }\n // TODO keep this in sync\n }\n\n // Add content parts, merging reasoning parts with same parentId\n for (const part of content) {\n if (part.type === \"tool-call\") {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"tool-call\" && c.toolCallId === part.toolCallId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n ...part,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n\n if (\n part.type === \"reasoning\" &&\n \"parentId\" in part &&\n part.parentId\n ) {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"reasoning\" &&\n \"parentId\" in c &&\n c.parentId === part.parentId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n text: `${existing.text}\\n\\n${part.text}`,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n assistantMessage.content.push(part);\n }\n break;\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n }\n }\n return assistantMessage;\n};\n\nconst chunkExternalMessages = <T>(\n callbackResults: CallbackResult<T>[],\n joinStrategy?: JoinStrategy,\n) => {\n const results: ChunkResult<T>[] = [];\n let isAssistant = false;\n let pendingNone = false; // true if the previous assistant message had joinStrategy \"none\"\n let inputs: T[] = [];\n let outputs: useExternalMessageConverter.Message[] = [];\n\n const flush = () => {\n if (outputs.length) {\n results.push({\n inputs,\n outputs,\n });\n }\n inputs = [];\n outputs = [];\n isAssistant = false;\n pendingNone = false;\n };\n\n for (const callbackResult of callbackResults) {\n for (const output of callbackResult.outputs) {\n if (\n (pendingNone && output.role !== \"tool\") ||\n !isAssistant ||\n output.role === \"user\" ||\n output.role === \"system\"\n ) {\n flush();\n }\n isAssistant = output.role === \"assistant\" || output.role === \"tool\";\n\n if (inputs.at(-1) !== callbackResult.input) {\n inputs.push(callbackResult.input);\n }\n outputs.push(output);\n\n if (\n output.role === \"assistant\" &&\n (output.convertConfig?.joinStrategy === \"none\" ||\n joinStrategy === \"none\")\n ) {\n pendingNone = true;\n }\n }\n }\n flush();\n return results;\n};\n\nfunction createErrorAssistantMessage(\n error: ReadonlyJSONValue,\n): ThreadAssistantMessage {\n const msg: ThreadAssistantMessage = {\n id: generateErrorMessageId(),\n role: \"assistant\",\n content: [],\n status: { type: \"incomplete\", reason: \"error\", error },\n createdAt: new Date(),\n metadata: {\n unstable_state: null,\n unstable_annotations: [],\n unstable_data: [],\n custom: {},\n steps: [],\n },\n };\n bindExternalStoreMessage(msg, []);\n return msg;\n}\n\nexport const convertExternalMessages = <T extends WeakKey>(\n messages: T[],\n callback: useExternalMessageConverter.Callback<T>,\n isRunning: boolean,\n metadata: useExternalMessageConverter.Metadata,\n) => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n const output = callback(message, metadata);\n const outputs = Array.isArray(output) ? output : [output];\n const result = { input: message, outputs };\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults);\n\n const result = chunks.map((message, idx) => {\n const isLast = idx === chunks.length - 1;\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? metadata.error : undefined,\n );\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n });\n\n if (metadata.error) {\n const lastMessage = result.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n result.push(createErrorAssistantMessage(metadata.error));\n }\n }\n\n return result;\n};\n\nexport const useExternalMessageConverter = <T extends WeakKey>({\n callback,\n messages,\n isRunning,\n joinStrategy,\n metadata,\n}: {\n callback: useExternalMessageConverter.Callback<T>;\n messages: T[];\n isRunning: boolean;\n joinStrategy?: JoinStrategy | undefined;\n metadata?: useExternalMessageConverter.Metadata | undefined;\n}) => {\n const state = useMemo(\n () => ({\n metadata: metadata ?? {},\n callback,\n callbackCache: new WeakMap<T, CallbackResult<T>>(),\n chunkCache: new WeakMap<\n useExternalMessageConverter.Message,\n ChunkResult<T>\n >(),\n converterCache: new ThreadMessageConverter(),\n }),\n [callback, metadata],\n );\n\n return useMemo(() => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n let result = state.callbackCache.get(message);\n if (!result) {\n const output = state.callback(message, state.metadata);\n const outputs = Array.isArray(output) ? output : [output];\n result = { input: message, outputs };\n state.callbackCache.set(message, result);\n }\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults, joinStrategy).map(\n (m) => {\n const key = m.outputs[0];\n if (!key) return m;\n\n const cached = state.chunkCache.get(key);\n if (cached && shallowArrayEqual(cached.outputs, m.outputs))\n return cached;\n state.chunkCache.set(key, m);\n return m;\n },\n );\n\n const threadMessages = state.converterCache.convertMessages(\n chunks,\n (cache, message, idx) => {\n const isLast = idx === chunks.length - 1;\n\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? state.metadata.error : undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n ) {\n const inputs = getExternalStoreMessages<T>(cache);\n if (shallowArrayEqual(inputs, message.inputs)) {\n return cache;\n }\n }\n\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n },\n );\n\n bindExternalStoreMessage(threadMessages, messages);\n\n if (state.metadata.error) {\n const lastMessage = threadMessages.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n threadMessages.push(createErrorAssistantMessage(state.metadata.error));\n }\n }\n\n return threadMessages;\n }, [state, messages, isRunning, joinStrategy]);\n};\n\nconst shallowArrayEqual = (a: unknown[], b: unknown[]) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n};\n"],"mappings":";;;;;;;;AA+BA,MAAM,qBAAqB,MACzB,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA;AAEzC,MAAM,yBAAyB,MAA6C;CAC1E,IAAI,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA,GAAW,OAAO;CAC7D,OACE,EAAE,aAAa,QACd,EAAE,YAAY,QAAQ,EAAE,SAAS,aAAa,KAAA;AAEnD;AA6CA,MAAM,sBAAsB,UAAkB,cAAsB,GACjE,qBAAqB,CACpB,GAAK,SAAiB,uBAAuB,CAAC,GAC9C,GAAK,SAAiB,uBAAuB,CAAC,CAChD,EACF;AAEA,MAAM,wBACJ,aACsB;CACtB,MAAM,mBAGF;EACF,MAAM;EACN,SAAS,CAAC;CACZ;CACA,KAAK,MAAM,UAAU,UACnB,IAAI,OAAO,SAAS,QAAQ;EAC1B,MAAM,cAAc,iBAAiB,QAAQ,WAC1C,MAAM,EAAE,SAAS,eAAe,EAAE,eAAe,OAAO,UAC3D;EAGA,IAAI,gBAAgB,IAAI;GACtB,MAAM,WAAW,iBAAiB,QAChC;GAEF,IAAI,OAAO,aAAa,KAAA;QAClB,SAAS,aAAa,OAAO,UAC/B,MAAM,IAAI,MACR,kBAAkB,OAAO,WAAW,GAAG,OAAO,SAAS,qCAAqC,SAAS,UACvG;GAAA;GAEJ,iBAAiB,QAAQ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;GACT,MAAM,WAAW,IAAI,KAAK,CAAC;GAC3B,OAAO;EACT,CACF;EAEA,MAAM,iBAAiB,MAAM,eAAe,gBAC1C,SACC,OAAO,SAAS,QAAQ;GACvB,MAAM,SAAS,QAAQ,OAAO,SAAS;GAEvC,MAAM,SAAS,qBAAqB,QAAQ,OAAO;GAOnD,MAAM,aAAa,cACjB,QACA,WAPA,OAAO,OAAO,YAAY,YAC1B,OAAO,QAAQ,KAAK,qBAAqB,GAEzC,OAAO,OAAO,YAAY,YAC1B,OAAO,QAAQ,KAAK,iBAAiB,GAMrC,SAAS,MAAM,SAAS,QAAQ,KAAA,CAClC;GAEA,IACE,UACC,MAAM,SAAS,eACd,CAAC,aAAa,MAAM,MAAM,KAC1B,MAAM,WAAW;QAGf,kBADW,yBAA4B,KAChB,GAAG,QAAQ,MAAM,GAC1C,OAAO;GAAA;GAIX,MAAM,aAAa,sBACjB,QACA,IAAI,SAAS,GACb,UACF;GACA,yBAAyB,YAAY,QAAQ,MAAM;GACnD,OAAO;EACT,CACF;EAEA,yBAAyB,gBAAgB,QAAQ;EAEjD,IAAI,MAAM,SAAS,OAAO;GACxB,MAAM,cAAc,eAAe,GAAG,EAAE;GACxC,IAAI,CAAC,eAAe,YAAY,SAAS,aACvC,eAAe,KAAK,4BAA4B,MAAM,SAAS,KAAK,CAAC;EAEzE;EAEA,OAAO;CACT,GAAG;EAAC;EAAO;EAAU;EAAW;CAAY,CAAC;AAC/C;AAEA,MAAM,qBAAqB,GAAc,MAAiB;CACxD,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,IAAI,EAAE,OAAO,EAAE,IAAI,OAAO;CAE5B,OAAO;AACT"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { AssistantRuntimeImpl } from "../../runtime/api/assistant-runtime.js";
|
|
3
3
|
import { ExternalStoreRuntimeCore } from "../../runtimes/external-store/external-store-runtime-core.js";
|
|
4
4
|
import { useRuntimeAdapters } from "./RuntimeAdapterProvider.js";
|
|
5
|
-
import { useEffect, useMemo, useState } from "react";
|
|
5
|
+
import { useEffect, useMemo, useState } from "@assistant-ui/tap/react-shim";
|
|
6
6
|
//#region src/react/runtimes/useExternalStoreRuntime.ts
|
|
7
7
|
const useExternalStoreRuntime = (store) => {
|
|
8
8
|
const [runtime] = useState(() => new ExternalStoreRuntimeCore(store));
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { useMemo } from "react";
|
|
2
|
+
import { useMemo } from "@assistant-ui/tap/react-shim";
|
|
3
3
|
//#region src/react/runtimes/useExternalStoreSharedOptions.ts
|
|
4
4
|
const useExternalStoreSharedOptions = (options) => {
|
|
5
5
|
const { isDisabled, isSendDisabled, unstable_capabilities, suggestions } = options;
|
|
@@ -32,8 +32,9 @@ declare const splitLocalRuntimeOptions: <T extends LocalRuntimeOptions>(options:
|
|
|
32
32
|
suggestion?: SuggestionAdapter | undefined;
|
|
33
33
|
}, "chatModel"> | undefined;
|
|
34
34
|
unstable_humanToolNames: string[] | undefined;
|
|
35
|
+
unstable_enableMessageQueue: boolean | undefined;
|
|
35
36
|
};
|
|
36
|
-
otherOptions: Omit<T, "adapters" | "maxSteps" | "unstable_humanToolNames" | "cloud" | "initialMessages">;
|
|
37
|
+
otherOptions: Omit<T, "adapters" | "maxSteps" | "unstable_humanToolNames" | "unstable_enableMessageQueue" | "cloud" | "initialMessages">;
|
|
37
38
|
};
|
|
38
39
|
declare const useLocalRuntime: (chatModel: ChatModelAdapter, {
|
|
39
40
|
cloud,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocalRuntime.d.ts","names":[],"sources":["../../../src/react/runtimes/useLocalRuntime.ts"],"mappings":";;;;;;;;;;;;;KAcY,mBAAA,GAAsB,IAAA,CAAK,uBAAA;EACrC,KAAA,GAAQ,cAAA;EACR,eAAA,YAA2B,iBAAA;EAC3B,QAAA,GAAW,IAAA,CAAK,uBAAA;AAAA;AAAA,cA+CL,wBAAA,aAAsC,mBAAA,EACjD,OAAA,EAAS,CAAA
|
|
1
|
+
{"version":3,"file":"useLocalRuntime.d.ts","names":[],"sources":["../../../src/react/runtimes/useLocalRuntime.ts"],"mappings":";;;;;;;;;;;;;KAcY,mBAAA,GAAsB,IAAA,CAAK,uBAAA;EACrC,KAAA,GAAQ,cAAA;EACR,eAAA,YAA2B,iBAAA;EAC3B,QAAA,GAAW,IAAA,CAAK,uBAAA;AAAA;AAAA,cA+CL,wBAAA,aAAsC,mBAAA,EACjD,OAAA,EAAS,CAAA;;;;;;;;;;;;;;;;;;;;cAyBE,eAAA,GACX,SAAA,EAAW,gBAAA;EACX,KAAA;EAAA,GAAA;AAAA,IAAuB,mBAAA,KACtB,gBAAA"}
|
|
@@ -3,7 +3,7 @@ import { LocalRuntimeCore } from "../../runtimes/local/local-runtime-core.js";
|
|
|
3
3
|
import { useRuntimeAdapters } from "./RuntimeAdapterProvider.js";
|
|
4
4
|
import { useRemoteThreadListRuntime } from "./useRemoteThreadListRuntime.js";
|
|
5
5
|
import { useCloudThreadListAdapter } from "./cloud/useCloudThreadListAdapter.js";
|
|
6
|
-
import { useEffect, useMemo, useRef, useState } from "react";
|
|
6
|
+
import { useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
7
7
|
import { useAuiState } from "@assistant-ui/store";
|
|
8
8
|
//#region src/react/runtimes/useLocalRuntime.ts
|
|
9
9
|
const useLocalThreadRuntime = (chatModel, { initialMessages, ...options }) => {
|
|
@@ -38,14 +38,15 @@ const useLocalThreadRuntime = (chatModel, { initialMessages, ...options }) => {
|
|
|
38
38
|
return useMemo(() => new AssistantRuntimeImpl(runtime), [runtime]);
|
|
39
39
|
};
|
|
40
40
|
const splitLocalRuntimeOptions = (options) => {
|
|
41
|
-
const { cloud, initialMessages, maxSteps, adapters, unstable_humanToolNames, ...rest } = options;
|
|
41
|
+
const { cloud, initialMessages, maxSteps, adapters, unstable_humanToolNames, unstable_enableMessageQueue, ...rest } = options;
|
|
42
42
|
return {
|
|
43
43
|
localRuntimeOptions: {
|
|
44
44
|
cloud,
|
|
45
45
|
initialMessages,
|
|
46
46
|
maxSteps,
|
|
47
47
|
adapters,
|
|
48
|
-
unstable_humanToolNames
|
|
48
|
+
unstable_humanToolNames,
|
|
49
|
+
unstable_enableMessageQueue
|
|
49
50
|
},
|
|
50
51
|
otherOptions: rest
|
|
51
52
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocalRuntime.js","names":[],"sources":["../../../src/react/runtimes/useLocalRuntime.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport type {\n AssistantRuntime,\n ChatModelAdapter,\n ThreadMessageLike,\n} from \"../../index\";\nimport type { LocalRuntimeOptionsBase } from \"../../runtimes/local/local-runtime-options\";\nimport { AssistantRuntimeImpl, LocalRuntimeCore } from \"../../internal\";\nimport { useAuiState } from \"@assistant-ui/store\";\nimport { useRemoteThreadListRuntime } from \"./useRemoteThreadListRuntime\";\nimport { useCloudThreadListAdapter } from \"./cloud/useCloudThreadListAdapter\";\nimport { useRuntimeAdapters } from \"./RuntimeAdapterProvider\";\nimport type { AssistantCloud } from \"assistant-cloud\";\n\nexport type LocalRuntimeOptions = Omit<LocalRuntimeOptionsBase, \"adapters\"> & {\n cloud?: AssistantCloud | undefined;\n initialMessages?: readonly ThreadMessageLike[] | undefined;\n adapters?: Omit<LocalRuntimeOptionsBase[\"adapters\"], \"chatModel\"> | undefined;\n};\n\nconst useLocalThreadRuntime = (\n chatModel: ChatModelAdapter,\n { initialMessages, ...options }: LocalRuntimeOptions,\n): AssistantRuntime => {\n const { modelContext, ...threadListAdapters } = useRuntimeAdapters() ?? {};\n const opt = {\n ...options,\n adapters: {\n ...threadListAdapters,\n ...options.adapters,\n chatModel,\n },\n };\n\n const [runtime] = useState(() => new LocalRuntimeCore(opt, initialMessages));\n\n const threadIdRef = useRef<string | undefined>(undefined);\n threadIdRef.current = useAuiState((s) => s.threadListItem.remoteId);\n\n useEffect(() => {\n runtime.threads\n .getMainThreadRuntimeCore()\n .__internal_setGetThreadId(() => threadIdRef.current);\n }, [runtime]);\n\n useEffect(() => {\n return () => {\n runtime.threads.getMainThreadRuntimeCore().detach();\n };\n }, [runtime]);\n\n useEffect(() => {\n runtime.threads.getMainThreadRuntimeCore().__internal_setOptions(opt);\n runtime.threads.getMainThreadRuntimeCore().__internal_load();\n });\n\n useEffect(() => {\n if (!modelContext) return undefined;\n return runtime.registerModelContextProvider(modelContext);\n }, [modelContext, runtime]);\n\n return useMemo(() => new AssistantRuntimeImpl(runtime), [runtime]);\n};\n\nexport const splitLocalRuntimeOptions = <T extends LocalRuntimeOptions>(\n options: T,\n) => {\n const {\n cloud,\n initialMessages,\n maxSteps,\n adapters,\n unstable_humanToolNames,\n ...rest\n } = options;\n\n return {\n localRuntimeOptions: {\n cloud,\n initialMessages,\n maxSteps,\n adapters,\n unstable_humanToolNames,\n },\n otherOptions: rest,\n };\n};\n\nexport const useLocalRuntime = (\n chatModel: ChatModelAdapter,\n { cloud, ...options }: LocalRuntimeOptions = {},\n): AssistantRuntime => {\n const cloudAdapter = useCloudThreadListAdapter({ cloud });\n return useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useLocalThreadRuntime(chatModel, options);\n },\n adapter: cloudAdapter,\n allowNesting: true,\n });\n};\n"],"mappings":";;;;;;;;AAoBA,MAAM,yBACJ,WACA,EAAE,iBAAiB,GAAG,cACD;CACrB,MAAM,EAAE,cAAc,GAAG,uBAAuB,mBAAmB,KAAK,CAAC;CACzE,MAAM,MAAM;EACV,GAAG;EACH,UAAU;GACR,GAAG;GACH,GAAG,QAAQ;GACX;EACF;CACF;CAEA,MAAM,CAAC,WAAW,eAAe,IAAI,iBAAiB,KAAK,eAAe,CAAC;CAE3E,MAAM,cAAc,OAA2B,KAAA,CAAS;CACxD,YAAY,UAAU,aAAa,MAAM,EAAE,eAAe,QAAQ;CAElE,gBAAgB;EACd,QAAQ,QACL,yBAAyB,
|
|
1
|
+
{"version":3,"file":"useLocalRuntime.js","names":[],"sources":["../../../src/react/runtimes/useLocalRuntime.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport type {\n AssistantRuntime,\n ChatModelAdapter,\n ThreadMessageLike,\n} from \"../../index\";\nimport type { LocalRuntimeOptionsBase } from \"../../runtimes/local/local-runtime-options\";\nimport { AssistantRuntimeImpl, LocalRuntimeCore } from \"../../internal\";\nimport { useAuiState } from \"@assistant-ui/store\";\nimport { useRemoteThreadListRuntime } from \"./useRemoteThreadListRuntime\";\nimport { useCloudThreadListAdapter } from \"./cloud/useCloudThreadListAdapter\";\nimport { useRuntimeAdapters } from \"./RuntimeAdapterProvider\";\nimport type { AssistantCloud } from \"assistant-cloud\";\n\nexport type LocalRuntimeOptions = Omit<LocalRuntimeOptionsBase, \"adapters\"> & {\n cloud?: AssistantCloud | undefined;\n initialMessages?: readonly ThreadMessageLike[] | undefined;\n adapters?: Omit<LocalRuntimeOptionsBase[\"adapters\"], \"chatModel\"> | undefined;\n};\n\nconst useLocalThreadRuntime = (\n chatModel: ChatModelAdapter,\n { initialMessages, ...options }: LocalRuntimeOptions,\n): AssistantRuntime => {\n const { modelContext, ...threadListAdapters } = useRuntimeAdapters() ?? {};\n const opt = {\n ...options,\n adapters: {\n ...threadListAdapters,\n ...options.adapters,\n chatModel,\n },\n };\n\n const [runtime] = useState(() => new LocalRuntimeCore(opt, initialMessages));\n\n const threadIdRef = useRef<string | undefined>(undefined);\n threadIdRef.current = useAuiState((s) => s.threadListItem.remoteId);\n\n useEffect(() => {\n runtime.threads\n .getMainThreadRuntimeCore()\n .__internal_setGetThreadId(() => threadIdRef.current);\n }, [runtime]);\n\n useEffect(() => {\n return () => {\n runtime.threads.getMainThreadRuntimeCore().detach();\n };\n }, [runtime]);\n\n useEffect(() => {\n runtime.threads.getMainThreadRuntimeCore().__internal_setOptions(opt);\n runtime.threads.getMainThreadRuntimeCore().__internal_load();\n });\n\n useEffect(() => {\n if (!modelContext) return undefined;\n return runtime.registerModelContextProvider(modelContext);\n }, [modelContext, runtime]);\n\n return useMemo(() => new AssistantRuntimeImpl(runtime), [runtime]);\n};\n\nexport const splitLocalRuntimeOptions = <T extends LocalRuntimeOptions>(\n options: T,\n) => {\n const {\n cloud,\n initialMessages,\n maxSteps,\n adapters,\n unstable_humanToolNames,\n unstable_enableMessageQueue,\n ...rest\n } = options;\n\n return {\n localRuntimeOptions: {\n cloud,\n initialMessages,\n maxSteps,\n adapters,\n unstable_humanToolNames,\n unstable_enableMessageQueue,\n },\n otherOptions: rest,\n };\n};\n\nexport const useLocalRuntime = (\n chatModel: ChatModelAdapter,\n { cloud, ...options }: LocalRuntimeOptions = {},\n): AssistantRuntime => {\n const cloudAdapter = useCloudThreadListAdapter({ cloud });\n return useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useLocalThreadRuntime(chatModel, options);\n },\n adapter: cloudAdapter,\n allowNesting: true,\n });\n};\n"],"mappings":";;;;;;;;AAoBA,MAAM,yBACJ,WACA,EAAE,iBAAiB,GAAG,cACD;CACrB,MAAM,EAAE,cAAc,GAAG,uBAAuB,mBAAmB,KAAK,CAAC;CACzE,MAAM,MAAM;EACV,GAAG;EACH,UAAU;GACR,GAAG;GACH,GAAG,QAAQ;GACX;EACF;CACF;CAEA,MAAM,CAAC,WAAW,eAAe,IAAI,iBAAiB,KAAK,eAAe,CAAC;CAE3E,MAAM,cAAc,OAA2B,KAAA,CAAS;CACxD,YAAY,UAAU,aAAa,MAAM,EAAE,eAAe,QAAQ;CAElE,gBAAgB;EACd,QAAQ,QACL,yBAAyB,CAAC,CAC1B,gCAAgC,YAAY,OAAO;CACxD,GAAG,CAAC,OAAO,CAAC;CAEZ,gBAAgB;EACd,aAAa;GACX,QAAQ,QAAQ,yBAAyB,CAAC,CAAC,OAAO;EACpD;CACF,GAAG,CAAC,OAAO,CAAC;CAEZ,gBAAgB;EACd,QAAQ,QAAQ,yBAAyB,CAAC,CAAC,sBAAsB,GAAG;EACpE,QAAQ,QAAQ,yBAAyB,CAAC,CAAC,gBAAgB;CAC7D,CAAC;CAED,gBAAgB;EACd,IAAI,CAAC,cAAc,OAAO,KAAA;EAC1B,OAAO,QAAQ,6BAA6B,YAAY;CAC1D,GAAG,CAAC,cAAc,OAAO,CAAC;CAE1B,OAAO,cAAc,IAAI,qBAAqB,OAAO,GAAG,CAAC,OAAO,CAAC;AACnE;AAEA,MAAa,4BACX,YACG;CACH,MAAM,EACJ,OACA,iBACA,UACA,UACA,yBACA,6BACA,GAAG,SACD;CAEJ,OAAO;EACL,qBAAqB;GACnB;GACA;GACA;GACA;GACA;GACA;EACF;EACA,cAAc;CAChB;AACF;AAEA,MAAa,mBACX,WACA,EAAE,OAAO,GAAG,YAAiC,CAAC,MACzB;CAErB,OAAO,2BAA2B;EAChC,aAAa,SAAS,cAAc;GAClC,OAAO,sBAAsB,WAAW,OAAO;EACjD;EACA,SALmB,0BAA0B,EAAE,MAAM,CAKjC;EACpB,cAAc;CAChB,CAAC;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BaseAssistantRuntimeCore } from "../../runtime/base/base-assistant-runtime-core.js";
|
|
2
2
|
import { AssistantRuntimeImpl } from "../../runtime/api/assistant-runtime.js";
|
|
3
3
|
import { RemoteThreadListThreadListRuntimeCore } from "./RemoteThreadListThreadListRuntimeCore.js";
|
|
4
|
-
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
4
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
5
5
|
import { useAui } from "@assistant-ui/store";
|
|
6
6
|
//#region src/react/runtimes/useRemoteThreadListRuntime.ts
|
|
7
7
|
var RemoteThreadListRuntimeCore = class extends BaseAssistantRuntimeCore {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRemoteThreadListRuntime.js","names":[],"sources":["../../../src/react/runtimes/useRemoteThreadListRuntime.ts"],"sourcesContent":["import { useState, useEffect, useMemo, useRef, useCallback } from \"react\";\nimport { BaseAssistantRuntimeCore } from \"../../runtime/base/base-assistant-runtime-core\";\nimport { AssistantRuntimeImpl } from \"../../runtime/api/assistant-runtime\";\nimport type { RemoteThreadListOptions } from \"../../runtimes/remote-thread-list/types\";\nimport type { AssistantRuntimeCore } from \"../../runtime/interfaces/assistant-runtime-core\";\nimport type { AssistantRuntime } from \"../../runtime/api/assistant-runtime\";\nimport { RemoteThreadListThreadListRuntimeCore } from \"./RemoteThreadListThreadListRuntimeCore\";\nimport { useAui } from \"@assistant-ui/store\";\n\nclass RemoteThreadListRuntimeCore\n extends BaseAssistantRuntimeCore\n implements AssistantRuntimeCore\n{\n public readonly threads;\n\n constructor(options: RemoteThreadListOptions) {\n super();\n this.threads = new RemoteThreadListThreadListRuntimeCore(\n options,\n this._contextProvider,\n );\n }\n\n public get RenderComponent() {\n return this.threads.__internal_RenderComponent;\n }\n}\n\nconst useRemoteThreadListRuntimeImpl = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const [runtime] = useState(() => new RemoteThreadListRuntimeCore(options));\n useEffect(() => {\n runtime.threads.__internal_setOptions(options);\n runtime.threads.__internal_load();\n }, [runtime, options]);\n\n return useMemo(() => new AssistantRuntimeImpl(runtime), [runtime]);\n};\n\nexport const useRemoteThreadListRuntime = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const runtimeHookRef = useRef(options.runtimeHook);\n runtimeHookRef.current = options.runtimeHook;\n\n // threadId/initialThreadId only affect the constructor; capture once via ref\n const startThreadIdRef = useRef(options.threadId ?? options.initialThreadId);\n\n const stableRuntimeHook = useCallback(() => {\n return runtimeHookRef.current();\n }, []);\n\n const stableOptions = useMemo<RemoteThreadListOptions>(\n () => ({\n adapter: options.adapter,\n allowNesting: options.allowNesting,\n initialThreadId: startThreadIdRef.current,\n runtimeHook: stableRuntimeHook,\n }),\n [options.adapter, options.allowNesting, stableRuntimeHook],\n );\n\n const aui = useAui();\n const isNested = aui.threadListItem.source !== null;\n\n if (isNested) {\n if (!stableOptions.allowNesting) {\n throw new Error(\n \"useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. \" +\n \"Set allowNesting: true to allow nesting (the inner runtime will become a no-op).\",\n );\n }\n\n // If allowNesting is true and already inside a thread list context,\n // just call the runtimeHook directly (no-op behavior)\n return stableRuntimeHook();\n }\n\n const runtime = useRemoteThreadListRuntimeImpl(stableOptions);\n\n const prevThreadIdRef = useRef(options.threadId);\n useEffect(() => {\n if (options.threadId === prevThreadIdRef.current) return;\n prevThreadIdRef.current = options.threadId;\n if (options.threadId) {\n runtime.threads.switchToThread(options.threadId).catch(() => {});\n } else {\n runtime.threads.switchToNewThread().catch(() => {});\n }\n }, [runtime, options.threadId]);\n\n return runtime;\n};\n"],"mappings":";;;;;;AASA,IAAM,8BAAN,cACU,yBAEV;CACE;CAEA,YAAY,SAAkC;EAC5C,MAAM;EACN,KAAK,UAAU,IAAI,sCACjB,SACA,KAAK,gBACP;CACF;CAEA,IAAW,kBAAkB;EAC3B,OAAO,KAAK,QAAQ;CACtB;AACF;AAEA,MAAM,kCACJ,YACqB;CACrB,MAAM,CAAC,WAAW,eAAe,IAAI,4BAA4B,OAAO,CAAC;CACzE,gBAAgB;EACd,QAAQ,QAAQ,sBAAsB,OAAO;EAC7C,QAAQ,QAAQ,gBAAgB;CAClC,GAAG,CAAC,SAAS,OAAO,CAAC;CAErB,OAAO,cAAc,IAAI,qBAAqB,OAAO,GAAG,CAAC,OAAO,CAAC;AACnE;AAEA,MAAa,8BACX,YACqB;CACrB,MAAM,iBAAiB,OAAO,QAAQ,WAAW;CACjD,eAAe,UAAU,QAAQ;CAGjC,MAAM,mBAAmB,OAAO,QAAQ,YAAY,QAAQ,eAAe;CAE3E,MAAM,oBAAoB,kBAAkB;EAC1C,OAAO,eAAe,QAAQ;CAChC,GAAG,CAAC,CAAC;CAEL,MAAM,gBAAgB,eACb;EACL,SAAS,QAAQ;EACjB,cAAc,QAAQ;EACtB,iBAAiB,iBAAiB;EAClC,aAAa;CACf,IACA;EAAC,QAAQ;EAAS,QAAQ;EAAc;CAAiB,CAC3D;CAKA,IAHY,OACO,
|
|
1
|
+
{"version":3,"file":"useRemoteThreadListRuntime.js","names":[],"sources":["../../../src/react/runtimes/useRemoteThreadListRuntime.ts"],"sourcesContent":["import { useState, useEffect, useMemo, useRef, useCallback } from \"react\";\nimport { BaseAssistantRuntimeCore } from \"../../runtime/base/base-assistant-runtime-core\";\nimport { AssistantRuntimeImpl } from \"../../runtime/api/assistant-runtime\";\nimport type { RemoteThreadListOptions } from \"../../runtimes/remote-thread-list/types\";\nimport type { AssistantRuntimeCore } from \"../../runtime/interfaces/assistant-runtime-core\";\nimport type { AssistantRuntime } from \"../../runtime/api/assistant-runtime\";\nimport { RemoteThreadListThreadListRuntimeCore } from \"./RemoteThreadListThreadListRuntimeCore\";\nimport { useAui } from \"@assistant-ui/store\";\n\nclass RemoteThreadListRuntimeCore\n extends BaseAssistantRuntimeCore\n implements AssistantRuntimeCore\n{\n public readonly threads;\n\n constructor(options: RemoteThreadListOptions) {\n super();\n this.threads = new RemoteThreadListThreadListRuntimeCore(\n options,\n this._contextProvider,\n );\n }\n\n public get RenderComponent() {\n return this.threads.__internal_RenderComponent;\n }\n}\n\nconst useRemoteThreadListRuntimeImpl = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const [runtime] = useState(() => new RemoteThreadListRuntimeCore(options));\n useEffect(() => {\n runtime.threads.__internal_setOptions(options);\n runtime.threads.__internal_load();\n }, [runtime, options]);\n\n return useMemo(() => new AssistantRuntimeImpl(runtime), [runtime]);\n};\n\nexport const useRemoteThreadListRuntime = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const runtimeHookRef = useRef(options.runtimeHook);\n runtimeHookRef.current = options.runtimeHook;\n\n // threadId/initialThreadId only affect the constructor; capture once via ref\n const startThreadIdRef = useRef(options.threadId ?? options.initialThreadId);\n\n const stableRuntimeHook = useCallback(() => {\n return runtimeHookRef.current();\n }, []);\n\n const stableOptions = useMemo<RemoteThreadListOptions>(\n () => ({\n adapter: options.adapter,\n allowNesting: options.allowNesting,\n initialThreadId: startThreadIdRef.current,\n runtimeHook: stableRuntimeHook,\n }),\n [options.adapter, options.allowNesting, stableRuntimeHook],\n );\n\n const aui = useAui();\n const isNested = aui.threadListItem.source !== null;\n\n if (isNested) {\n if (!stableOptions.allowNesting) {\n throw new Error(\n \"useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. \" +\n \"Set allowNesting: true to allow nesting (the inner runtime will become a no-op).\",\n );\n }\n\n // If allowNesting is true and already inside a thread list context,\n // just call the runtimeHook directly (no-op behavior)\n return stableRuntimeHook();\n }\n\n const runtime = useRemoteThreadListRuntimeImpl(stableOptions);\n\n const prevThreadIdRef = useRef(options.threadId);\n useEffect(() => {\n if (options.threadId === prevThreadIdRef.current) return;\n prevThreadIdRef.current = options.threadId;\n if (options.threadId) {\n runtime.threads.switchToThread(options.threadId).catch(() => {});\n } else {\n runtime.threads.switchToNewThread().catch(() => {});\n }\n }, [runtime, options.threadId]);\n\n return runtime;\n};\n"],"mappings":";;;;;;AASA,IAAM,8BAAN,cACU,yBAEV;CACE;CAEA,YAAY,SAAkC;EAC5C,MAAM;EACN,KAAK,UAAU,IAAI,sCACjB,SACA,KAAK,gBACP;CACF;CAEA,IAAW,kBAAkB;EAC3B,OAAO,KAAK,QAAQ;CACtB;AACF;AAEA,MAAM,kCACJ,YACqB;CACrB,MAAM,CAAC,WAAW,eAAe,IAAI,4BAA4B,OAAO,CAAC;CACzE,gBAAgB;EACd,QAAQ,QAAQ,sBAAsB,OAAO;EAC7C,QAAQ,QAAQ,gBAAgB;CAClC,GAAG,CAAC,SAAS,OAAO,CAAC;CAErB,OAAO,cAAc,IAAI,qBAAqB,OAAO,GAAG,CAAC,OAAO,CAAC;AACnE;AAEA,MAAa,8BACX,YACqB;CACrB,MAAM,iBAAiB,OAAO,QAAQ,WAAW;CACjD,eAAe,UAAU,QAAQ;CAGjC,MAAM,mBAAmB,OAAO,QAAQ,YAAY,QAAQ,eAAe;CAE3E,MAAM,oBAAoB,kBAAkB;EAC1C,OAAO,eAAe,QAAQ;CAChC,GAAG,CAAC,CAAC;CAEL,MAAM,gBAAgB,eACb;EACL,SAAS,QAAQ;EACjB,cAAc,QAAQ;EACtB,iBAAiB,iBAAiB;EAClC,aAAa;CACf,IACA;EAAC,QAAQ;EAAS,QAAQ;EAAc;CAAiB,CAC3D;CAKA,IAHY,OACO,CAAC,CAAC,eAAe,WAAW,MAEjC;EACZ,IAAI,CAAC,cAAc,cACjB,MAAM,IAAI,MACR,sKAEF;EAKF,OAAO,kBAAkB;CAC3B;CAEA,MAAM,UAAU,+BAA+B,aAAa;CAE5D,MAAM,kBAAkB,OAAO,QAAQ,QAAQ;CAC/C,gBAAgB;EACd,IAAI,QAAQ,aAAa,gBAAgB,SAAS;EAClD,gBAAgB,UAAU,QAAQ;EAClC,IAAI,QAAQ,UACV,QAAQ,QAAQ,eAAe,QAAQ,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAC;OAE/D,QAAQ,QAAQ,kBAAkB,CAAC,CAAC,YAAY,CAAC,CAAC;CAEtD,GAAG,CAAC,SAAS,QAAQ,QAAQ,CAAC;CAE9B,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupParts.js","names":[],"sources":["../../../src/react/utils/groupParts.ts"],"sourcesContent":["import { isMcpAppUri } from \"../../types/message\";\nimport type { PartState } from \"../../store/scopes/part\";\nimport type { ToolsState } from \"../types/scopes/tools\";\n\n/**\n * Registry context passed to a `groupBy` function as its second argument by\n * `<MessagePrimitive.GroupedParts>`. Carries the live tool-UI registry so a\n * `groupBy` can resolve registry-driven grouping (e.g. standalone tool calls)\n * without the part itself having to carry that information.\n */\nexport type GroupByContext = {\n /** Tool UIs registered in the tool-UI registry, keyed by tool name. */\n readonly toolUIs?: ToolsState[\"toolUIs\"];\n};\n\n/**\n * Hierarchical adjacent-coalescing grouping for message parts.\n *\n * Given a group path per part (from `groupBy`), builds a tree of group\n * nodes wrapping individual parts. Adjacent parts sharing a path prefix\n * coalesce into the same group; ungrouped parts are direct children of\n * the root.\n *\n * Each node gets a structural `nodeKey` built from sibling indices\n * (`\"0.1.0\"`), stable under append-only streaming.\n */\n\n/**\n * Symbol attached to memoizable `groupBy` functions (e.g. those returned\n * by {@link groupPartByType}). Carries a string fingerprint of the config\n * so `MessagePrimitive.GroupedParts` can memo the tree on\n * `[parts, memoKey]` across renders — even when the helper call site\n * reconstructs the function each render.\n */\nexport const GROUPBY_MEMO_KEY: unique symbol = Symbol.for(\n \"@assistant-ui/groupBy.memoKey\",\n);\n\n/**\n * Synthetic part-type keys recognized by {@link groupPartByType}, in\n * addition to real {@link PartState} types:\n *\n * - `\"standalone-tool-call\"` — a tool-call whose UI should be presented on its\n * own, outside the chain-of-thought grouping. Matches MCP-app tool calls plus\n * any tool-call whose registered UI opts into standalone display (human\n * tools, the built-in generative-UI tool, and tools that set\n * `display: \"standalone\"`). Resolving the registry-driven cases reads the\n * {@link GroupByContext} passed to the `groupBy` function. Takes precedence\n * over the `\"tool-call\"` entry.\n * - `\"mcp-app\"` — **deprecated**, kept for back-compat. Matches only MCP-app\n * tool calls. Prefer `\"standalone-tool-call\"`, which is a superset.\n */\ntype GroupPartType = PartState[\"type\"] | \"standalone-tool-call\" | \"mcp-app\";\n\n/**\n * Build a `groupBy` from a `part.type → group-key path` lookup.\n * Parts whose type isn't in the map are left ungrouped. The returned\n * function carries a stable {@link GROUPBY_MEMO_KEY} fingerprint so\n * `<MessagePrimitive.GroupedParts>` can memoize its tree across renders.\n *\n * The synthetic `\"standalone-tool-call\"` key matches tool calls that should\n * render outside the chain-of-thought grouping. MCP-app calls are detected from\n * the part alone; the registry-driven cases (human tools, the generative-UI\n * tool, `display: \"standalone\"` opt-ins) are resolved from the\n * {@link GroupByContext} that `<MessagePrimitive.GroupedParts>` passes to the\n * `groupBy` function — the helper needs nothing threaded into it.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * \"standalone-tool-call\": [],\n * })}\n * >\n * {({ part, children }) => { ... }}\n * </MessagePrimitive.GroupedParts>\n * ```\n */\nexport const groupPartByType = <TKey extends `group-${string}`>(\n map: Partial<Readonly<Record<GroupPartType, readonly TKey[]>>>,\n): ((part: PartState, context?: GroupByContext) => readonly TKey[]) => {\n const lookup = map as Readonly<Record<string, readonly TKey[] | undefined>>;\n const fn = ((part, context) => {\n if (part.type === \"tool-call\") {\n const isMcpApp = isMcpAppUri(part.mcp?.app?.resourceUri);\n // Read the first registration's flag — the same one `resolveToolRender`\n // renders — so grouping and rendering never disagree for a tool name.\n const isStandalone =\n isMcpApp ||\n (context?.toolUIs?.[part.toolName]?.[0]?.standalone ?? false);\n if (isStandalone && lookup[\"standalone-tool-call\"] !== undefined) {\n return lookup[\"standalone-tool-call\"]!;\n }\n // TODO(v0.15): drop the deprecated \"mcp-app\" key (superseded by \"standalone-tool-call\").\n if (isMcpApp && lookup[\"mcp-app\"] !== undefined) {\n return lookup[\"mcp-app\"]!;\n }\n }\n return lookup[part.type] ?? [];\n }) as ((part: PartState, context?: GroupByContext) => readonly TKey[]) & {\n [GROUPBY_MEMO_KEY]?: string;\n };\n // Sort keys so the fingerprint is insensitive to map insertion order —\n // two maps with the same key/value pairs but different declaration order\n // would otherwise hash differently and invalidate the memo unnecessarily.\n const sortedKeys = Object.keys(map).sort();\n const sortedEntries = sortedKeys.map((k) => [k, map[k as keyof typeof map]]);\n fn[GROUPBY_MEMO_KEY] = `groupPartByType:${JSON.stringify(sortedEntries)}`;\n return fn;\n};\n\nexport type GroupNode = GroupNodeGroup | GroupNodePart;\n\nexport interface GroupNodeGroup {\n readonly type: \"group\";\n /** Current-level group key (last segment of the path). */\n readonly key: string;\n /** Structural React key: sibling-index path, e.g. `\"0.1.0\"`. */\n readonly nodeKey: string;\n /** Indices of parts in this subtree, in order. */\n readonly indices: readonly number[];\n readonly children: readonly GroupNode[];\n}\n\nexport interface GroupNodePart {\n readonly type: \"part\";\n /** Index of the part in the message. */\n readonly index: number;\n /** Structural React key: sibling-index path within parent. */\n readonly nodeKey: string;\n}\n\ninterface BuildFrame {\n key: string;\n nodeKey: string;\n indices: number[];\n children: GroupNode[];\n nextChildIdx: number;\n}\n\nconst makeChildNodeKey = (parent: BuildFrame): string => {\n const idx = parent.nextChildIdx++;\n return parent.nodeKey === \"\" ? String(idx) : `${parent.nodeKey}.${idx}`;\n};\n\n/**\n * Build the group tree from an array of normalized group paths.\n * `paths[i]` is the path for part `i`. The output tree contains one\n * `part` node per part and one `group` node per coalesced run.\n */\nexport const buildGroupTree = (\n paths: readonly (readonly string[])[],\n): readonly GroupNode[] => {\n const root: BuildFrame = {\n key: \"\",\n nodeKey: \"\",\n indices: [],\n children: [],\n nextChildIdx: 0,\n };\n const stack: BuildFrame[] = [root];\n\n const closeTop = (): void => {\n const closing = stack.pop()!;\n const parent = stack[stack.length - 1]!;\n parent.children.push({\n type: \"group\",\n key: closing.key,\n nodeKey: closing.nodeKey,\n indices: closing.indices,\n children: closing.children,\n });\n };\n\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i]!;\n\n // Find the longest prefix shared between currently-open groups\n // (excluding root) and this part's path.\n let common = 0;\n while (\n common < stack.length - 1 &&\n common < path.length &&\n stack[common + 1]!.key === path[common]\n ) {\n common++;\n }\n\n // Close groups not on this path.\n while (stack.length - 1 > common) {\n closeTop();\n }\n\n // Open new groups down to the part's depth.\n while (stack.length - 1 < path.length) {\n const parent = stack[stack.length - 1]!;\n stack.push({\n key: path[stack.length - 1]!,\n nodeKey: makeChildNodeKey(parent),\n indices: [],\n children: [],\n nextChildIdx: 0,\n });\n }\n\n // Push this part as a leaf in the deepest open group (or root).\n const top = stack[stack.length - 1]!;\n top.children.push({\n type: \"part\",\n index: i,\n nodeKey: makeChildNodeKey(top),\n });\n\n // Record the part index in every open ancestor group.\n for (let s = 1; s < stack.length; s++) {\n stack[s]!.indices.push(i);\n }\n }\n\n // Close any still-open groups.\n while (stack.length > 1) {\n closeTop();\n }\n\n return root.children;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,mBAAkC,OAAO,IACpD,+BACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,mBACX,QACqE;CACrE,MAAM,SAAS;CACf,MAAM,OAAO,MAAM,YAAY;EAC7B,IAAI,KAAK,SAAS,aAAa;GAC7B,MAAM,WAAW,YAAY,KAAK,KAAK,KAAK,WAAW;GAMvD,KAFE,aACC,SAAS,UAAU,KAAK,YAAY,IAAI,cAAc,WACrC,OAAO,4BAA4B,KAAA,GACrD,OAAO,OAAO;GAGhB,IAAI,YAAY,OAAO,eAAe,KAAA,GACpC,OAAO,OAAO;EAElB;EACA,OAAO,OAAO,KAAK,SAAS,CAAC;CAC/B;CAOA,MAAM,gBADa,OAAO,KAAK,GAAG,EAAE,KACL,EAAE,KAAK,MAAM,CAAC,GAAG,IAAI,EAAsB,CAAC;CAC3E,GAAG,oBAAoB,mBAAmB,KAAK,UAAU,aAAa;CACtE,OAAO;AACT;AA+BA,MAAM,oBAAoB,WAA+B;CACvD,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,YAAY,KAAK,OAAO,GAAG,IAAI,GAAG,OAAO,QAAQ,GAAG;AACpE;;;;;;AAOA,MAAa,kBACX,UACyB;CACzB,MAAM,OAAmB;EACvB,KAAK;EACL,SAAS;EACT,SAAS,CAAC;EACV,UAAU,CAAC;EACX,cAAc;CAChB;CACA,MAAM,QAAsB,CAAC,IAAI;CAEjC,MAAM,iBAAuB;EAC3B,MAAM,UAAU,MAAM,IAAI;EAE1B,MADqB,MAAM,SAAS,GAC7B,SAAS,KAAK;GACnB,MAAM;GACN,KAAK,QAAQ;GACb,SAAS,QAAQ;GACjB,SAAS,QAAQ;GACjB,UAAU,QAAQ;EACpB,CAAC;CACH;CAEA,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,OAAO,MAAM;EAInB,IAAI,SAAS;EACb,OACE,SAAS,MAAM,SAAS,KACxB,SAAS,KAAK,UACd,MAAM,SAAS,GAAI,QAAQ,KAAK,SAEhC;EAIF,OAAO,MAAM,SAAS,IAAI,QACxB,SAAS;EAIX,OAAO,MAAM,SAAS,IAAI,KAAK,QAAQ;GACrC,MAAM,SAAS,MAAM,MAAM,SAAS;GACpC,MAAM,KAAK;IACT,KAAK,KAAK,MAAM,SAAS;IACzB,SAAS,iBAAiB,MAAM;IAChC,SAAS,CAAC;IACV,UAAU,CAAC;IACX,cAAc;GAChB,CAAC;EACH;EAGA,MAAM,MAAM,MAAM,MAAM,SAAS;EACjC,IAAI,SAAS,KAAK;GAChB,MAAM;GACN,OAAO;GACP,SAAS,iBAAiB,GAAG;EAC/B,CAAC;EAGD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAChC,MAAM,GAAI,QAAQ,KAAK,CAAC;CAE5B;CAGA,OAAO,MAAM,SAAS,GACpB,SAAS;CAGX,OAAO,KAAK;AACd"}
|
|
1
|
+
{"version":3,"file":"groupParts.js","names":[],"sources":["../../../src/react/utils/groupParts.ts"],"sourcesContent":["import { isMcpAppUri } from \"../../types/message\";\nimport type { PartState } from \"../../store/scopes/part\";\nimport type { ToolsState } from \"../types/scopes/tools\";\n\n/**\n * Registry context passed to a `groupBy` function as its second argument by\n * `<MessagePrimitive.GroupedParts>`. Carries the live tool-UI registry so a\n * `groupBy` can resolve registry-driven grouping (e.g. standalone tool calls)\n * without the part itself having to carry that information.\n */\nexport type GroupByContext = {\n /** Tool UIs registered in the tool-UI registry, keyed by tool name. */\n readonly toolUIs?: ToolsState[\"toolUIs\"];\n};\n\n/**\n * Hierarchical adjacent-coalescing grouping for message parts.\n *\n * Given a group path per part (from `groupBy`), builds a tree of group\n * nodes wrapping individual parts. Adjacent parts sharing a path prefix\n * coalesce into the same group; ungrouped parts are direct children of\n * the root.\n *\n * Each node gets a structural `nodeKey` built from sibling indices\n * (`\"0.1.0\"`), stable under append-only streaming.\n */\n\n/**\n * Symbol attached to memoizable `groupBy` functions (e.g. those returned\n * by {@link groupPartByType}). Carries a string fingerprint of the config\n * so `MessagePrimitive.GroupedParts` can memo the tree on\n * `[parts, memoKey]` across renders — even when the helper call site\n * reconstructs the function each render.\n */\nexport const GROUPBY_MEMO_KEY: unique symbol = Symbol.for(\n \"@assistant-ui/groupBy.memoKey\",\n);\n\n/**\n * Synthetic part-type keys recognized by {@link groupPartByType}, in\n * addition to real {@link PartState} types:\n *\n * - `\"standalone-tool-call\"` — a tool-call whose UI should be presented on its\n * own, outside the chain-of-thought grouping. Matches MCP-app tool calls plus\n * any tool-call whose registered UI opts into standalone display (human\n * tools, the built-in generative-UI tool, and tools that set\n * `display: \"standalone\"`). Resolving the registry-driven cases reads the\n * {@link GroupByContext} passed to the `groupBy` function. Takes precedence\n * over the `\"tool-call\"` entry.\n * - `\"mcp-app\"` — **deprecated**, kept for back-compat. Matches only MCP-app\n * tool calls. Prefer `\"standalone-tool-call\"`, which is a superset.\n */\ntype GroupPartType = PartState[\"type\"] | \"standalone-tool-call\" | \"mcp-app\";\n\n/**\n * Build a `groupBy` from a `part.type → group-key path` lookup.\n * Parts whose type isn't in the map are left ungrouped. The returned\n * function carries a stable {@link GROUPBY_MEMO_KEY} fingerprint so\n * `<MessagePrimitive.GroupedParts>` can memoize its tree across renders.\n *\n * The synthetic `\"standalone-tool-call\"` key matches tool calls that should\n * render outside the chain-of-thought grouping. MCP-app calls are detected from\n * the part alone; the registry-driven cases (human tools, the generative-UI\n * tool, `display: \"standalone\"` opt-ins) are resolved from the\n * {@link GroupByContext} that `<MessagePrimitive.GroupedParts>` passes to the\n * `groupBy` function — the helper needs nothing threaded into it.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * \"standalone-tool-call\": [],\n * })}\n * >\n * {({ part, children }) => { ... }}\n * </MessagePrimitive.GroupedParts>\n * ```\n */\nexport const groupPartByType = <TKey extends `group-${string}`>(\n map: Partial<Readonly<Record<GroupPartType, readonly TKey[]>>>,\n): ((part: PartState, context?: GroupByContext) => readonly TKey[]) => {\n const lookup = map as Readonly<Record<string, readonly TKey[] | undefined>>;\n const fn = ((part, context) => {\n if (part.type === \"tool-call\") {\n const isMcpApp = isMcpAppUri(part.mcp?.app?.resourceUri);\n // Read the first registration's flag — the same one `resolveToolRender`\n // renders — so grouping and rendering never disagree for a tool name.\n const isStandalone =\n isMcpApp ||\n (context?.toolUIs?.[part.toolName]?.[0]?.standalone ?? false);\n if (isStandalone && lookup[\"standalone-tool-call\"] !== undefined) {\n return lookup[\"standalone-tool-call\"]!;\n }\n // TODO(v0.15): drop the deprecated \"mcp-app\" key (superseded by \"standalone-tool-call\").\n if (isMcpApp && lookup[\"mcp-app\"] !== undefined) {\n return lookup[\"mcp-app\"]!;\n }\n }\n return lookup[part.type] ?? [];\n }) as ((part: PartState, context?: GroupByContext) => readonly TKey[]) & {\n [GROUPBY_MEMO_KEY]?: string;\n };\n // Sort keys so the fingerprint is insensitive to map insertion order —\n // two maps with the same key/value pairs but different declaration order\n // would otherwise hash differently and invalidate the memo unnecessarily.\n const sortedKeys = Object.keys(map).sort();\n const sortedEntries = sortedKeys.map((k) => [k, map[k as keyof typeof map]]);\n fn[GROUPBY_MEMO_KEY] = `groupPartByType:${JSON.stringify(sortedEntries)}`;\n return fn;\n};\n\nexport type GroupNode = GroupNodeGroup | GroupNodePart;\n\nexport interface GroupNodeGroup {\n readonly type: \"group\";\n /** Current-level group key (last segment of the path). */\n readonly key: string;\n /** Structural React key: sibling-index path, e.g. `\"0.1.0\"`. */\n readonly nodeKey: string;\n /** Indices of parts in this subtree, in order. */\n readonly indices: readonly number[];\n readonly children: readonly GroupNode[];\n}\n\nexport interface GroupNodePart {\n readonly type: \"part\";\n /** Index of the part in the message. */\n readonly index: number;\n /** Structural React key: sibling-index path within parent. */\n readonly nodeKey: string;\n}\n\ninterface BuildFrame {\n key: string;\n nodeKey: string;\n indices: number[];\n children: GroupNode[];\n nextChildIdx: number;\n}\n\nconst makeChildNodeKey = (parent: BuildFrame): string => {\n const idx = parent.nextChildIdx++;\n return parent.nodeKey === \"\" ? String(idx) : `${parent.nodeKey}.${idx}`;\n};\n\n/**\n * Build the group tree from an array of normalized group paths.\n * `paths[i]` is the path for part `i`. The output tree contains one\n * `part` node per part and one `group` node per coalesced run.\n */\nexport const buildGroupTree = (\n paths: readonly (readonly string[])[],\n): readonly GroupNode[] => {\n const root: BuildFrame = {\n key: \"\",\n nodeKey: \"\",\n indices: [],\n children: [],\n nextChildIdx: 0,\n };\n const stack: BuildFrame[] = [root];\n\n const closeTop = (): void => {\n const closing = stack.pop()!;\n const parent = stack[stack.length - 1]!;\n parent.children.push({\n type: \"group\",\n key: closing.key,\n nodeKey: closing.nodeKey,\n indices: closing.indices,\n children: closing.children,\n });\n };\n\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i]!;\n\n // Find the longest prefix shared between currently-open groups\n // (excluding root) and this part's path.\n let common = 0;\n while (\n common < stack.length - 1 &&\n common < path.length &&\n stack[common + 1]!.key === path[common]\n ) {\n common++;\n }\n\n // Close groups not on this path.\n while (stack.length - 1 > common) {\n closeTop();\n }\n\n // Open new groups down to the part's depth.\n while (stack.length - 1 < path.length) {\n const parent = stack[stack.length - 1]!;\n stack.push({\n key: path[stack.length - 1]!,\n nodeKey: makeChildNodeKey(parent),\n indices: [],\n children: [],\n nextChildIdx: 0,\n });\n }\n\n // Push this part as a leaf in the deepest open group (or root).\n const top = stack[stack.length - 1]!;\n top.children.push({\n type: \"part\",\n index: i,\n nodeKey: makeChildNodeKey(top),\n });\n\n // Record the part index in every open ancestor group.\n for (let s = 1; s < stack.length; s++) {\n stack[s]!.indices.push(i);\n }\n }\n\n // Close any still-open groups.\n while (stack.length > 1) {\n closeTop();\n }\n\n return root.children;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,mBAAkC,OAAO,IACpD,+BACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,mBACX,QACqE;CACrE,MAAM,SAAS;CACf,MAAM,OAAO,MAAM,YAAY;EAC7B,IAAI,KAAK,SAAS,aAAa;GAC7B,MAAM,WAAW,YAAY,KAAK,KAAK,KAAK,WAAW;GAMvD,KAFE,aACC,SAAS,UAAU,KAAK,SAAS,GAAG,EAAE,EAAE,cAAc,WACrC,OAAO,4BAA4B,KAAA,GACrD,OAAO,OAAO;GAGhB,IAAI,YAAY,OAAO,eAAe,KAAA,GACpC,OAAO,OAAO;EAElB;EACA,OAAO,OAAO,KAAK,SAAS,CAAC;CAC/B;CAOA,MAAM,gBADa,OAAO,KAAK,GAAG,CAAC,CAAC,KACL,CAAC,CAAC,KAAK,MAAM,CAAC,GAAG,IAAI,EAAsB,CAAC;CAC3E,GAAG,oBAAoB,mBAAmB,KAAK,UAAU,aAAa;CACtE,OAAO;AACT;AA+BA,MAAM,oBAAoB,WAA+B;CACvD,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,YAAY,KAAK,OAAO,GAAG,IAAI,GAAG,OAAO,QAAQ,GAAG;AACpE;;;;;;AAOA,MAAa,kBACX,UACyB;CACzB,MAAM,OAAmB;EACvB,KAAK;EACL,SAAS;EACT,SAAS,CAAC;EACV,UAAU,CAAC;EACX,cAAc;CAChB;CACA,MAAM,QAAsB,CAAC,IAAI;CAEjC,MAAM,iBAAuB;EAC3B,MAAM,UAAU,MAAM,IAAI;EAE1B,MADqB,MAAM,SAAS,EAC9B,CAAC,SAAS,KAAK;GACnB,MAAM;GACN,KAAK,QAAQ;GACb,SAAS,QAAQ;GACjB,SAAS,QAAQ;GACjB,UAAU,QAAQ;EACpB,CAAC;CACH;CAEA,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,OAAO,MAAM;EAInB,IAAI,SAAS;EACb,OACE,SAAS,MAAM,SAAS,KACxB,SAAS,KAAK,UACd,MAAM,SAAS,EAAE,CAAE,QAAQ,KAAK,SAEhC;EAIF,OAAO,MAAM,SAAS,IAAI,QACxB,SAAS;EAIX,OAAO,MAAM,SAAS,IAAI,KAAK,QAAQ;GACrC,MAAM,SAAS,MAAM,MAAM,SAAS;GACpC,MAAM,KAAK;IACT,KAAK,KAAK,MAAM,SAAS;IACzB,SAAS,iBAAiB,MAAM;IAChC,SAAS,CAAC;IACV,UAAU,CAAC;IACX,cAAc;GAChB,CAAC;EACH;EAGA,MAAM,MAAM,MAAM,MAAM,SAAS;EACjC,IAAI,SAAS,KAAK;GAChB,MAAM;GACN,OAAO;GACP,SAAS,iBAAiB,GAAG;EAC/B,CAAC;EAGD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAChC,MAAM,EAAE,CAAE,QAAQ,KAAK,CAAC;CAE5B;CAGA,OAAO,MAAM,SAAS,GACpB,SAAS;CAGX,OAAO,KAAK;AACd"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachment-runtime.js","names":[],"sources":["../../../src/runtime/api/attachment-runtime.ts"],"sourcesContent":["import type { Attachment, CompleteAttachment } from \"../../types/attachment\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\n\nimport type { ComposerRuntimeCoreBinding } from \"./bindings\";\nimport type { AttachmentRuntimePath } from \"./paths\";\n\ntype MessageAttachmentState = CompleteAttachment & {\n readonly source: \"message\";\n};\n\ntype ThreadComposerAttachmentState = Attachment & {\n readonly source: \"thread-composer\";\n};\n\ntype EditComposerAttachmentState = Attachment & {\n readonly source: \"edit-composer\";\n};\n\nexport type AttachmentState =\n | ThreadComposerAttachmentState\n | EditComposerAttachmentState\n | MessageAttachmentState;\n\ntype AttachmentSnapshotBinding<Source extends AttachmentRuntimeSource> =\n SubscribableWithState<\n AttachmentState & { source: Source },\n AttachmentRuntimePath & { attachmentSource: Source }\n >;\n\ntype AttachmentRuntimeSource = AttachmentState[\"source\"];\n\nexport type AttachmentRuntime<\n TSource extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> = {\n readonly path: AttachmentRuntimePath & { attachmentSource: TSource };\n readonly source: TSource;\n getState(): AttachmentState & { source: TSource };\n remove(): Promise<void>;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport abstract class AttachmentRuntimeImpl<\n Source extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> implements AttachmentRuntime {\n public get path() {\n return this._core.path;\n }\n\n public abstract get source(): Source;\n\n constructor(private _core: AttachmentSnapshotBinding<Source>) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.getState = this.getState.bind(this);\n this.remove = this.remove.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n\n public getState(): AttachmentState & { source: Source } {\n return this._core.getState();\n }\n\n public abstract remove(): Promise<void>;\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n}\n\nabstract class ComposerAttachmentRuntime<\n Source extends \"thread-composer\" | \"edit-composer\",\n> extends AttachmentRuntimeImpl<Source> {\n constructor(\n core: AttachmentSnapshotBinding<Source>,\n private _composerApi: ComposerRuntimeCoreBinding,\n ) {\n super(core);\n }\n\n public remove() {\n const core = this._composerApi.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.removeAttachment(this.getState().id);\n }\n}\n\nexport class ThreadComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"thread-composer\"> {\n public get source(): \"thread-composer\" {\n return \"thread-composer\";\n }\n}\n\nexport class EditComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"edit-composer\"> {\n public get source(): \"edit-composer\" {\n return \"edit-composer\";\n }\n}\n\nexport class MessageAttachmentRuntimeImpl extends AttachmentRuntimeImpl<\"message\"> {\n public get source(): \"message\" {\n return \"message\";\n }\n\n public remove(): never {\n throw new Error(\"Message attachments cannot be removed\");\n }\n}\n"],"mappings":";AA0CA,IAAsB,wBAAtB,MAE+B;CAOT;CANpB,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM;CACpB;CAIA,YAAY,OAAkD;EAA1C,KAAA,QAAA;EAClB,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;EACvC,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;CAC3C;CAEA,WAAwD;EACtD,OAAO,KAAK,MAAM,SAAS;CAC7B;CAIA,UAAiB,UAAsB;EACrC,OAAO,KAAK,MAAM,UAAU,QAAQ;CACtC;AACF;AAEA,IAAe,4BAAf,cAEU,sBAA8B;CAG5B;CAFV,YACE,MACA,cACA;EACA,MAAM,IAAI;EAFF,KAAA,eAAA;CAGV;CAEA,SAAgB;EACd,MAAM,OAAO,KAAK,aAAa,SAAS;EACxC,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,2BAA2B;EACtD,OAAO,KAAK,iBAAiB,KAAK,SAAS,
|
|
1
|
+
{"version":3,"file":"attachment-runtime.js","names":[],"sources":["../../../src/runtime/api/attachment-runtime.ts"],"sourcesContent":["import type { Attachment, CompleteAttachment } from \"../../types/attachment\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\n\nimport type { ComposerRuntimeCoreBinding } from \"./bindings\";\nimport type { AttachmentRuntimePath } from \"./paths\";\n\ntype MessageAttachmentState = CompleteAttachment & {\n readonly source: \"message\";\n};\n\ntype ThreadComposerAttachmentState = Attachment & {\n readonly source: \"thread-composer\";\n};\n\ntype EditComposerAttachmentState = Attachment & {\n readonly source: \"edit-composer\";\n};\n\nexport type AttachmentState =\n | ThreadComposerAttachmentState\n | EditComposerAttachmentState\n | MessageAttachmentState;\n\ntype AttachmentSnapshotBinding<Source extends AttachmentRuntimeSource> =\n SubscribableWithState<\n AttachmentState & { source: Source },\n AttachmentRuntimePath & { attachmentSource: Source }\n >;\n\ntype AttachmentRuntimeSource = AttachmentState[\"source\"];\n\nexport type AttachmentRuntime<\n TSource extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> = {\n readonly path: AttachmentRuntimePath & { attachmentSource: TSource };\n readonly source: TSource;\n getState(): AttachmentState & { source: TSource };\n remove(): Promise<void>;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport abstract class AttachmentRuntimeImpl<\n Source extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> implements AttachmentRuntime {\n public get path() {\n return this._core.path;\n }\n\n public abstract get source(): Source;\n\n constructor(private _core: AttachmentSnapshotBinding<Source>) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.getState = this.getState.bind(this);\n this.remove = this.remove.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n\n public getState(): AttachmentState & { source: Source } {\n return this._core.getState();\n }\n\n public abstract remove(): Promise<void>;\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n}\n\nabstract class ComposerAttachmentRuntime<\n Source extends \"thread-composer\" | \"edit-composer\",\n> extends AttachmentRuntimeImpl<Source> {\n constructor(\n core: AttachmentSnapshotBinding<Source>,\n private _composerApi: ComposerRuntimeCoreBinding,\n ) {\n super(core);\n }\n\n public remove() {\n const core = this._composerApi.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.removeAttachment(this.getState().id);\n }\n}\n\nexport class ThreadComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"thread-composer\"> {\n public get source(): \"thread-composer\" {\n return \"thread-composer\";\n }\n}\n\nexport class EditComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"edit-composer\"> {\n public get source(): \"edit-composer\" {\n return \"edit-composer\";\n }\n}\n\nexport class MessageAttachmentRuntimeImpl extends AttachmentRuntimeImpl<\"message\"> {\n public get source(): \"message\" {\n return \"message\";\n }\n\n public remove(): never {\n throw new Error(\"Message attachments cannot be removed\");\n }\n}\n"],"mappings":";AA0CA,IAAsB,wBAAtB,MAE+B;CAOT;CANpB,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM;CACpB;CAIA,YAAY,OAAkD;EAA1C,KAAA,QAAA;EAClB,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;EACvC,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;CAC3C;CAEA,WAAwD;EACtD,OAAO,KAAK,MAAM,SAAS;CAC7B;CAIA,UAAiB,UAAsB;EACrC,OAAO,KAAK,MAAM,UAAU,QAAQ;CACtC;AACF;AAEA,IAAe,4BAAf,cAEU,sBAA8B;CAG5B;CAFV,YACE,MACA,cACA;EACA,MAAM,IAAI;EAFF,KAAA,eAAA;CAGV;CAEA,SAAgB;EACd,MAAM,OAAO,KAAK,aAAa,SAAS;EACxC,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,2BAA2B;EACtD,OAAO,KAAK,iBAAiB,KAAK,SAAS,CAAC,CAAC,EAAE;CACjD;AACF;AAEA,IAAa,sCAAb,cAAyD,0BAA6C;CACpG,IAAW,SAA4B;EACrC,OAAO;CACT;AACF;AAEA,IAAa,oCAAb,cAAuD,0BAA2C;CAChG,IAAW,SAA0B;EACnC,OAAO;CACT;AACF;AAEA,IAAa,+BAAb,cAAkD,sBAAiC;CACjF,IAAW,SAAoB;EAC7B,OAAO;CACT;CAEA,SAAuB;EACrB,MAAM,IAAI,MAAM,uCAAuC;CACzD;AACF"}
|
|
@@ -2,6 +2,7 @@ import { MessageRole, RunConfig } from "../../types/message.js";
|
|
|
2
2
|
import { Attachment, CreateAttachment } from "../../types/attachment.js";
|
|
3
3
|
import { Unsubscribe } from "../../types/unsubscribe.js";
|
|
4
4
|
import { QuoteInfo } from "../../types/quote.js";
|
|
5
|
+
import { QueueItemState } from "../../store/scopes/queue-item.js";
|
|
5
6
|
import { ComposerRuntimeEventCallback, ComposerRuntimeEventType, DictationState, SendOptions } from "../interfaces/composer-runtime-core.js";
|
|
6
7
|
import { ComposerRuntimePath } from "./paths.js";
|
|
7
8
|
import { ComposerRuntimeCoreBinding, EditComposerRuntimeCoreBinding, ThreadComposerRuntimeCoreBinding } from "./bindings.js";
|
|
@@ -27,7 +28,8 @@ type BaseComposerState = {
|
|
|
27
28
|
* The currently quoted text, if any.
|
|
28
29
|
* Undefined when no quote is set.
|
|
29
30
|
*/
|
|
30
|
-
readonly quote: QuoteInfo | undefined;
|
|
31
|
+
readonly quote: QuoteInfo | undefined; /** Messages waiting to be processed. Empty unless the `queue` capability is set. */
|
|
32
|
+
readonly queue: readonly QueueItemState[];
|
|
31
33
|
};
|
|
32
34
|
type ThreadComposerState = BaseComposerState & {
|
|
33
35
|
readonly type: "thread";
|
|
@@ -93,7 +95,9 @@ type ComposerRuntime = {
|
|
|
93
95
|
/**
|
|
94
96
|
* Cancel the current run. In edit mode, this will exit edit mode.
|
|
95
97
|
*/
|
|
96
|
-
cancel(): void;
|
|
98
|
+
cancel(): void; /** Promote a queued message so it processes next. */
|
|
99
|
+
steerQueueItem(queueItemId: string): void; /** Remove a queued message. */
|
|
100
|
+
removeQueueItem(queueItemId: string): void;
|
|
97
101
|
/**
|
|
98
102
|
* Listens for changes to the composer state.
|
|
99
103
|
* @param callback The callback to call when the composer state changes.
|
|
@@ -137,6 +141,8 @@ declare abstract class ComposerRuntimeImpl implements ComposerRuntime {
|
|
|
137
141
|
clearAttachments(): Promise<void>;
|
|
138
142
|
send(options?: SendOptions): void;
|
|
139
143
|
cancel(): void;
|
|
144
|
+
steerQueueItem(queueItemId: string): void;
|
|
145
|
+
removeQueueItem(queueItemId: string): void;
|
|
140
146
|
setRole(role: MessageRole): void;
|
|
141
147
|
startDictation(): void;
|
|
142
148
|
stopDictation(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"composer-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/composer-runtime.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"composer-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/composer-runtime.ts"],"mappings":";;;;;;;;;;;KA0CK,iBAAA;EAAA,SACM,SAAA;EAAA,SACA,OAAA;EAAA,SACA,SAAA;EAAA,SACA,OAAA;EAAA,SAEA,IAAA;EAAA,SACA,IAAA,EAAM,WAAA;EAAA,SACN,WAAA,WAAsB,UAAA;EAAA,SACtB,SAAA,EAAW,SAAA;EAAA,SAEX,gBAAA;EAe8B;;;;EAAA,SAT9B,SAAA,EAAW,cAAA;EAXX;;;;EAAA,SAiBA,KAAA,EAAO,SAAA,cAdP;EAAA,SAiBA,KAAA,WAAgB,cAAA;AAAA;AAAA,KAGf,mBAAA,GAAsB,iBAAiB;EAAA,SACxC,IAAI;AAAA;AAAA,KAGH,iBAAA,GAAoB,iBAAiB;EAAA,SACtC,IAAA;EAAA,SACA,QAAA;EAAA,SACA,QAAA;AAAA;AAAA,KAGC,aAAA,GAAgB,mBAAA,GAAsB,iBAAiB;AAAA,KAuDvD,eAAA;EAAA,SACD,IAAA,EAAM,mBAAA;EAAA,SACN,IAAA;EAlEI;AAGf;;EAoEE,QAAA,IAAY,aAAA;EApEmC;;;;;;AAG9B;AAGnB;;EAyEE,aAAA,CAAc,gBAAA,EAAkB,IAAA,GAAO,gBAAA,GAAmB,OAAA;EAzEhC;AAAuC;AAuDnE;;EAwBE,OAAA,CAAQ,IAAA;EAvBO;;;;EA6Bf,OAAA,CAAQ,IAAA,EAAM,WAAA;EAAA;;;;;;;;;;;EAad,YAAA,CAAa,SAAA,EAAW,SAAA;EAgErB;;;EA3DH,KAAA,IAAS,OAAA;EA/CM;;;EAoDf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A,WAAc,iBAAA;AAAA;AAAA,KAGzC,qBAAA,GAAwB,IAAA,CAClC,eAAA;EAAA,SAGS,IAAA,EAAM,mBAAA;IAAwB,cAAA;EAAA;EAAA,SAC9B,IAAA;EACT,QAAA,IAAY,mBAAA;EAEZ,oBAAA,CACE,GAAA,WACC,iBAAA;IAAsB,MAAA;EAAA;AAAA;AAAA,cAGd,yBAAA,SACH,mBAAA,YACG,qBAAA;EAAA,IAES,IAAA,IACQ,mBAAA;IACxB,cAAA;EAAA;EAAA,IAIO,IAAA;EAAA,QAIH,SAAA;cAEI,IAAA,EAAM,gCAAA;EAgBF,QAAA,IAAY,mBAAA;EAIrB,oBAAA,CAAqB,GAAA,WAAW,mCAAA;AAAA;AAAA,KA0B7B,mBAAA,GAAsB,IAAA,CAChC,eAAA;EAAA,SAGS,IAAA,EAAM,mBAAA;IAAwB,cAAA;EAAA;EAAA,SAC9B,IAAA;EAET,QAAA,IAAY,iBAAA;EACZ,SAAA;EAEA,oBAAA,CACE,GAAA,WACC,iBAAA;IAAsB,MAAA;EAAA;AAAA;AAAA,cAGd,uBAAA,SACH,mBAAA,YACG,mBAAA;EAAA,QAaD,UAAA;EAAA,IAXU,IAAA,IACQ,mBAAA;IAAwB,cAAA;EAAA;EAAA,IAGzC,IAAA;EAAA,QAIH,SAAA;cAEN,IAAA,EAAM,8BAAA,EACE,UAAA;EAmBM,sBAAA;EAKA,QAAA,IAAY,iBAAA;EAIrB,SAAA;EAIA,oBAAA,CAAqB,GAAA,WAAW,iCAAA;AAAA"}
|
|
@@ -17,6 +17,7 @@ const getThreadComposerState = (runtime) => {
|
|
|
17
17
|
attachmentAccept: runtime?.attachmentAccept ?? "",
|
|
18
18
|
dictation: runtime?.dictation,
|
|
19
19
|
quote: runtime?.quote,
|
|
20
|
+
queue: runtime?.queue ?? EMPTY_ARRAY,
|
|
20
21
|
value: runtime?.text ?? ""
|
|
21
22
|
});
|
|
22
23
|
};
|
|
@@ -34,6 +35,7 @@ const getEditComposerState = (runtime) => {
|
|
|
34
35
|
attachmentAccept: runtime?.attachmentAccept ?? "",
|
|
35
36
|
dictation: runtime?.dictation,
|
|
36
37
|
quote: runtime?.quote,
|
|
38
|
+
queue: runtime?.queue ?? EMPTY_ARRAY,
|
|
37
39
|
parentId: runtime?.parentId ?? null,
|
|
38
40
|
sourceId: runtime?.sourceId ?? null,
|
|
39
41
|
value: runtime?.text ?? ""
|
|
@@ -57,6 +59,8 @@ var ComposerRuntimeImpl = class {
|
|
|
57
59
|
this.clearAttachments = this.clearAttachments.bind(this);
|
|
58
60
|
this.send = this.send.bind(this);
|
|
59
61
|
this.cancel = this.cancel.bind(this);
|
|
62
|
+
this.steerQueueItem = this.steerQueueItem.bind(this);
|
|
63
|
+
this.removeQueueItem = this.removeQueueItem.bind(this);
|
|
60
64
|
this.setRole = this.setRole.bind(this);
|
|
61
65
|
this.getAttachmentByIndex = this.getAttachmentByIndex.bind(this);
|
|
62
66
|
this.startDictation = this.startDictation.bind(this);
|
|
@@ -99,6 +103,16 @@ var ComposerRuntimeImpl = class {
|
|
|
99
103
|
if (!core) throw new Error("Composer is not available");
|
|
100
104
|
core.cancel();
|
|
101
105
|
}
|
|
106
|
+
steerQueueItem(queueItemId) {
|
|
107
|
+
const core = this._core.getState();
|
|
108
|
+
if (!core) throw new Error("Composer is not available");
|
|
109
|
+
core.steerQueueItem(queueItemId);
|
|
110
|
+
}
|
|
111
|
+
removeQueueItem(queueItemId) {
|
|
112
|
+
const core = this._core.getState();
|
|
113
|
+
if (!core) throw new Error("Composer is not available");
|
|
114
|
+
core.removeQueueItem(queueItemId);
|
|
115
|
+
}
|
|
102
116
|
setRole(role) {
|
|
103
117
|
const core = this._core.getState();
|
|
104
118
|
if (!core) throw new Error("Composer is not available");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"composer-runtime.js","names":[],"sources":["../../../src/runtime/api/composer-runtime.ts"],"sourcesContent":["import type { Attachment, CreateAttachment } from \"../../types/attachment\";\nimport type { MessageRole } from \"../../types/message\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport {\n LazyMemoizeSubject,\n EventSubscriptionSubject,\n} from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type {\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventType,\n DictationState,\n EditComposerRuntimeCore,\n SendOptions,\n ThreadComposerRuntimeCore,\n} from \"../interfaces/composer-runtime-core\";\nimport type {\n ThreadComposerRuntimeCoreBinding,\n EditComposerRuntimeCoreBinding,\n ComposerRuntimeCoreBinding,\n} from \"./bindings\";\nimport type { ComposerRuntimePath } from \"./paths\";\n\nimport {\n type AttachmentRuntime,\n type AttachmentState,\n EditComposerAttachmentRuntimeImpl,\n ThreadComposerAttachmentRuntimeImpl,\n} from \"./attachment-runtime\";\n\nexport type {\n ThreadComposerRuntimeCoreBinding,\n EditComposerRuntimeCoreBinding,\n ComposerRuntimeCoreBinding,\n};\n\ntype BaseComposerState = {\n readonly canCancel: boolean;\n readonly canSend: boolean;\n readonly isEditing: boolean;\n readonly isEmpty: boolean;\n\n readonly text: string;\n readonly role: MessageRole;\n readonly attachments: readonly Attachment[];\n readonly runConfig: RunConfig;\n\n readonly attachmentAccept: string;\n\n /**\n * The current state of dictation.\n * Undefined when dictation is not active.\n */\n readonly dictation: DictationState | undefined;\n\n /**\n * The currently quoted text, if any.\n * Undefined when no quote is set.\n */\n readonly quote: QuoteInfo | undefined;\n};\n\nexport type ThreadComposerState = BaseComposerState & {\n readonly type: \"thread\";\n};\n\nexport type EditComposerState = BaseComposerState & {\n readonly type: \"edit\";\n readonly parentId: string | null;\n readonly sourceId: string | null;\n};\n\nexport type ComposerState = ThreadComposerState | EditComposerState;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst EMPTY_OBJECT = Object.freeze({});\nconst getThreadComposerState = (\n runtime: ThreadComposerRuntimeCore | undefined,\n): ThreadComposerState => {\n return Object.freeze({\n type: \"thread\",\n\n isEditing: runtime?.isEditing ?? false,\n canCancel: runtime?.canCancel ?? false,\n canSend: runtime?.canSend ?? false,\n isEmpty: runtime?.isEmpty ?? true,\n\n attachments: runtime?.attachments ?? EMPTY_ARRAY,\n text: runtime?.text ?? \"\",\n role: runtime?.role ?? \"user\",\n runConfig: runtime?.runConfig ?? EMPTY_OBJECT,\n attachmentAccept: runtime?.attachmentAccept ?? \"\",\n dictation: runtime?.dictation,\n quote: runtime?.quote,\n\n value: runtime?.text ?? \"\",\n });\n};\n\nconst getEditComposerState = (\n runtime: EditComposerRuntimeCore | undefined,\n): EditComposerState => {\n return Object.freeze({\n type: \"edit\",\n\n isEditing: runtime?.isEditing ?? false,\n canCancel: runtime?.canCancel ?? false,\n canSend: runtime?.canSend ?? false,\n isEmpty: runtime?.isEmpty ?? true,\n\n text: runtime?.text ?? \"\",\n role: runtime?.role ?? \"user\",\n attachments: runtime?.attachments ?? EMPTY_ARRAY,\n runConfig: runtime?.runConfig ?? EMPTY_OBJECT,\n attachmentAccept: runtime?.attachmentAccept ?? \"\",\n dictation: runtime?.dictation,\n quote: runtime?.quote,\n\n parentId: runtime?.parentId ?? null,\n sourceId: runtime?.sourceId ?? null,\n\n value: runtime?.text ?? \"\",\n });\n};\n\nexport type ComposerRuntime = {\n readonly path: ComposerRuntimePath;\n readonly type: \"edit\" | \"thread\";\n\n /**\n * Get the current state of the composer. Includes any data that has been added to the composer.\n */\n getState(): ComposerState;\n\n /**\n * Add an attachment to the composer. Accepts either a standard File object\n * (processed through the AttachmentAdapter) or a CreateAttachment descriptor\n * for external-source attachments (URLs, API data, CMS references). External\n * descriptors bypass the adapter's `add()` step but still respect\n * `adapter.accept` when an adapter is configured; without an adapter they\n * are added as-is.\n * @param fileOrAttachment The file or attachment descriptor to add.\n */\n addAttachment(fileOrAttachment: File | CreateAttachment): Promise<void>;\n\n /**\n * Set the text of the composer.\n * @param text The text to set in the composer.\n */\n setText(text: string): void;\n\n /**\n * Set the role of the composer. For instance, if you'd like a specific message to have the 'assistant' role, you can do so here.\n * @param role The role to set in the composer.\n */\n setRole(role: MessageRole): void;\n\n /**\n * Set the run config of the composer. This is used to send custom configuration data to the model.\n * Within your backend, you can use the `runConfig` object.\n * Example:\n * ```ts\n * composerRuntime.setRunConfig({\n * custom: { customField: \"customValue\" }\n * });\n * ```\n * @param runConfig The run config to set in the composer.\n */\n setRunConfig(runConfig: RunConfig): void;\n\n /**\n * Reset the composer. This will clear the entire state of the composer, including all text and attachments.\n */\n reset(): Promise<void>;\n\n /**\n * Clear all attachments from the composer.\n */\n clearAttachments(): Promise<void>;\n\n /**\n * Send a message. This will send whatever text or attachments are in the composer.\n * @param options Optional send options. Use `{ startRun: true }` to force starting a new run.\n */\n send(options?: SendOptions): void;\n\n /**\n * Cancel the current run. In edit mode, this will exit edit mode.\n */\n cancel(): void;\n\n /**\n * Listens for changes to the composer state.\n * @param callback The callback to call when the composer state changes.\n */\n subscribe(callback: () => void): Unsubscribe;\n\n /**\n * Get an attachment by index.\n * @param idx The index of the attachment to get.\n */\n getAttachmentByIndex(idx: number): AttachmentRuntime;\n\n /**\n * Start dictation to convert voice to text input.\n * Requires a DictationAdapter to be configured.\n */\n startDictation(): void;\n\n /**\n * Stop the current dictation session.\n */\n stopDictation(): void;\n\n /**\n * Set a quote for the next message. Pass undefined to clear.\n * @param quote The quote info to set, or undefined to clear.\n */\n setQuote(quote: QuoteInfo | undefined): void;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport abstract class ComposerRuntimeImpl implements ComposerRuntime {\n public get path() {\n return this._core.path;\n }\n\n public abstract get type(): \"edit\" | \"thread\";\n\n constructor(protected _core: ComposerRuntimeCoreBinding) {}\n\n protected __internal_bindMethods() {\n this.setText = this.setText.bind(this);\n this.setRunConfig = this.setRunConfig.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.addAttachment = this.addAttachment.bind(this);\n this.reset = this.reset.bind(this);\n this.clearAttachments = this.clearAttachments.bind(this);\n this.send = this.send.bind(this);\n this.cancel = this.cancel.bind(this);\n this.setRole = this.setRole.bind(this);\n this.getAttachmentByIndex = this.getAttachmentByIndex.bind(this);\n this.startDictation = this.startDictation.bind(this);\n this.stopDictation = this.stopDictation.bind(this);\n this.setQuote = this.setQuote.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n }\n\n public abstract getState(): ComposerState;\n\n public setText(text: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setText(text);\n }\n\n public setRunConfig(runConfig: RunConfig) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setRunConfig(runConfig);\n }\n\n public addAttachment(fileOrAttachment: File | CreateAttachment) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.addAttachment(fileOrAttachment);\n }\n\n public reset() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.reset();\n }\n\n public clearAttachments() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.clearAttachments();\n }\n\n public send(options?: SendOptions) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.send(options);\n }\n\n public cancel() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.cancel();\n }\n\n public setRole(role: MessageRole) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setRole(role);\n }\n\n public startDictation() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.startDictation();\n }\n\n public stopDictation() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.stopDictation();\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setQuote(quote);\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ComposerRuntimeEventType>\n >();\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ComposerRuntimeEventType>({\n event,\n binding: this._core,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n\n public abstract getAttachmentByIndex(idx: number): AttachmentRuntime;\n}\n\nexport type ThreadComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"thread\" };\n readonly type: \"thread\";\n getState(): ThreadComposerState;\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"thread-composer\" };\n};\n\nexport class ThreadComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements ThreadComposerRuntime\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & {\n composerSource: \"thread\";\n };\n }\n\n public get type() {\n return \"thread\" as const;\n }\n\n private _getState;\n\n constructor(core: ThreadComposerRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n path: core.path,\n getState: () => getThreadComposerState(core.getState()),\n subscribe: (callback) => core.subscribe(callback),\n });\n super({\n path: core.path,\n getState: () => core.getState(),\n subscribe: (callback) => stateBinding.subscribe(callback),\n });\n this._getState = stateBinding.getState.bind(stateBinding);\n\n this.__internal_bindMethods();\n }\n\n public override getState(): ThreadComposerState {\n return this._getState();\n }\n\n public getAttachmentByIndex(idx: number) {\n return new ThreadComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"thread-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: `${this.path.ref}.attachments[${idx}]`,\n },\n getState: () => {\n const attachments = this.getState().attachments;\n const attachment = attachments[idx];\n if (!attachment) return SKIP_UPDATE;\n\n return {\n ...attachment,\n source: \"thread-composer\",\n } satisfies AttachmentState & { source: \"thread-composer\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n\nexport type EditComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"edit\" };\n readonly type: \"edit\";\n\n getState(): EditComposerState;\n beginEdit(): void;\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"edit-composer\" };\n};\n\nexport class EditComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements EditComposerRuntime\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & { composerSource: \"edit\" };\n }\n\n public get type() {\n return \"edit\" as const;\n }\n\n private _getState;\n constructor(\n core: EditComposerRuntimeCoreBinding,\n private _beginEdit: () => void,\n ) {\n const stateBinding = new LazyMemoizeSubject({\n path: core.path,\n getState: () => getEditComposerState(core.getState()),\n subscribe: (callback) => core.subscribe(callback),\n });\n\n super({\n path: core.path,\n getState: () => core.getState(),\n subscribe: (callback) => stateBinding.subscribe(callback),\n });\n\n this._getState = stateBinding.getState.bind(stateBinding);\n\n this.__internal_bindMethods();\n }\n\n public override __internal_bindMethods() {\n super.__internal_bindMethods();\n this.beginEdit = this.beginEdit.bind(this);\n }\n\n public override getState(): EditComposerState {\n return this._getState();\n }\n\n public beginEdit() {\n this._beginEdit();\n }\n\n public getAttachmentByIndex(idx: number) {\n return new EditComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"edit-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: `${this.path.ref}.attachments[${idx}]`,\n },\n getState: () => {\n const attachments = this.getState().attachments;\n const attachment = attachments[idx];\n if (!attachment) return SKIP_UPDATE;\n\n return {\n ...attachment,\n source: \"edit-composer\",\n } satisfies AttachmentState & { source: \"edit-composer\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n"],"mappings":";;;AA+EA,MAAM,cAAc,OAAO,OAAO,CAAC,CAAC;AACpC,MAAM,eAAe,OAAO,OAAO,CAAC,CAAC;AACrC,MAAM,0BACJ,YACwB;CACxB,OAAO,OAAO,OAAO;EACnB,MAAM;EAEN,WAAW,SAAS,aAAa;EACjC,WAAW,SAAS,aAAa;EACjC,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,WAAW;EAE7B,aAAa,SAAS,eAAe;EACrC,MAAM,SAAS,QAAQ;EACvB,MAAM,SAAS,QAAQ;EACvB,WAAW,SAAS,aAAa;EACjC,kBAAkB,SAAS,oBAAoB;EAC/C,WAAW,SAAS;EACpB,OAAO,SAAS;EAEhB,OAAO,SAAS,QAAQ;CAC1B,CAAC;AACH;AAEA,MAAM,wBACJ,YACsB;CACtB,OAAO,OAAO,OAAO;EACnB,MAAM;EAEN,WAAW,SAAS,aAAa;EACjC,WAAW,SAAS,aAAa;EACjC,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,WAAW;EAE7B,MAAM,SAAS,QAAQ;EACvB,MAAM,SAAS,QAAQ;EACvB,aAAa,SAAS,eAAe;EACrC,WAAW,SAAS,aAAa;EACjC,kBAAkB,SAAS,oBAAoB;EAC/C,WAAW,SAAS;EACpB,OAAO,SAAS;EAEhB,UAAU,SAAS,YAAY;EAC/B,UAAU,SAAS,YAAY;EAE/B,OAAO,SAAS,QAAQ;CAC1B,CAAC;AACH;AA0GA,IAAsB,sBAAtB,MAAqE;CAO7C;CANtB,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM;CACpB;CAIA,YAAY,OAA6C;EAAnC,KAAA,QAAA;CAAoC;CAE1D,yBAAmC;EACjC,KAAK,UAAU,KAAK,QAAQ,KAAK,IAAI;EACrC,KAAK,eA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AC1D,CAAC;EAZO,KAAA,aAAA;EAcR,KAAK,YAAY,aAAa,SAAS,KAAK,YAAY;EAExD,KAAK,uBAAuB;CAC9B;CAEA,yBAAyC;EACvC,MAAM,uBAAuB;EAC7B,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;CAC3C;CAEA,WAA8C;EAC5C,OAAO,KAAK,UAAU;CACxB;CAEA,YAAmB;EACjB,KAAK,WAAW;CAClB;CAEA,qBAA4B,KAAa;EACvC,OAAO,IAAI,kCACT,IAAI,sBAAsB;GACxB,MAAM;IACJ,GAAG,KAAK;IACR,kBAAkB;IAClB,oBAAoB;KAAE,MAAM;KAAS,OAAO;IAAI;IAChD,KAAK,GAAG,KAAK,KAAK,IAAI,eAAe,IAAI;GAC3C;GACA,gBAAgB;IAEd,MAAM,aADc,KAAK,SAAS,EAAE,YACL;IAC/B,IAAI,CAAC,YAAY,OAAO;IAExB,OAAO;KACL,GAAG;KACH,QAAQ;IACV;GACF;GACA,YAAY,aAAa,KAAK,MAAM,UAAU,QAAQ;EACxD,CAAC,GACD,KAAK,KACP;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"composer-runtime.js","names":[],"sources":["../../../src/runtime/api/composer-runtime.ts"],"sourcesContent":["import type { Attachment, CreateAttachment } from \"../../types/attachment\";\nimport type { MessageRole } from \"../../types/message\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport type { QueueItemState } from \"../../store/scopes/queue-item\";\nimport {\n LazyMemoizeSubject,\n EventSubscriptionSubject,\n} from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type {\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventType,\n DictationState,\n EditComposerRuntimeCore,\n SendOptions,\n ThreadComposerRuntimeCore,\n} from \"../interfaces/composer-runtime-core\";\nimport type {\n ThreadComposerRuntimeCoreBinding,\n EditComposerRuntimeCoreBinding,\n ComposerRuntimeCoreBinding,\n} from \"./bindings\";\nimport type { ComposerRuntimePath } from \"./paths\";\n\nimport {\n type AttachmentRuntime,\n type AttachmentState,\n EditComposerAttachmentRuntimeImpl,\n ThreadComposerAttachmentRuntimeImpl,\n} from \"./attachment-runtime\";\n\nexport type {\n ThreadComposerRuntimeCoreBinding,\n EditComposerRuntimeCoreBinding,\n ComposerRuntimeCoreBinding,\n};\n\ntype BaseComposerState = {\n readonly canCancel: boolean;\n readonly canSend: boolean;\n readonly isEditing: boolean;\n readonly isEmpty: boolean;\n\n readonly text: string;\n readonly role: MessageRole;\n readonly attachments: readonly Attachment[];\n readonly runConfig: RunConfig;\n\n readonly attachmentAccept: string;\n\n /**\n * The current state of dictation.\n * Undefined when dictation is not active.\n */\n readonly dictation: DictationState | undefined;\n\n /**\n * The currently quoted text, if any.\n * Undefined when no quote is set.\n */\n readonly quote: QuoteInfo | undefined;\n\n /** Messages waiting to be processed. Empty unless the `queue` capability is set. */\n readonly queue: readonly QueueItemState[];\n};\n\nexport type ThreadComposerState = BaseComposerState & {\n readonly type: \"thread\";\n};\n\nexport type EditComposerState = BaseComposerState & {\n readonly type: \"edit\";\n readonly parentId: string | null;\n readonly sourceId: string | null;\n};\n\nexport type ComposerState = ThreadComposerState | EditComposerState;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst EMPTY_OBJECT = Object.freeze({});\nconst getThreadComposerState = (\n runtime: ThreadComposerRuntimeCore | undefined,\n): ThreadComposerState => {\n return Object.freeze({\n type: \"thread\",\n\n isEditing: runtime?.isEditing ?? false,\n canCancel: runtime?.canCancel ?? false,\n canSend: runtime?.canSend ?? false,\n isEmpty: runtime?.isEmpty ?? true,\n\n attachments: runtime?.attachments ?? EMPTY_ARRAY,\n text: runtime?.text ?? \"\",\n role: runtime?.role ?? \"user\",\n runConfig: runtime?.runConfig ?? EMPTY_OBJECT,\n attachmentAccept: runtime?.attachmentAccept ?? \"\",\n dictation: runtime?.dictation,\n quote: runtime?.quote,\n queue: runtime?.queue ?? EMPTY_ARRAY,\n\n value: runtime?.text ?? \"\",\n });\n};\n\nconst getEditComposerState = (\n runtime: EditComposerRuntimeCore | undefined,\n): EditComposerState => {\n return Object.freeze({\n type: \"edit\",\n\n isEditing: runtime?.isEditing ?? false,\n canCancel: runtime?.canCancel ?? false,\n canSend: runtime?.canSend ?? false,\n isEmpty: runtime?.isEmpty ?? true,\n\n text: runtime?.text ?? \"\",\n role: runtime?.role ?? \"user\",\n attachments: runtime?.attachments ?? EMPTY_ARRAY,\n runConfig: runtime?.runConfig ?? EMPTY_OBJECT,\n attachmentAccept: runtime?.attachmentAccept ?? \"\",\n dictation: runtime?.dictation,\n quote: runtime?.quote,\n queue: runtime?.queue ?? EMPTY_ARRAY,\n\n parentId: runtime?.parentId ?? null,\n sourceId: runtime?.sourceId ?? null,\n\n value: runtime?.text ?? \"\",\n });\n};\n\nexport type ComposerRuntime = {\n readonly path: ComposerRuntimePath;\n readonly type: \"edit\" | \"thread\";\n\n /**\n * Get the current state of the composer. Includes any data that has been added to the composer.\n */\n getState(): ComposerState;\n\n /**\n * Add an attachment to the composer. Accepts either a standard File object\n * (processed through the AttachmentAdapter) or a CreateAttachment descriptor\n * for external-source attachments (URLs, API data, CMS references). External\n * descriptors bypass the adapter's `add()` step but still respect\n * `adapter.accept` when an adapter is configured; without an adapter they\n * are added as-is.\n * @param fileOrAttachment The file or attachment descriptor to add.\n */\n addAttachment(fileOrAttachment: File | CreateAttachment): Promise<void>;\n\n /**\n * Set the text of the composer.\n * @param text The text to set in the composer.\n */\n setText(text: string): void;\n\n /**\n * Set the role of the composer. For instance, if you'd like a specific message to have the 'assistant' role, you can do so here.\n * @param role The role to set in the composer.\n */\n setRole(role: MessageRole): void;\n\n /**\n * Set the run config of the composer. This is used to send custom configuration data to the model.\n * Within your backend, you can use the `runConfig` object.\n * Example:\n * ```ts\n * composerRuntime.setRunConfig({\n * custom: { customField: \"customValue\" }\n * });\n * ```\n * @param runConfig The run config to set in the composer.\n */\n setRunConfig(runConfig: RunConfig): void;\n\n /**\n * Reset the composer. This will clear the entire state of the composer, including all text and attachments.\n */\n reset(): Promise<void>;\n\n /**\n * Clear all attachments from the composer.\n */\n clearAttachments(): Promise<void>;\n\n /**\n * Send a message. This will send whatever text or attachments are in the composer.\n * @param options Optional send options. Use `{ startRun: true }` to force starting a new run.\n */\n send(options?: SendOptions): void;\n\n /**\n * Cancel the current run. In edit mode, this will exit edit mode.\n */\n cancel(): void;\n\n /** Promote a queued message so it processes next. */\n steerQueueItem(queueItemId: string): void;\n\n /** Remove a queued message. */\n removeQueueItem(queueItemId: string): void;\n\n /**\n * Listens for changes to the composer state.\n * @param callback The callback to call when the composer state changes.\n */\n subscribe(callback: () => void): Unsubscribe;\n\n /**\n * Get an attachment by index.\n * @param idx The index of the attachment to get.\n */\n getAttachmentByIndex(idx: number): AttachmentRuntime;\n\n /**\n * Start dictation to convert voice to text input.\n * Requires a DictationAdapter to be configured.\n */\n startDictation(): void;\n\n /**\n * Stop the current dictation session.\n */\n stopDictation(): void;\n\n /**\n * Set a quote for the next message. Pass undefined to clear.\n * @param quote The quote info to set, or undefined to clear.\n */\n setQuote(quote: QuoteInfo | undefined): void;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport abstract class ComposerRuntimeImpl implements ComposerRuntime {\n public get path() {\n return this._core.path;\n }\n\n public abstract get type(): \"edit\" | \"thread\";\n\n constructor(protected _core: ComposerRuntimeCoreBinding) {}\n\n protected __internal_bindMethods() {\n this.setText = this.setText.bind(this);\n this.setRunConfig = this.setRunConfig.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.addAttachment = this.addAttachment.bind(this);\n this.reset = this.reset.bind(this);\n this.clearAttachments = this.clearAttachments.bind(this);\n this.send = this.send.bind(this);\n this.cancel = this.cancel.bind(this);\n this.steerQueueItem = this.steerQueueItem.bind(this);\n this.removeQueueItem = this.removeQueueItem.bind(this);\n this.setRole = this.setRole.bind(this);\n this.getAttachmentByIndex = this.getAttachmentByIndex.bind(this);\n this.startDictation = this.startDictation.bind(this);\n this.stopDictation = this.stopDictation.bind(this);\n this.setQuote = this.setQuote.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n }\n\n public abstract getState(): ComposerState;\n\n public setText(text: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setText(text);\n }\n\n public setRunConfig(runConfig: RunConfig) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setRunConfig(runConfig);\n }\n\n public addAttachment(fileOrAttachment: File | CreateAttachment) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.addAttachment(fileOrAttachment);\n }\n\n public reset() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.reset();\n }\n\n public clearAttachments() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.clearAttachments();\n }\n\n public send(options?: SendOptions) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.send(options);\n }\n\n public cancel() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.cancel();\n }\n\n public steerQueueItem(queueItemId: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.steerQueueItem(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.removeQueueItem(queueItemId);\n }\n\n public setRole(role: MessageRole) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setRole(role);\n }\n\n public startDictation() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.startDictation();\n }\n\n public stopDictation() {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.stopDictation();\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n const core = this._core.getState();\n if (!core) throw new Error(\"Composer is not available\");\n core.setQuote(quote);\n }\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ComposerRuntimeEventType>\n >();\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ComposerRuntimeEventType>({\n event,\n binding: this._core,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n\n public abstract getAttachmentByIndex(idx: number): AttachmentRuntime;\n}\n\nexport type ThreadComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"thread\" };\n readonly type: \"thread\";\n getState(): ThreadComposerState;\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"thread-composer\" };\n};\n\nexport class ThreadComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements ThreadComposerRuntime\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & {\n composerSource: \"thread\";\n };\n }\n\n public get type() {\n return \"thread\" as const;\n }\n\n private _getState;\n\n constructor(core: ThreadComposerRuntimeCoreBinding) {\n const stateBinding = new LazyMemoizeSubject({\n path: core.path,\n getState: () => getThreadComposerState(core.getState()),\n subscribe: (callback) => core.subscribe(callback),\n });\n super({\n path: core.path,\n getState: () => core.getState(),\n subscribe: (callback) => stateBinding.subscribe(callback),\n });\n this._getState = stateBinding.getState.bind(stateBinding);\n\n this.__internal_bindMethods();\n }\n\n public override getState(): ThreadComposerState {\n return this._getState();\n }\n\n public getAttachmentByIndex(idx: number) {\n return new ThreadComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"thread-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: `${this.path.ref}.attachments[${idx}]`,\n },\n getState: () => {\n const attachments = this.getState().attachments;\n const attachment = attachments[idx];\n if (!attachment) return SKIP_UPDATE;\n\n return {\n ...attachment,\n source: \"thread-composer\",\n } satisfies AttachmentState & { source: \"thread-composer\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n\nexport type EditComposerRuntime = Omit<\n ComposerRuntime,\n \"getState\" | \"getAttachmentByIndex\"\n> & {\n readonly path: ComposerRuntimePath & { composerSource: \"edit\" };\n readonly type: \"edit\";\n\n getState(): EditComposerState;\n beginEdit(): void;\n\n getAttachmentByIndex(\n idx: number,\n ): AttachmentRuntime & { source: \"edit-composer\" };\n};\n\nexport class EditComposerRuntimeImpl\n extends ComposerRuntimeImpl\n implements EditComposerRuntime\n{\n public override get path() {\n return this._core.path as ComposerRuntimePath & { composerSource: \"edit\" };\n }\n\n public get type() {\n return \"edit\" as const;\n }\n\n private _getState;\n constructor(\n core: EditComposerRuntimeCoreBinding,\n private _beginEdit: () => void,\n ) {\n const stateBinding = new LazyMemoizeSubject({\n path: core.path,\n getState: () => getEditComposerState(core.getState()),\n subscribe: (callback) => core.subscribe(callback),\n });\n\n super({\n path: core.path,\n getState: () => core.getState(),\n subscribe: (callback) => stateBinding.subscribe(callback),\n });\n\n this._getState = stateBinding.getState.bind(stateBinding);\n\n this.__internal_bindMethods();\n }\n\n public override __internal_bindMethods() {\n super.__internal_bindMethods();\n this.beginEdit = this.beginEdit.bind(this);\n }\n\n public override getState(): EditComposerState {\n return this._getState();\n }\n\n public beginEdit() {\n this._beginEdit();\n }\n\n public getAttachmentByIndex(idx: number) {\n return new EditComposerAttachmentRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ...this.path,\n attachmentSource: \"edit-composer\",\n attachmentSelector: { type: \"index\", index: idx },\n ref: `${this.path.ref}.attachments[${idx}]`,\n },\n getState: () => {\n const attachments = this.getState().attachments;\n const attachment = attachments[idx];\n if (!attachment) return SKIP_UPDATE;\n\n return {\n ...attachment,\n source: \"edit-composer\",\n } satisfies AttachmentState & { source: \"edit-composer\" };\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n"],"mappings":";;;AAmFA,MAAM,cAAc,OAAO,OAAO,CAAC,CAAC;AACpC,MAAM,eAAe,OAAO,OAAO,CAAC,CAAC;AACrC,MAAM,0BACJ,YACwB;CACxB,OAAO,OAAO,OAAO;EACnB,MAAM;EAEN,WAAW,SAAS,aAAa;EACjC,WAAW,SAAS,aAAa;EACjC,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,WAAW;EAE7B,aAAa,SAAS,eAAe;EACrC,MAAM,SAAS,QAAQ;EACvB,MAAM,SAAS,QAAQ;EACvB,WAAW,SAAS,aAAa;EACjC,kBAAkB,SAAS,oBAAoB;EAC/C,WAAW,SAAS;EACpB,OAAO,SAAS;EAChB,OAAO,SAAS,SAAS;EAEzB,OAAO,SAAS,QAAQ;CAC1B,CAAC;AACH;AAEA,MAAM,wBACJ,YACsB;CACtB,OAAO,OAAO,OAAO;EACnB,MAAM;EAEN,WAAW,SAAS,aAAa;EACjC,WAAW,SAAS,aAAa;EACjC,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,WAAW;EAE7B,MAAM,SAAS,QAAQ;EACvB,MAAM,SAAS,QAAQ;EACvB,aAAa,SAAS,eAAe;EACrC,WAAW,SAAS,aAAa;EACjC,kBAAkB,SAAS,oBAAoB;EAC/C,WAAW,SAAS;EACpB,OAAO,SAAS;EAChB,OAAO,SAAS,SAAS;EAEzB,UAAU,SAAS,YAAY;EAC/B,UAAU,SAAS,YAAY;EAE/B,OAAO,SAAS,QAAQ;CAC1B,CAAC;AACH;AAgHA,IAAsB,sBAAtB,MAAqE;CAO7C;CANtB,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM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":"message-part-runtime.js","names":[],"sources":["../../../src/runtime/api/message-part-runtime.ts"],"sourcesContent":["import type {\n ThreadAssistantMessagePart,\n ThreadUserMessagePart,\n ToolCallMessagePartStatus,\n} from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { MessagePartStatus } from \"../../types/message\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport type { ThreadRuntimeCoreBinding } from \"./thread-runtime\";\nimport type { MessageStateBinding } from \"./bindings\";\nimport type { MessagePartRuntimePath } from \"./paths\";\nimport { ToolResponse } from \"assistant-stream\";\n\nexport type MessagePartState = (\n | ThreadUserMessagePart\n | ThreadAssistantMessagePart\n) & {\n readonly status: MessagePartStatus | ToolCallMessagePartStatus;\n};\n\ntype MessagePartSnapshotBinding = SubscribableWithState<\n MessagePartState,\n MessagePartRuntimePath\n>;\n\nexport type MessagePartRuntime = {\n addToolResult(result: any | ToolResponse<any>): void;\n resumeToolCall(payload: unknown): void;\n respondToToolApproval(response: { approved: boolean; reason?: string }): void;\n\n readonly path: MessagePartRuntimePath;\n getState(): MessagePartState;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport class MessagePartRuntimeImpl implements MessagePartRuntime {\n public get path() {\n return this.contentBinding.path;\n }\n\n constructor(\n private contentBinding: MessagePartSnapshotBinding,\n private messageApi?: MessageStateBinding,\n private threadApi?: ThreadRuntimeCoreBinding,\n ) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.addToolResult = this.addToolResult.bind(this);\n this.resumeToolCall = this.resumeToolCall.bind(this);\n this.respondToToolApproval = this.respondToToolApproval.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n\n public getState() {\n return this.contentBinding.getState();\n }\n\n public addToolResult(result: any | ToolResponse<any>) {\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Message part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\"Tried to add tool result to non-tool message part\");\n\n if (!this.messageApi)\n throw new Error(\n \"Message API is not available. This is likely a bug in assistant-ui.\",\n );\n if (!this.threadApi) throw new Error(\"Thread API is not available\");\n\n const message = this.messageApi.getState();\n if (!message) throw new Error(\"Message is not available\");\n\n const toolName = state.toolName;\n const toolCallId = state.toolCallId;\n\n const response = ToolResponse.toResponse(result);\n this.threadApi.getState().addToolResult({\n messageId: message.id,\n toolName,\n toolCallId,\n result: response.result,\n artifact: response.artifact,\n isError: response.isError,\n });\n }\n\n public resumeToolCall(payload: unknown) {\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Message part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\"Tried to resume tool call on non-tool message part\");\n\n if (!this.threadApi) throw new Error(\"Thread API is not available\");\n\n const toolCallId = state.toolCallId;\n this.threadApi.getState().resumeToolCall({\n toolCallId,\n payload,\n });\n }\n\n public respondToToolApproval(response: {\n approved: boolean;\n reason?: string;\n }) {\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Message part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\n \"Tried to respond to tool approval on non-tool message part\",\n );\n\n if (!state.approval || state.approval.approved !== undefined)\n throw new Error(\"Tool call has no pending approval\");\n\n if (!this.threadApi) throw new Error(\"Thread API is not available\");\n\n this.threadApi.getState().respondToToolApproval({\n approvalId: state.approval.id,\n approved: response.approved,\n ...(response.reason != null && { reason: response.reason }),\n });\n }\n\n public subscribe(callback: () => void) {\n return this.contentBinding.subscribe(callback);\n }\n}\n"],"mappings":";;AAmCA,IAAa,yBAAb,MAAkE;CAMtD;CACA;CACA;CAPV,IAAW,OAAO;EAChB,OAAO,KAAK,eAAe;CAC7B;CAEA,YACE,gBACA,YACA,WACA;EAHQ,KAAA,iBAAA;EACA,KAAA,aAAA;EACA,KAAA,YAAA;EAER,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,gBAAgB,KAAK,cAAc,KAAK,IAAI;EACjD,KAAK,iBAAiB,KAAK,eAAe,KAAK,IAAI;EACnD,KAAK,wBAAwB,KAAK,sBAAsB,KAAK,IAAI;EACjE,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;EACvC,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;CAC3C;CAEA,WAAkB;EAChB,OAAO,KAAK,eAAe,SAAS;CACtC;CAEA,cAAqB,QAAiC;EACpD,MAAM,QAAQ,KAAK,eAAe,SAAS;EAC3C,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,+BAA+B;EAE3D,IAAI,MAAM,SAAS,aACjB,MAAM,IAAI,MAAM,mDAAmD;EAErE,IAAI,CAAC,KAAK,YACR,MAAM,IAAI,MACR,qEACF;EACF,IAAI,CAAC,KAAK,WAAW,MAAM,IAAI,MAAM,6BAA6B;EAElE,MAAM,UAAU,KAAK,WAAW,SAAS;EACzC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,0BAA0B;EAExD,MAAM,WAAW,MAAM;EACvB,MAAM,aAAa,MAAM;EAEzB,MAAM,WAAW,aAAa,WAAW,MAAM;EAC/C,KAAK,UAAU,SAAS,
|
|
1
|
+
{"version":3,"file":"message-part-runtime.js","names":[],"sources":["../../../src/runtime/api/message-part-runtime.ts"],"sourcesContent":["import type {\n ThreadAssistantMessagePart,\n ThreadUserMessagePart,\n ToolCallMessagePartStatus,\n} from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { MessagePartStatus } from \"../../types/message\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport type { ThreadRuntimeCoreBinding } from \"./thread-runtime\";\nimport type { MessageStateBinding } from \"./bindings\";\nimport type { MessagePartRuntimePath } from \"./paths\";\nimport { ToolResponse } from \"assistant-stream\";\n\nexport type MessagePartState = (\n | ThreadUserMessagePart\n | ThreadAssistantMessagePart\n) & {\n readonly status: MessagePartStatus | ToolCallMessagePartStatus;\n};\n\ntype MessagePartSnapshotBinding = SubscribableWithState<\n MessagePartState,\n MessagePartRuntimePath\n>;\n\nexport type MessagePartRuntime = {\n addToolResult(result: any | ToolResponse<any>): void;\n resumeToolCall(payload: unknown): void;\n respondToToolApproval(response: { approved: boolean; reason?: string }): void;\n\n readonly path: MessagePartRuntimePath;\n getState(): MessagePartState;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport class MessagePartRuntimeImpl implements MessagePartRuntime {\n public get path() {\n return this.contentBinding.path;\n }\n\n constructor(\n private contentBinding: MessagePartSnapshotBinding,\n private messageApi?: MessageStateBinding,\n private threadApi?: ThreadRuntimeCoreBinding,\n ) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.addToolResult = this.addToolResult.bind(this);\n this.resumeToolCall = this.resumeToolCall.bind(this);\n this.respondToToolApproval = this.respondToToolApproval.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n\n public getState() {\n return this.contentBinding.getState();\n }\n\n public addToolResult(result: any | ToolResponse<any>) {\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Message part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\"Tried to add tool result to non-tool message part\");\n\n if (!this.messageApi)\n throw new Error(\n \"Message API is not available. This is likely a bug in assistant-ui.\",\n );\n if (!this.threadApi) throw new Error(\"Thread API is not available\");\n\n const message = this.messageApi.getState();\n if (!message) throw new Error(\"Message is not available\");\n\n const toolName = state.toolName;\n const toolCallId = state.toolCallId;\n\n const response = ToolResponse.toResponse(result);\n this.threadApi.getState().addToolResult({\n messageId: message.id,\n toolName,\n toolCallId,\n result: response.result,\n artifact: response.artifact,\n isError: response.isError,\n });\n }\n\n public resumeToolCall(payload: unknown) {\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Message part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\"Tried to resume tool call on non-tool message part\");\n\n if (!this.threadApi) throw new Error(\"Thread API is not available\");\n\n const toolCallId = state.toolCallId;\n this.threadApi.getState().resumeToolCall({\n toolCallId,\n payload,\n });\n }\n\n public respondToToolApproval(response: {\n approved: boolean;\n reason?: string;\n }) {\n const state = this.contentBinding.getState();\n if (!state) throw new Error(\"Message part is not available\");\n\n if (state.type !== \"tool-call\")\n throw new Error(\n \"Tried to respond to tool approval on non-tool message part\",\n );\n\n if (!state.approval || state.approval.approved !== undefined)\n throw new Error(\"Tool call has no pending approval\");\n\n if (!this.threadApi) throw new Error(\"Thread API is not available\");\n\n this.threadApi.getState().respondToToolApproval({\n approvalId: state.approval.id,\n approved: response.approved,\n ...(response.reason != null && { reason: response.reason }),\n });\n }\n\n public subscribe(callback: () => void) {\n return this.contentBinding.subscribe(callback);\n }\n}\n"],"mappings":";;AAmCA,IAAa,yBAAb,MAAkE;CAMtD;CACA;CACA;CAPV,IAAW,OAAO;EAChB,OAAO,KAAK,eAAe;CAC7B;CAEA,YACE,gBACA,YACA,WACA;EAHQ,KAAA,iBAAA;EACA,KAAA,aAAA;EACA,KAAA,YAAA;EAER,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,gBAAgB,KAAK,cAAc,KAAK,IAAI;EACjD,KAAK,iBAAiB,KAAK,eAAe,KAAK,IAAI;EACnD,KAAK,wBAAwB,KAAK,sBAAsB,KAAK,IAAI;EACjE,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;EACvC,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;CAC3C;CAEA,WAAkB;EAChB,OAAO,KAAK,eAAe,SAAS;CACtC;CAEA,cAAqB,QAAiC;EACpD,MAAM,QAAQ,KAAK,eAAe,SAAS;EAC3C,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,+BAA+B;EAE3D,IAAI,MAAM,SAAS,aACjB,MAAM,IAAI,MAAM,mDAAmD;EAErE,IAAI,CAAC,KAAK,YACR,MAAM,IAAI,MACR,qEACF;EACF,IAAI,CAAC,KAAK,WAAW,MAAM,IAAI,MAAM,6BAA6B;EAElE,MAAM,UAAU,KAAK,WAAW,SAAS;EACzC,IAAI,CAAC,SAAS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ShallowMemoizeSubject } from "../../subscribable/subscribable.js";
|
|
3
2
|
import { getThreadMessageText } from "../../utils/text.js";
|
|
3
|
+
import { NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "../../subscribable/subscribable.js";
|
|
4
4
|
import { MessageAttachmentRuntimeImpl } from "./attachment-runtime.js";
|
|
5
5
|
import { EditComposerRuntimeImpl } from "./composer-runtime.js";
|
|
6
6
|
import { MessagePartRuntimeImpl } from "./message-part-runtime.js";
|