@assistant-ui/core 0.3.13 → 0.3.14
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/speech.d.ts.map +1 -1
- package/dist/adapters/speech.js +9 -15
- package/dist/adapters/speech.js.map +1 -1
- package/dist/adapters/thread-history.d.ts +2 -0
- package/dist/adapters/thread-history.d.ts.map +1 -1
- package/dist/adapters/voice.d.ts.map +1 -1
- package/dist/adapters/voice.js +27 -15
- package/dist/adapters/voice.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +6 -6
- package/dist/model-context/frame/host.d.ts.map +1 -1
- package/dist/model-context/frame/host.js +2 -1
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/registry.d.ts.map +1 -1
- package/dist/model-context/registry.js +16 -4
- package/dist/model-context/registry.js.map +1 -1
- package/dist/react/RuntimeAdapter.d.ts +8 -1
- package/dist/react/RuntimeAdapter.d.ts.map +1 -1
- package/dist/react/RuntimeAdapter.js +23 -18
- package/dist/react/RuntimeAdapter.js.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js +28 -12
- package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
- package/dist/react/client/AdaptedRemoteThread.d.ts +11 -0
- package/dist/react/client/AdaptedRemoteThread.d.ts.map +1 -0
- package/dist/react/client/AdaptedRemoteThread.js +27 -0
- package/dist/react/client/AdaptedRemoteThread.js.map +1 -0
- package/dist/react/client/InMemoryThreadList.d.ts +19 -0
- package/dist/react/client/InMemoryThreadList.d.ts.map +1 -0
- package/dist/react/client/InMemoryThreadList.js +418 -0
- package/dist/react/client/InMemoryThreadList.js.map +1 -0
- package/dist/react/client/Interactables.d.ts.map +1 -1
- package/dist/react/client/Interactables.js +159 -102
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/RemoteThreadList.d.ts +34 -0
- package/dist/react/client/RemoteThreadList.d.ts.map +1 -0
- package/dist/react/client/RemoteThreadList.js +826 -0
- package/dist/react/client/RemoteThreadList.js.map +1 -0
- package/dist/react/client/Tools.d.ts.map +1 -1
- package/dist/react/client/Tools.js +38 -27
- package/dist/react/client/Tools.js.map +1 -1
- package/dist/react/index.d.ts +7 -2
- package/dist/react/index.js +5 -2
- package/dist/react/interactables-legacy/Interactables.d.ts.map +1 -1
- package/dist/react/interactables-legacy/Interactables.js +145 -110
- package/dist/react/interactables-legacy/Interactables.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarCopy.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useActionBarCopy.js +13 -18
- package/dist/react/primitive-hooks/useActionBarCopy.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarEdit.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useActionBarEdit.js +2 -4
- package/dist/react/primitive-hooks/useActionBarEdit.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarReload.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useActionBarReload.js +2 -4
- package/dist/react/primitive-hooks/useActionBarReload.js.map +1 -1
- package/dist/react/primitive-hooks/useBranchPickerNext.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useBranchPickerNext.js +2 -6
- package/dist/react/primitive-hooks/useBranchPickerNext.js.map +1 -1
- package/dist/react/primitive-hooks/useBranchPickerPrevious.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useBranchPickerPrevious.js +2 -6
- package/dist/react/primitive-hooks/useBranchPickerPrevious.js.map +1 -1
- package/dist/react/primitive-hooks/useComposerCancel.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useComposerCancel.js +2 -4
- package/dist/react/primitive-hooks/useComposerCancel.js.map +1 -1
- package/dist/react/primitive-hooks/useComposerSend.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useComposerSend.js +2 -4
- package/dist/react/primitive-hooks/useComposerSend.js.map +1 -1
- package/dist/react/primitive-hooks/useSuggestionTrigger.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useSuggestionTrigger.js +6 -2
- package/dist/react/primitive-hooks/useSuggestionTrigger.js.map +1 -1
- package/dist/react/primitives/message/MessageParts.d.ts +13 -0
- package/dist/react/primitives/message/MessageParts.d.ts.map +1 -1
- package/dist/react/primitives/message/MessageParts.js.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.d.ts.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/runtimes/RemoteThreadListHookInstanceManager.d.ts +22 -10
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +109 -71
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +8 -2
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +40 -13
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadResource.d.ts +30 -0
- package/dist/react/runtimes/RemoteThreadResource.d.ts.map +1 -0
- package/dist/react/runtimes/RemoteThreadResource.js +134 -0
- package/dist/react/runtimes/RemoteThreadResource.js.map +1 -0
- package/dist/react/runtimes/RuntimeAdapterProvider.d.ts +3 -10
- package/dist/react/runtimes/RuntimeAdapterProvider.d.ts.map +1 -1
- package/dist/react/runtimes/RuntimeAdapterProvider.js +3 -6
- package/dist/react/runtimes/RuntimeAdapterProvider.js.map +1 -1
- package/dist/react/runtimes/assistant-transport/commandQueue.d.ts +17 -0
- package/dist/react/runtimes/assistant-transport/commandQueue.d.ts.map +1 -0
- package/dist/react/runtimes/assistant-transport/commandQueue.js +55 -0
- package/dist/react/runtimes/assistant-transport/commandQueue.js.map +1 -0
- package/dist/react/runtimes/assistant-transport/replayBoundaryStream.d.ts +11 -0
- package/dist/react/runtimes/assistant-transport/replayBoundaryStream.d.ts.map +1 -0
- package/dist/react/runtimes/assistant-transport/replayBoundaryStream.js +165 -0
- package/dist/react/runtimes/assistant-transport/replayBoundaryStream.js.map +1 -0
- package/dist/react/runtimes/assistant-transport/runManager.d.ts +15 -0
- package/dist/react/runtimes/assistant-transport/runManager.d.ts.map +1 -0
- package/dist/react/runtimes/assistant-transport/runManager.js +86 -0
- package/dist/react/runtimes/assistant-transport/runManager.js.map +1 -0
- package/dist/react/runtimes/assistant-transport/types.d.ts +130 -0
- package/dist/react/runtimes/assistant-transport/types.d.ts.map +1 -0
- package/dist/react/runtimes/assistant-transport/types.js +0 -0
- package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.d.ts +14 -0
- package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.d.ts.map +1 -0
- package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.js +296 -0
- package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.js.map +1 -0
- package/dist/react/runtimes/assistant-transport/useConvertedState.d.ts +7 -0
- package/dist/react/runtimes/assistant-transport/useConvertedState.d.ts.map +1 -0
- package/dist/react/runtimes/assistant-transport/useConvertedState.js +25 -0
- package/dist/react/runtimes/assistant-transport/useConvertedState.js.map +1 -0
- package/dist/react/runtimes/assistant-transport/useLatestRef.d.ts +7 -0
- package/dist/react/runtimes/assistant-transport/useLatestRef.d.ts.map +1 -0
- package/dist/react/runtimes/assistant-transport/useLatestRef.js +27 -0
- package/dist/react/runtimes/assistant-transport/useLatestRef.js.map +1 -0
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +39 -13
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts +2 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js +3 -3
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.d.ts +4 -0
- package/dist/react/runtimes/cloud/auiV0.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.js +7 -0
- package/dist/react/runtimes/cloud/auiV0.js.map +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +22 -12
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListRuntime.d.ts +16 -0
- package/dist/react/runtimes/cloud/useCloudThreadListRuntime.d.ts.map +1 -0
- package/dist/react/runtimes/cloud/useCloudThreadListRuntime.js +36 -0
- package/dist/react/runtimes/cloud/useCloudThreadListRuntime.js.map +1 -0
- package/dist/react/runtimes/external-message-converter.js +14 -14
- package/dist/react/runtimes/external-message-converter.js.map +1 -1
- package/dist/react/runtimes/useExternalStoreRuntime.d.ts.map +1 -1
- package/dist/react/runtimes/useExternalStoreRuntime.js +44 -28
- package/dist/react/runtimes/useExternalStoreRuntime.js.map +1 -1
- package/dist/react/runtimes/useExternalStoreSharedOptions.js.map +1 -1
- package/dist/react/runtimes/useLocalRuntime.js +1 -1
- package/dist/react/runtimes/useRuntimeAdapters.d.ts +9 -0
- package/dist/react/runtimes/useRuntimeAdapters.d.ts.map +1 -0
- package/dist/react/runtimes/useRuntimeAdapters.js +20 -0
- package/dist/react/runtimes/useRuntimeAdapters.js.map +1 -0
- package/dist/runtime/api/composer-runtime.d.ts +5 -0
- package/dist/runtime/api/composer-runtime.d.ts.map +1 -1
- package/dist/runtime/api/composer-runtime.js.map +1 -1
- package/dist/runtime/api/message-runtime.js +1 -1
- package/dist/runtime/api/thread-list-runtime.d.ts +1 -0
- package/dist/runtime/api/thread-list-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-runtime.js +4 -2
- package/dist/runtime/api/thread-list-runtime.js.map +1 -1
- package/dist/runtime/api/thread-runtime.d.ts +12 -2
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js +8 -2
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +8 -7
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.d.ts +1 -0
- package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js +3 -3
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.d.ts +0 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.js +10 -4
- package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
- package/dist/runtime/interfaces/thread-runtime-core.d.ts +6 -0
- package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/internal.js +5 -5
- package/dist/runtime/queue/message-queue.d.ts.map +1 -1
- package/dist/runtime/queue/message-queue.js +2 -1
- package/dist/runtime/queue/message-queue.js.map +1 -1
- package/dist/runtime/utils/thread-runtime-lifecycle.d.ts +8 -0
- package/dist/runtime/utils/thread-runtime-lifecycle.d.ts.map +1 -0
- package/dist/runtime/utils/thread-runtime-lifecycle.js +11 -0
- package/dist/runtime/utils/thread-runtime-lifecycle.js.map +1 -0
- package/dist/runtimes/external-store/external-store-shared-options.js.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js +4 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +8 -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 +35 -13
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/internal.d.ts +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts +3 -0
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +53 -13
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts +1 -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.js +3 -0
- package/dist/runtimes/remote-thread-list/empty-thread-core.js.map +1 -1
- package/dist/runtimes/remote-thread-list/types.d.ts +29 -1
- package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts +1 -12
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +67 -38
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
- package/dist/store/clients/suggestions.js +2 -2
- package/dist/store/clients/suggestions.js.map +1 -1
- package/dist/store/clients/thread-selection-events.d.ts +10 -0
- package/dist/store/clients/thread-selection-events.d.ts.map +1 -0
- package/dist/store/clients/thread-selection-events.js +40 -0
- package/dist/store/clients/thread-selection-events.js.map +1 -0
- package/dist/store/env.d.ts +5 -0
- package/dist/store/env.d.ts.map +1 -0
- package/dist/store/env.js +12 -0
- package/dist/store/env.js.map +1 -0
- package/dist/store/index.d.ts +5 -3
- package/dist/store/index.js +4 -2
- package/dist/store/internal.d.ts +4 -1
- package/dist/store/internal.js +4 -1
- package/dist/store/primitive-predicates.d.ts +19 -0
- package/dist/store/primitive-predicates.d.ts.map +1 -0
- package/dist/store/primitive-predicates.js +19 -0
- package/dist/store/primitive-predicates.js.map +1 -0
- package/dist/store/runtime-clients/attachment-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/attachment-runtime-client.js +18 -11
- package/dist/store/runtime-clients/attachment-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/handle-runtime-action.d.ts +5 -0
- package/dist/store/runtime-clients/handle-runtime-action.d.ts.map +1 -0
- package/dist/store/runtime-clients/handle-runtime-action.js +12 -0
- package/dist/store/runtime-clients/handle-runtime-action.js.map +1 -0
- package/dist/store/runtime-clients/handle-thread-list-action.d.ts +5 -0
- package/dist/store/runtime-clients/handle-thread-list-action.d.ts.map +1 -0
- package/dist/store/runtime-clients/handle-thread-list-action.js +7 -0
- package/dist/store/runtime-clients/handle-thread-list-action.js.map +1 -0
- 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 +62 -29
- 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 +5 -6
- package/dist/store/runtime-clients/thread-list-runtime-client.js.map +1 -1
- package/dist/store/scopes/composer.d.ts +9 -4
- package/dist/store/scopes/composer.d.ts.map +1 -1
- package/dist/store/scopes/thread-list-item.d.ts +7 -6
- package/dist/store/scopes/thread-list-item.d.ts.map +1 -1
- package/dist/store/scopes/thread.d.ts +8 -7
- package/dist/store/scopes/thread.d.ts.map +1 -1
- package/dist/store/scopes/threads.d.ts +17 -1
- package/dist/store/scopes/threads.d.ts.map +1 -1
- package/dist/subscribable/subscribable.d.ts +2 -1
- package/dist/subscribable/subscribable.d.ts.map +1 -1
- package/dist/subscribable/subscribable.js +23 -18
- package/dist/subscribable/subscribable.js.map +1 -1
- package/dist/utils/composite-context-provider.d.ts +1 -0
- package/dist/utils/composite-context-provider.d.ts.map +1 -1
- package/dist/utils/composite-context-provider.js +25 -9
- package/dist/utils/composite-context-provider.js.map +1 -1
- package/dist/utils/notify-event-listeners.d.ts +2 -2
- package/dist/utils/notify-event-listeners.d.ts.map +1 -1
- package/dist/utils/notify-event-listeners.js +2 -2
- package/dist/utils/notify-event-listeners.js.map +1 -1
- package/package.json +7 -7
- package/src/adapters/speech.test.ts +118 -1
- package/src/adapters/speech.ts +21 -22
- package/src/adapters/thread-history.ts +2 -0
- package/src/adapters/voice.test.ts +69 -0
- package/src/adapters/voice.ts +27 -27
- package/src/index.ts +1 -0
- package/src/model-context/frame/host.test.ts +23 -0
- package/src/model-context/frame/host.ts +2 -1
- package/src/model-context/registry.test.ts +131 -0
- package/src/model-context/registry.ts +16 -6
- package/src/react/RuntimeAdapter.test.ts +2 -0
- package/src/react/RuntimeAdapter.ts +20 -8
- package/src/react/adapters/LocalStorageThreadListAdapter.tsx +34 -17
- package/src/react/client/AdaptedRemoteThread.ts +41 -0
- package/src/react/client/InMemoryThreadList.test.tsx +148 -0
- package/src/react/client/InMemoryThreadList.ts +290 -0
- package/src/react/client/Interactables.test.ts +326 -2
- package/src/react/client/Interactables.ts +227 -110
- package/src/react/client/RemoteThreadList.test.ts +1026 -0
- package/src/react/client/RemoteThreadList.ts +1067 -0
- package/src/react/client/Tools.ts +36 -29
- package/src/react/index.ts +13 -0
- package/src/react/interactables-legacy/Interactables.test.ts +317 -0
- package/src/react/interactables-legacy/Interactables.ts +204 -128
- package/src/react/primitive-hooks/useActionBarCopy.ts +2 -7
- package/src/react/primitive-hooks/useActionBarEdit.ts +2 -1
- package/src/react/primitive-hooks/useActionBarReload.ts +2 -6
- package/src/react/primitive-hooks/useBranchPickerNext.ts +2 -7
- package/src/react/primitive-hooks/useBranchPickerPrevious.ts +2 -7
- package/src/react/primitive-hooks/useComposerCancel.ts +2 -1
- package/src/react/primitive-hooks/useComposerSend.ts +2 -5
- package/src/react/primitive-hooks/useSuggestionTrigger.test.ts +11 -0
- package/src/react/primitive-hooks/useSuggestionTrigger.ts +4 -5
- package/src/react/primitives/message/MessageParts.tsx +0 -1
- package/src/react/primitives/thread/ThreadMessages.tsx +2 -1
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.retry.test.tsx +116 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.running.test.tsx +1 -1
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.test.tsx +57 -6
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.title.test.tsx +272 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +159 -124
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +59 -20
- package/src/react/runtimes/RemoteThreadResource.test.ts +141 -0
- package/src/react/runtimes/RemoteThreadResource.ts +231 -0
- package/src/react/runtimes/RuntimeAdapterProvider.tsx +8 -20
- package/src/react/runtimes/assistant-transport/commandQueue.ts +68 -0
- package/src/react/runtimes/assistant-transport/replayBoundaryStream.test.ts +455 -0
- package/src/react/runtimes/assistant-transport/replayBoundaryStream.ts +172 -0
- package/src/react/runtimes/assistant-transport/runManager.ts +124 -0
- package/src/react/runtimes/assistant-transport/transport-delivery.test.tsx +79 -0
- package/src/react/runtimes/assistant-transport/transport-parentid.test.tsx +97 -0
- package/src/react/runtimes/assistant-transport/transport-scheduling.test.ts +414 -0
- package/src/react/runtimes/assistant-transport/types.ts +170 -0
- package/src/react/runtimes/assistant-transport/useAssistantTransport.spec.md +141 -0
- package/src/react/runtimes/assistant-transport/useAssistantTransportRuntime.test.tsx +625 -0
- package/src/react/runtimes/assistant-transport/useAssistantTransportRuntime.ts +481 -0
- package/src/react/runtimes/assistant-transport/useConvertedState.ts +20 -0
- package/src/react/runtimes/assistant-transport/useLatestRef.ts +9 -0
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +131 -6
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +61 -15
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.ts +6 -4
- package/src/react/runtimes/cloud/auiV0.ts +17 -1
- package/src/react/runtimes/cloud/useCloudThreadListAdapter.tsx +36 -21
- package/src/react/runtimes/cloud/useCloudThreadListRuntime.test.tsx +56 -0
- package/src/react/runtimes/cloud/useCloudThreadListRuntime.ts +31 -0
- package/src/react/runtimes/external-message-converter.test.ts +143 -0
- package/src/react/runtimes/external-message-converter.ts +41 -41
- package/src/react/runtimes/remote-thread-hook-on-tap.test.ts +58 -0
- package/src/react/runtimes/useExternalStoreRuntime.lifecycle.test.tsx +83 -0
- package/src/react/runtimes/useExternalStoreRuntime.suggestions.test.tsx +13 -3
- package/src/react/runtimes/useExternalStoreRuntime.ts +7 -0
- package/src/react/runtimes/useExternalStoreSharedOptions.ts +3 -1
- package/src/react/runtimes/useLocalRuntime.test.tsx +130 -4
- package/src/react/runtimes/useRuntimeAdapters.test.tsx +62 -0
- package/src/react/runtimes/useRuntimeAdapters.ts +28 -0
- package/src/runtime/api/composer-runtime.ts +5 -0
- package/src/runtime/api/thread-list-runtime.ts +3 -1
- package/src/runtime/api/thread-runtime.ts +20 -2
- package/src/runtime/base/base-composer-runtime-core.ts +6 -5
- package/src/runtime/base/base-thread-runtime-core.test.ts +191 -0
- package/src/runtime/base/base-thread-runtime-core.ts +11 -2
- package/src/runtime/base/default-thread-composer-runtime-core.ts +12 -4
- package/src/runtime/interfaces/thread-runtime-core.ts +6 -0
- package/src/runtime/queue/message-queue.ts +2 -1
- package/src/runtime/utils/thread-runtime-lifecycle.ts +18 -0
- package/src/runtimes/external-store/external-store-shared-options.ts +3 -1
- package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +4 -1
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +99 -34
- package/src/runtimes/local/local-thread-runtime-core.test.ts +373 -4
- package/src/runtimes/local/local-thread-runtime-core.ts +79 -14
- package/src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts +4 -0
- package/src/runtimes/remote-thread-list/empty-thread-core.ts +4 -0
- package/src/runtimes/remote-thread-list/types.ts +30 -0
- package/src/runtimes/tool-invocations/EDGE_CASES.md +17 -6
- package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +243 -0
- package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +127 -61
- package/src/store/clients/model-context-client.test.ts +16 -8
- package/src/store/clients/suggestions.ts +2 -2
- package/src/store/clients/thread-selection-events.ts +21 -0
- package/src/store/env.ts +11 -0
- package/src/store/index.ts +14 -1
- package/src/store/internal.ts +13 -0
- package/src/store/primitive-predicates.test.ts +184 -0
- package/src/store/primitive-predicates.ts +43 -0
- package/src/store/runtime-clients/attachment-runtime-client.test.ts +41 -0
- package/src/store/runtime-clients/attachment-runtime-client.ts +2 -1
- package/src/store/runtime-clients/handle-runtime-action.ts +11 -0
- package/src/store/runtime-clients/handle-thread-list-action.test.ts +69 -0
- package/src/store/runtime-clients/handle-thread-list-action.ts +6 -0
- package/src/store/runtime-clients/thread-list-item-runtime-client.ts +15 -7
- package/src/store/runtime-clients/thread-list-runtime-client.ts +9 -6
- package/src/store/scopes/composer.ts +9 -4
- package/src/store/scopes/thread-list-item.ts +7 -6
- package/src/store/scopes/thread.ts +8 -7
- package/src/store/scopes/threads.ts +14 -0
- package/src/subscribable/subscribable.test.ts +77 -1
- package/src/subscribable/subscribable.ts +38 -23
- package/src/tests/RemoteThreadListThreadListRuntimeCore-switchToThread-unarchive.test.ts +25 -0
- package/src/tests/auiV0Encode.test.ts +66 -0
- package/src/tests/base-composer-runtime-core-send.test.ts +30 -0
- package/src/tests/base-composer-runtime-core.test.ts +28 -0
- package/src/tests/composer-can-cancel.test.ts +101 -0
- package/src/tests/external-store-thread-list-runtime-core.test.ts +101 -0
- package/src/tests/external-store-thread-runtime-core-adapter.test.ts +191 -1
- package/src/tests/external-store-thread-runtime-core.test.ts +124 -0
- package/src/tests/interactables-toolui-migration.test.tsx +66 -0
- package/src/tests/message-queue.test.ts +28 -0
- package/src/tests/session-reset-notification.test.ts +145 -0
- package/src/tests/thread-switch-events.test.tsx +99 -1
- package/src/tests/tools-scope-migration.test.tsx +58 -0
- package/src/utils/composite-context-provider.test.ts +139 -0
- package/src/utils/composite-context-provider.ts +26 -8
- package/src/utils/notify-event-listeners.ts +10 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-list-runtime.js","names":["Unsubscribe","LazyMemoizeSubject","NestedSubscriptionSubject","SKIP_UPDATE","ShallowMemoizeSubject","ThreadListRuntimeCore","ThreadListItemRuntime","ThreadListItemRuntimeImpl","ThreadListItemState","ThreadListItemRuntimeBinding","ThreadRuntime","ThreadRuntimeCoreBinding","ThreadRuntimeImpl","RESOLVED_PROMISE","Promise","resolve","ThreadListState","mainThreadId","newThreadId","threadIds","archivedThreadIds","isLoading","isLoadingMore","hasMore","threadItems","Readonly","Record","Omit","ThreadListRuntime","getState","subscribe","callback","main","getById","threadId","mainItem","getItemById","getItemByIndex","idx","getArchivedItemByIndex","switchToThread","options","unarchive","switchToNewThread","getLoadThreadsPromise","reload","reloadMainThread","loadMore","getThreadListState","threadList","getThreadListItemState","undefined","threadData","id","remoteId","externalId","title","status","lastMessageAt","custom","isMain","isRunning","unstable_isThreadRunning","ThreadListRuntimeCoreBinding","ThreadListRuntimeImpl","_getState","_core","_runtimeFactory","binding","threadListItemBinding","constructor","stateBinding","path","bind","_mainThreadListItemRuntime","ref","threadSelector","type","getMainThreadRuntimeCore","__internal_bindMethods","JSON","stringify","getThreadRuntimeCore","index"],"sources":["../../../src/runtime/api/thread-list-runtime.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport {\n LazyMemoizeSubject,\n NestedSubscriptionSubject,\n} from \"../../subscribable/subscribable\";\nimport {\n SKIP_UPDATE,\n ShallowMemoizeSubject,\n} from \"../../subscribable/subscribable\";\nimport type { ThreadListRuntimeCore } from \"../interfaces/thread-list-runtime-core\";\nimport {\n type ThreadListItemRuntime,\n ThreadListItemRuntimeImpl,\n type ThreadListItemState,\n} from \"./thread-list-item-runtime\";\nimport {\n type ThreadListItemRuntimeBinding,\n type ThreadRuntime,\n type ThreadRuntimeCoreBinding,\n ThreadRuntimeImpl,\n} from \"./thread-runtime\";\n\nconst RESOLVED_PROMISE = Promise.resolve();\n\nexport type ThreadListState = {\n readonly mainThreadId: string;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly isLoading: boolean;\n readonly isLoadingMore: boolean;\n readonly hasMore: boolean;\n readonly threadItems: Readonly<\n Record<\n string,\n Omit<ThreadListItemState, \"isMain\" | \"threadId\" | \"isRunning\">\n >\n >;\n};\n\nexport type ThreadListRuntime = {\n getState(): ThreadListState;\n\n subscribe(callback: () => void): Unsubscribe;\n\n readonly main: ThreadRuntime;\n getById(threadId: string): ThreadRuntime;\n\n readonly mainItem: ThreadListItemRuntime;\n getItemById(threadId: string): ThreadListItemRuntime;\n getItemByIndex(idx: number): ThreadListItemRuntime;\n getArchivedItemByIndex(idx: number): ThreadListItemRuntime;\n\n switchToThread(\n threadId: string,\n options?: { unarchive?: boolean },\n ): Promise<void>;\n switchToNewThread(): Promise<void>;\n\n getLoadThreadsPromise(): Promise<void>;\n reload(): Promise<void>;\n /**\n * Refetches the open thread's remote state, for state that changed out of\n * band and so never reached the stream. When the runtime declares the\n * in-place capability (`unstable_refetchThread`), composer drafts survive,\n * existing messages stay rendered during the refetch, and the promise\n * settles with the refetch, rejecting if it fails; that runtime also owns\n * what happens to a run in progress, since this does not stop one. Runtimes\n * without the capability have their hook remounted instead, which discards\n * unsent composer input and ends any run, and the promise resolves once the\n * new runtime attaches. A thread that has not been sent yet is left alone.\n */\n reloadMainThread(): Promise<void>;\n loadMore(): Promise<void>;\n};\n\nconst getThreadListState = (\n threadList: ThreadListRuntimeCore,\n): ThreadListState => {\n return {\n mainThreadId: threadList.mainThreadId,\n newThreadId: threadList.newThreadId,\n threadIds: threadList.threadIds,\n archivedThreadIds: threadList.archivedThreadIds,\n isLoading: threadList.isLoading,\n isLoadingMore: threadList.isLoadingMore ?? false,\n hasMore: threadList.hasMore ?? false,\n threadItems: threadList.threadItems,\n };\n};\n\nconst getThreadListItemState = (\n threadList: ThreadListRuntimeCore,\n threadId: string | undefined,\n): ThreadListItemState | SKIP_UPDATE => {\n if (threadId === undefined) return SKIP_UPDATE;\n\n const threadData = threadList.getItemById(threadId);\n if (!threadData) return SKIP_UPDATE;\n return {\n id: threadData.id,\n remoteId: threadData.remoteId,\n externalId: threadData.externalId,\n title: threadData.title,\n status: threadData.status,\n lastMessageAt: threadData.lastMessageAt,\n custom: threadData.custom,\n isMain: threadData.id === threadList.mainThreadId,\n isRunning: threadList.unstable_isThreadRunning?.(threadData.id) ?? false,\n };\n};\n\nexport type ThreadListRuntimeCoreBinding = ThreadListRuntimeCore;\n\nexport class ThreadListRuntimeImpl implements ThreadListRuntime {\n private _getState;\n private _core: ThreadListRuntimeCoreBinding;\n private _runtimeFactory: new (\n binding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) => ThreadRuntime;\n\n constructor(\n _core: ThreadListRuntimeCoreBinding,\n _runtimeFactory: new (\n binding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) => ThreadRuntime = ThreadRuntimeImpl,\n ) {\n this._core = _core;\n this._runtimeFactory = _runtimeFactory;\n const stateBinding = new LazyMemoizeSubject({\n path: {},\n getState: () => getThreadListState(_core),\n subscribe: (callback) => _core.subscribe(callback),\n });\n\n this._getState = stateBinding.getState.bind(stateBinding);\n\n this._mainThreadListItemRuntime = new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `threadItems[main]`,\n threadSelector: { type: \"main\" },\n },\n getState: () => {\n return getThreadListItemState(this._core, this._core.mainThreadId);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n\n this.main = new _runtimeFactory(\n new NestedSubscriptionSubject({\n path: {\n ref: \"threads.main\",\n threadSelector: { type: \"main\" },\n },\n getState: () => _core.getMainThreadRuntimeCore(),\n subscribe: (callback) => _core.subscribe(callback),\n }),\n this._mainThreadListItemRuntime,\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.switchToThread = this.switchToThread.bind(this);\n this.switchToNewThread = this.switchToNewThread.bind(this);\n this.getLoadThreadsPromise = this.getLoadThreadsPromise.bind(this);\n this.reload = this.reload.bind(this);\n this.reloadMainThread = this.reloadMainThread.bind(this);\n this.loadMore = this.loadMore.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.getById = this.getById.bind(this);\n this.getItemById = this.getItemById.bind(this);\n this.getItemByIndex = this.getItemByIndex.bind(this);\n this.getArchivedItemByIndex = this.getArchivedItemByIndex.bind(this);\n }\n\n public switchToThread(\n threadId: string,\n options?: { unarchive?: boolean },\n ): Promise<void> {\n return this._core.switchToThread(threadId, options);\n }\n\n public switchToNewThread(): Promise<void> {\n return this._core.switchToNewThread();\n }\n\n public getLoadThreadsPromise(): Promise<void> {\n return this._core.getLoadThreadsPromise();\n }\n\n public reload(): Promise<void> {\n return this._core.reload?.() ?? RESOLVED_PROMISE;\n }\n\n public reloadMainThread(): Promise<void> {\n return this._core.reloadMainThread?.() ?? RESOLVED_PROMISE;\n }\n\n public loadMore(): Promise<void> {\n return this._core.loadMore?.() ?? RESOLVED_PROMISE;\n }\n\n public getState(): ThreadListState {\n return this._getState();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n return this._core.subscribe(callback);\n }\n\n private _mainThreadListItemRuntime;\n\n public readonly main: ThreadRuntime;\n\n public get mainItem() {\n return this._mainThreadListItemRuntime;\n }\n\n public getById(threadId: string) {\n return new this._runtimeFactory(\n new NestedSubscriptionSubject({\n path: {\n ref: `threads[threadId=${JSON.stringify(threadId)}]`,\n threadSelector: { type: \"threadId\", threadId },\n },\n getState: () => this._core.getThreadRuntimeCore(threadId),\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this.mainItem,\n );\n }\n\n public getItemByIndex(idx: number) {\n return new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `threadItems[${idx}]`,\n threadSelector: { type: \"index\", index: idx },\n },\n getState: () => {\n return getThreadListItemState(this._core, this._core.threadIds[idx]);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n\n public getArchivedItemByIndex(idx: number) {\n return new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `archivedThreadItems[${idx}]`,\n threadSelector: { type: \"archiveIndex\", index: idx },\n },\n getState: () => {\n return getThreadListItemState(\n this._core,\n this._core.archivedThreadIds[idx],\n );\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n\n public getItemById(threadId: string) {\n return new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `threadItems[threadId=${threadId}]`,\n threadSelector: { type: \"threadId\", threadId },\n },\n getState: () => {\n return getThreadListItemState(this._core, threadId);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n"],"mappings":";;;;AAsBA,MAAMa,mBAAmBC,QAAQC,QAAQ;AAsDzC,MAAMiC,sBACJC,eACoB;CACpB,OAAO;EACLhC,cAAcgC,WAAWhC;EACzBC,aAAa+B,WAAW/B;EACxBC,WAAW8B,WAAW9B;EACtBC,mBAAmB6B,WAAW7B;EAC9BC,WAAW4B,WAAW5B;EACtBC,eAAe2B,WAAW3B,iBAAiB;EAC3CC,SAAS0B,WAAW1B,WAAW;EAC/BC,aAAayB,WAAWzB;CAC1B;AACF;AAEA,MAAM0B,0BACJD,YACAf,aACsC;CACtC,IAAIA,aAA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EACxD,CAAC,GACD,KAAKmC,KACP;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"thread-list-runtime.js","names":["Unsubscribe","LazyMemoizeSubject","NestedSubscriptionSubject","SKIP_UPDATE","ShallowMemoizeSubject","ThreadListRuntimeCore","ThreadListItemRuntime","ThreadListItemRuntimeImpl","ThreadListItemState","ThreadListItemRuntimeBinding","ThreadRuntime","ThreadRuntimeCoreBinding","ThreadRuntimeImpl","RESOLVED_PROMISE","Promise","resolve","ThreadListState","mainThreadId","newThreadId","threadIds","archivedThreadIds","isLoading","isLoadingMore","hasMore","threadItems","Readonly","Record","Omit","ThreadListRuntime","getState","subscribe","callback","main","getById","threadId","mainItem","getItemById","getItemByIndex","idx","getArchivedItemByIndex","switchToThread","options","unarchive","switchToNewThread","getLoadThreadsPromise","reload","reloadMainThread","loadMore","getThreadListState","threadList","getThreadListItemState","undefined","threadData","id","remoteId","externalId","title","status","lastMessageAt","custom","isMain","isRunning","unstable_isThreadRunning","ThreadListRuntimeCoreBinding","ThreadListRuntimeImpl","_getState","_stateBinding","_core","_runtimeFactory","binding","threadListItemBinding","constructor","stateBinding","path","bind","_mainThreadListItemRuntime","ref","threadSelector","type","getMainThreadRuntimeCore","__internal_bindMethods","JSON","stringify","getThreadRuntimeCore","index"],"sources":["../../../src/runtime/api/thread-list-runtime.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport {\n LazyMemoizeSubject,\n NestedSubscriptionSubject,\n} from \"../../subscribable/subscribable\";\nimport {\n SKIP_UPDATE,\n ShallowMemoizeSubject,\n} from \"../../subscribable/subscribable\";\nimport type { ThreadListRuntimeCore } from \"../interfaces/thread-list-runtime-core\";\nimport {\n type ThreadListItemRuntime,\n ThreadListItemRuntimeImpl,\n type ThreadListItemState,\n} from \"./thread-list-item-runtime\";\nimport {\n type ThreadListItemRuntimeBinding,\n type ThreadRuntime,\n type ThreadRuntimeCoreBinding,\n ThreadRuntimeImpl,\n} from \"./thread-runtime\";\n\nconst RESOLVED_PROMISE = Promise.resolve();\n\nexport type ThreadListState = {\n readonly mainThreadId: string;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly isLoading: boolean;\n readonly isLoadingMore: boolean;\n readonly hasMore: boolean;\n readonly threadItems: Readonly<\n Record<\n string,\n Omit<ThreadListItemState, \"isMain\" | \"threadId\" | \"isRunning\">\n >\n >;\n};\n\nexport type ThreadListRuntime = {\n getState(): ThreadListState;\n\n subscribe(callback: () => void): Unsubscribe;\n\n readonly main: ThreadRuntime;\n getById(threadId: string): ThreadRuntime;\n\n readonly mainItem: ThreadListItemRuntime;\n getItemById(threadId: string): ThreadListItemRuntime;\n getItemByIndex(idx: number): ThreadListItemRuntime;\n getArchivedItemByIndex(idx: number): ThreadListItemRuntime;\n\n switchToThread(\n threadId: string,\n options?: { unarchive?: boolean },\n ): Promise<void>;\n switchToNewThread(): Promise<void>;\n\n getLoadThreadsPromise(): Promise<void>;\n reload(): Promise<void>;\n /**\n * Refetches the open thread's remote state, for state that changed out of\n * band and so never reached the stream. When the runtime declares the\n * in-place capability (`unstable_refetchThread`), composer drafts survive,\n * existing messages stay rendered during the refetch, and the promise\n * settles with the refetch, rejecting if it fails; that runtime also owns\n * what happens to a run in progress, since this does not stop one. Runtimes\n * without the capability have their hook remounted instead, which discards\n * unsent composer input and ends any run, and the promise resolves once the\n * new runtime attaches. A thread that has not been sent yet is left alone.\n */\n reloadMainThread(): Promise<void>;\n loadMore(): Promise<void>;\n};\n\nconst getThreadListState = (\n threadList: ThreadListRuntimeCore,\n): ThreadListState => {\n return {\n mainThreadId: threadList.mainThreadId,\n newThreadId: threadList.newThreadId,\n threadIds: threadList.threadIds,\n archivedThreadIds: threadList.archivedThreadIds,\n isLoading: threadList.isLoading,\n isLoadingMore: threadList.isLoadingMore ?? false,\n hasMore: threadList.hasMore ?? false,\n threadItems: threadList.threadItems,\n };\n};\n\nconst getThreadListItemState = (\n threadList: ThreadListRuntimeCore,\n threadId: string | undefined,\n): ThreadListItemState | SKIP_UPDATE => {\n if (threadId === undefined) return SKIP_UPDATE;\n\n const threadData = threadList.getItemById(threadId);\n if (!threadData) return SKIP_UPDATE;\n return {\n id: threadData.id,\n remoteId: threadData.remoteId,\n externalId: threadData.externalId,\n title: threadData.title,\n status: threadData.status,\n lastMessageAt: threadData.lastMessageAt,\n custom: threadData.custom,\n isMain: threadData.id === threadList.mainThreadId,\n isRunning: threadList.unstable_isThreadRunning?.(threadData.id) ?? false,\n };\n};\n\nexport type ThreadListRuntimeCoreBinding = ThreadListRuntimeCore;\n\nexport class ThreadListRuntimeImpl implements ThreadListRuntime {\n private _getState;\n private _stateBinding: LazyMemoizeSubject<ThreadListState, object>;\n private _core: ThreadListRuntimeCoreBinding;\n private _runtimeFactory: new (\n binding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) => ThreadRuntime;\n\n constructor(\n _core: ThreadListRuntimeCoreBinding,\n _runtimeFactory: new (\n binding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) => ThreadRuntime = ThreadRuntimeImpl,\n ) {\n this._core = _core;\n this._runtimeFactory = _runtimeFactory;\n const stateBinding = new LazyMemoizeSubject({\n path: {},\n getState: () => getThreadListState(_core),\n subscribe: (callback) => _core.subscribe(callback),\n });\n\n this._getState = stateBinding.getState.bind(stateBinding);\n this._stateBinding = stateBinding;\n\n this._mainThreadListItemRuntime = new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `threadItems[main]`,\n threadSelector: { type: \"main\" },\n },\n getState: () => {\n return getThreadListItemState(this._core, this._core.mainThreadId);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n\n this.main = new _runtimeFactory(\n new NestedSubscriptionSubject({\n path: {\n ref: \"threads.main\",\n threadSelector: { type: \"main\" },\n },\n getState: () => _core.getMainThreadRuntimeCore(),\n subscribe: (callback) => _core.subscribe(callback),\n }),\n this._mainThreadListItemRuntime,\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.switchToThread = this.switchToThread.bind(this);\n this.switchToNewThread = this.switchToNewThread.bind(this);\n this.getLoadThreadsPromise = this.getLoadThreadsPromise.bind(this);\n this.reload = this.reload.bind(this);\n this.reloadMainThread = this.reloadMainThread.bind(this);\n this.loadMore = this.loadMore.bind(this);\n this.getState = this.getState.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.getById = this.getById.bind(this);\n this.getItemById = this.getItemById.bind(this);\n this.getItemByIndex = this.getItemByIndex.bind(this);\n this.getArchivedItemByIndex = this.getArchivedItemByIndex.bind(this);\n }\n\n public switchToThread(\n threadId: string,\n options?: { unarchive?: boolean },\n ): Promise<void> {\n return this._core.switchToThread(threadId, options);\n }\n\n public switchToNewThread(): Promise<void> {\n return this._core.switchToNewThread();\n }\n\n public getLoadThreadsPromise(): Promise<void> {\n return this._core.getLoadThreadsPromise();\n }\n\n public reload(): Promise<void> {\n return this._core.reload?.() ?? RESOLVED_PROMISE;\n }\n\n public reloadMainThread(): Promise<void> {\n return this._core.reloadMainThread?.() ?? RESOLVED_PROMISE;\n }\n\n public loadMore(): Promise<void> {\n return this._core.loadMore?.() ?? RESOLVED_PROMISE;\n }\n\n public getState(): ThreadListState {\n return this._getState();\n }\n\n public subscribe(callback: () => void): Unsubscribe {\n return this._stateBinding.subscribe(callback);\n }\n\n private _mainThreadListItemRuntime;\n\n public readonly main: ThreadRuntime;\n\n public get mainItem() {\n return this._mainThreadListItemRuntime;\n }\n\n public getById(threadId: string) {\n return new this._runtimeFactory(\n new NestedSubscriptionSubject({\n path: {\n ref: `threads[threadId=${JSON.stringify(threadId)}]`,\n threadSelector: { type: \"threadId\", threadId },\n },\n getState: () => this._core.getThreadRuntimeCore(threadId),\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this.mainItem,\n );\n }\n\n public getItemByIndex(idx: number) {\n return new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `threadItems[${idx}]`,\n threadSelector: { type: \"index\", index: idx },\n },\n getState: () => {\n return getThreadListItemState(this._core, this._core.threadIds[idx]);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n\n public getArchivedItemByIndex(idx: number) {\n return new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `archivedThreadItems[${idx}]`,\n threadSelector: { type: \"archiveIndex\", index: idx },\n },\n getState: () => {\n return getThreadListItemState(\n this._core,\n this._core.archivedThreadIds[idx],\n );\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n\n public getItemById(threadId: string) {\n return new ThreadListItemRuntimeImpl(\n new ShallowMemoizeSubject({\n path: {\n ref: `threadItems[threadId=${threadId}]`,\n threadSelector: { type: \"threadId\", threadId },\n },\n getState: () => {\n return getThreadListItemState(this._core, threadId);\n },\n subscribe: (callback) => this._core.subscribe(callback),\n }),\n this._core,\n );\n }\n}\n"],"mappings":";;;;AAsBA,MAAMa,mBAAmBC,QAAQC,QAAQ;AAsDzC,MAAMiC,sBACJC,eACoB;CACpB,OAAO;EACLhC,cAAcgC,WAAWhC;EACzBC,aAAa+B,WAAW/B;EACxBC,WAAW8B,WAAW9B;EACtBC,mBAAmB6B,WAAW7B;EAC9BC,WAAW4B,WAAW5B;EACtBC,eAAe2B,WAAW3B,iBAAiB;EAC3CC,SAAS0B,WAAW1B,WAAW;EAC/BC,aAAayB,WAAWzB;CAC1B;AACF;AAEA,MAAM0B,0BACJD,YACAf,aACsC;CACtC,IAAIA,aAAaiB,KAAAA,GAAW,OAAOhD;CAEnC,MAAMiD,aAAaH,WAAWb,YAAYF,QAAQ;CAClD,IAAI,CAACkB,YAAY,OAAOjD;CACxB,OAAO;EACLkD,IAAID,WAAWC;EACfC,UAAUF,WAAWE;EACrBC,YAAYH,WAAWG;EACvBC,OAAOJ,WAAWI;EAClBC,QAAQL,W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D,QAAQ;GACxDJ,YAAYC,aAAa,KAAKoC,MAAMrC,UAAUC,QAAQ;EACxD,CAAC,GACD,KAAKI,QACP;CACF;CAEA,eAAsBG,KAAa;EACjC,OAAO,IAAI/B,0BACT,IAAIH,sBAAsB;GACxBqE,MAAM;IACJG,KAAK,eAAetC,IAAG;IACvBuC,gBAAgB;KAAEC,MAAM;KAASM,OAAO9C;IAAI;GAC9C;GACAT,gBAAgB;IACd,OAAOqB,uBAAuB,KAAKiB,OAAO,KAAKA,MAAMhD,UAAUmB,IAAI;GACrE;GACAR,YAAYC,aAAa,KAAKoC,MAAMrC,UAAUC,QAAQ;EACxD,CAAC,GACD,KAAKoC,KACP;CACF;CAEA,uBAA8B7B,KAAa;EACzC,OAAO,IAAI/B,0BACT,IAAIH,sBAAsB;GACxBqE,MAAM;IACJG,KAAK,uBAAuBtC,IAAG;IAC/BuC,gBAAgB;KAAEC,MAAM;KAAgBM,OAAO9C;IAAI;GACrD;GACAT,gBAAgB;IACd,OAAOqB,uBACL,KAAKiB,OACL,KAAKA,MAAM/C,kBAAkBkB,IAC/B;GACF;GACAR,YAAYC,aAAa,KAAKoC,MAAMrC,UAAUC,QAAQ;EACxD,CAAC,GACD,KAAKoC,KACP;CACF;CAEA,YAAmBjC,UAAkB;EACnC,OAAO,IAAI3B,0BACT,IAAIH,sBAAsB;GACxBqE,MAAM;IACJG,KAAK,wBAAwB1C,SAAQ;IACrC2C,gBAAgB;KAAEC,MAAM;KAAY5C;IAAS;GAC/C;GACAL,gBAAgB;IACd,OAAOqB,uBAAuB,KAAKiB,OAAOjC,QAAQ;GACpD;GACAJ,YAAYC,aAAa,KAAKoC,MAAMrC,UAAUC,QAAQ;EACxD,CAAC,GACD,KAAKoC,KACP;CACF;AACF"}
|
|
@@ -99,7 +99,7 @@ type ThreadState = {
|
|
|
99
99
|
* The canonical `isRunning` derivation. A runtime that tracks run state itself
|
|
100
100
|
* reports it directly; the rest fall back to the trailing assistant message.
|
|
101
101
|
*/
|
|
102
|
-
declare const getThreadRuntimeCoreIsRunning: (runtime: ThreadRuntimeCore) => boolean;
|
|
102
|
+
declare const getThreadRuntimeCoreIsRunning: (runtime: Pick<ThreadRuntimeCore, "isRunning" | "messages">) => boolean;
|
|
103
103
|
declare const getThreadState: (runtime: ThreadRuntimeCore, threadListItemState: ThreadListItemState) => ThreadState;
|
|
104
104
|
type ThreadRuntime = {
|
|
105
105
|
/**
|
|
@@ -158,6 +158,13 @@ type ThreadRuntime = {
|
|
|
158
158
|
importExternalState(state: any): void;
|
|
159
159
|
subscribe(callback: () => void): Unsubscribe;
|
|
160
160
|
cancelRun(): void;
|
|
161
|
+
/**
|
|
162
|
+
* Notifies the runtime that the adapter discarded its backing session.
|
|
163
|
+
* Clears session-scoped tool-invocation state without run-cancel side
|
|
164
|
+
* effects such as composer draft restoration. Internal API for
|
|
165
|
+
* external-store adapter authors.
|
|
166
|
+
*/
|
|
167
|
+
unstable_notifySessionReset(): void;
|
|
161
168
|
getModelContext(): ModelContext;
|
|
162
169
|
export(): ExportedMessageRepository;
|
|
163
170
|
import(repository: ExportedMessageRepository): void;
|
|
@@ -198,6 +205,7 @@ declare class ThreadRuntimeImpl implements ThreadRuntime {
|
|
|
198
205
|
startRun: (config: StartRunConfig) => void;
|
|
199
206
|
resumeRun: (config: ResumeRunConfig) => void;
|
|
200
207
|
cancelRun: () => void;
|
|
208
|
+
unstable_notifySessionReset: () => void;
|
|
201
209
|
addToolResult: (options: AddToolResultOptions) => void;
|
|
202
210
|
resumeToolCall: (options: ResumeToolCallOptions) => void;
|
|
203
211
|
respondToToolApproval: (options: RespondToToolApprovalOptions) => void;
|
|
@@ -273,19 +281,21 @@ declare class ThreadRuntimeImpl implements ThreadRuntime {
|
|
|
273
281
|
getStateState(): ThreadState;
|
|
274
282
|
};
|
|
275
283
|
private readonly _threadBinding;
|
|
284
|
+
private readonly _stateBinding;
|
|
276
285
|
constructor(threadBinding: ThreadRuntimeCoreBinding, threadListItemBinding: ThreadListItemRuntimeBinding);
|
|
277
286
|
protected __internal_bindMethods(): void;
|
|
278
287
|
readonly composer: ThreadComposerRuntimeImpl;
|
|
279
288
|
getState(): ThreadState;
|
|
280
289
|
append(message: CreateAppendMessage): void;
|
|
281
290
|
deleteMessage(messageId: string): void | Promise<void>;
|
|
282
|
-
subscribe(callback: () => void):
|
|
291
|
+
subscribe(callback: () => void): () => void;
|
|
283
292
|
getModelContext(): ModelContext;
|
|
284
293
|
startRun(config: CreateStartRunConfig): void;
|
|
285
294
|
resumeRun(config: CreateResumeRunConfig): void;
|
|
286
295
|
exportExternalState(): any;
|
|
287
296
|
importExternalState(state: any): void;
|
|
288
297
|
cancelRun(): void;
|
|
298
|
+
unstable_notifySessionReset(): void;
|
|
289
299
|
stopSpeaking(): void;
|
|
290
300
|
connectVoice(): void;
|
|
291
301
|
disconnectVoice(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;KA+CY;EACV;EACA;EACA,YAAY;;KAGF,wBAAwB;EAClC,UACE,SAAS,wBACN,eAAe;;KAoBV;EAGN;EACA;EACA,OAAO;EACP,SAAS;EACT,cAAc;EACd,WAAW;EACX,YAAY;EACZ,YAAY;EACZ;;KAiCM,2BAA2B,sBACrC,mBACA;EAEA,eAAe,uBAAuB;;KAG5B,+BAA+B,sBACzC,qBACA;KAGU;;;;;WAKD;;;;;;WAOA,UAAU;;;;WAKV;;;;WAKA;;;;WAKA;;;;WAKA,cAAc;;;;WAKd,mBAAmB;;;;;;WAOnB,OAAO;;;;WAKP,sBAAsB;;;;WAKtB;;;;WAKA,QAAQ;WAER,OAAO;;;;;;cAOL,gCACX,SAAS;
|
|
1
|
+
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;KA+CY;EACV;EACA;EACA,YAA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AAS;EAchB,cAAc,2BAAiB;EAI/B,UAAU;EAIV,mBAAe;EAIf,SAAS,QAAQ;EAIjB,UAAU,QAAQ;EAIlB;EAIA,oBAAoB;EAIpB;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA,qBAAqB,uBAAoB;EAIzC;EAIA;EAIA,UAAM;EAIN,OAAO,MAAM;EAIb,MAAM,2BAA2B;EAIjC,kBAAkB,cAAW;EAsB7B,eAAe,oBAAiB;UAW/B;UA2CA;EAKD,YAAY,UAAU,wBAC3B,OAAO,GACP,UAAU,2BAA2B,KACpC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { EventSubscriptionSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "../../subscribable/subscribable.js";
|
|
1
2
|
import { isMessageNotSentError } from "../../types/error.js";
|
|
2
3
|
import { symbolInnerMessage } from "../utils/external-store-message.js";
|
|
3
|
-
import { EventSubscriptionSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "../../subscribable/subscribable.js";
|
|
4
4
|
import { ThreadComposerRuntimeImpl } from "./composer-runtime.js";
|
|
5
5
|
import { MessageRuntimeImpl } from "./message-runtime.js";
|
|
6
6
|
//#region src/runtime/api/thread-runtime.ts
|
|
@@ -78,6 +78,7 @@ var ThreadRuntimeImpl = class {
|
|
|
78
78
|
return this._threadBinding;
|
|
79
79
|
}
|
|
80
80
|
_threadBinding;
|
|
81
|
+
_stateBinding;
|
|
81
82
|
constructor(threadBinding, threadListItemBinding) {
|
|
82
83
|
const stateBinding = new ShallowMemoizeSubject({
|
|
83
84
|
path: threadBinding.path,
|
|
@@ -91,6 +92,7 @@ var ThreadRuntimeImpl = class {
|
|
|
91
92
|
};
|
|
92
93
|
}
|
|
93
94
|
});
|
|
95
|
+
this._stateBinding = stateBinding;
|
|
94
96
|
this._threadBinding = {
|
|
95
97
|
path: threadBinding.path,
|
|
96
98
|
getState: () => threadBinding.getState(),
|
|
@@ -117,6 +119,7 @@ var ThreadRuntimeImpl = class {
|
|
|
117
119
|
this.exportExternalState = this.exportExternalState.bind(this);
|
|
118
120
|
this.startRun = this.startRun.bind(this);
|
|
119
121
|
this.cancelRun = this.cancelRun.bind(this);
|
|
122
|
+
this.unstable_notifySessionReset = this.unstable_notifySessionReset.bind(this);
|
|
120
123
|
this.stopSpeaking = this.stopSpeaking.bind(this);
|
|
121
124
|
this.connectVoice = this.connectVoice.bind(this);
|
|
122
125
|
this.disconnectVoice = this.disconnectVoice.bind(this);
|
|
@@ -148,7 +151,7 @@ var ThreadRuntimeImpl = class {
|
|
|
148
151
|
return this._threadBinding.getState().deleteMessage(messageId);
|
|
149
152
|
}
|
|
150
153
|
subscribe(callback) {
|
|
151
|
-
return this.
|
|
154
|
+
return this._stateBinding.subscribe(callback);
|
|
152
155
|
}
|
|
153
156
|
getModelContext() {
|
|
154
157
|
return this._threadBinding.getState().getModelContext();
|
|
@@ -168,6 +171,9 @@ var ThreadRuntimeImpl = class {
|
|
|
168
171
|
cancelRun() {
|
|
169
172
|
this._threadBinding.getState().cancelRun();
|
|
170
173
|
}
|
|
174
|
+
unstable_notifySessionReset() {
|
|
175
|
+
this._threadBinding.getState().unstable_notifySessionReset();
|
|
176
|
+
}
|
|
171
177
|
stopSpeaking() {
|
|
172
178
|
return this._threadBinding.getState().stopSpeaking();
|
|
173
179
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.js","names":["ThreadSuggestion","RuntimeCapabilities","ThreadRuntimeCore","SpeechState","VoiceSessionState","ThreadRuntimeEventCallback","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ExportedMessageRepository","ThreadMessageLike","MessageRuntime","MessageRuntimeImpl","MessageState","NestedSubscriptionSubject","ShallowMemoizeSubject","SKIP_UPDATE","SubscribableWithState","ThreadComposerRuntime","ThreadComposerRuntimeImpl","MessageRuntimePath","ThreadListItemRuntimePath","ThreadRuntimePath","ThreadListItemState","AppendMessage","ThreadMessage","Unsubscribe","isMessageNotSentError","RunConfig","EventSubscriptionSubject","symbolInnerMessage","ModelContext","ChatModelRunOptions","ChatModelRunResult","ReadonlyJSONValue","CreateStartRunConfig","parentId","sourceId","runConfig","CreateResumeRunConfig","stream","options","AsyncGenerator","toResumeRunConfig","message","toStartRunConfig","CreateAppendMessage","role","content","attachments","metadata","createdAt","Date","startRun","toAppendMessage","messages","at","id","type","text","custom","ThreadRuntimeCoreBinding","outerSubscribe","callback","ThreadListItemRuntimeBinding","ThreadState","threadId","isDisabled","isLoading","isRunning","capabilities","state","suggestions","extras","speech","voice","getThreadRuntimeCoreIsRunning","runtime","undefined","lastMessage","status","getThreadState","threadListItemState","Object","freeze","ThreadRuntime","path","composer","getState","append","deleteMessage","messageId","Promise","config","resumeRun","exportExternalState","importExternalState","subscribe","cancelRun","getModelContext","export","import","repository","reset","initialMessages","getMessageByIndex","idx","getMessageById","stopSpeaking","connectVoice","disconnectVoice","getVoiceVolume","subscribeVoiceVolume","muteVoice","unmuteVoice","unstable_on","event","E","ThreadRuntimeImpl","_threadBinding","__internal_threadBinding","getStateState","constructor","threadBinding","threadListItemBinding","stateBinding","sub1","sub2","ref","composerSource","__internal_bindMethods","bind","task","resolve","catch","error","data","Error","_getMessageRuntime","messageSelector","index","JSON","stringify","speechState","thread","branches","getBranches","isLast","branchNumber","indexOf","branchCount","length","_eventSubscriptionSubjects","Map","subject","get","binding","set","payload"],"sources":["../../../src/runtime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { isMessageNotSentError } from \"../../types/error\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\n/**\n * The canonical `isRunning` derivation. A runtime that tracks run state itself\n * reports it directly; the rest fall back to the trailing assistant message.\n */\nexport const getThreadRuntimeCoreIsRunning = (\n runtime: ThreadRuntimeCore,\n): boolean => {\n if (runtime.isRunning !== undefined) return runtime.isRunning;\n const lastMessage = runtime.messages.at(-1);\n return (\n lastMessage?.role === \"assistant\" && lastMessage.status.type === \"running\"\n );\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning: getThreadRuntimeCoreIsRunning(runtime),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n deleteMessage(messageId: string): void | Promise<void>;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n\n connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => {\n sub1();\n sub2();\n };\n },\n });\n\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.deleteMessage = this.deleteMessage.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\n }\n\n public readonly composer;\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n const task = this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n // An undispatched send is reported to the composer, so it is a control\n // signal rather than a failure to surface; every other rejection keeps\n // reaching the host untouched.\n void Promise.resolve(task).catch((error) => {\n if (!isMessageNotSentError(error)) throw error;\n });\n }\n\n public deleteMessage(messageId: string) {\n return this._threadBinding.getState().deleteMessage(messageId);\n }\n\n public subscribe(callback: () => void) {\n return this._threadBinding.subscribe(callback);\n }\n\n public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n}\n"],"mappings":";;;;;;AA2DA,MAAM2C,qBAAqBC,YAAoD;CA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AK4B,eAAe/B,SAAS,CAAC,CAACmB,eAAehB,SAAS,CAC/D;CACF;CAEA,mBACEL,MACAvB,UAGA;EACA,OAAO,IAAInD,mBACT,IAAIG,sBAAsB;GACxBuE;GACAE,gBAAgB;IACd,MAAM,EAAE5C,SAASR,UAAUwG,UAAU7E,SAAS,KAAK,CAAC;IAEpD,MAAM,EAAER,UAAUmB,QAAQqE,gBACxB,KAAKxB,eAAe/B,SAAS;IAE/B,IAAI,CAAC5C,WAAWR,aAAa0C,KAAAA,KAAa8D,UAAU9D,KAAAA,GAClD,OAAO9D;IAIT,MAAMiI,WAFS,KAAK1B,eAAe/B,SAElBwD,CAAM,CAACE,YAAYtG,QAAQa,EAAE;IAE9C,OAAO;KACL,GAAGb;MACGd,qBAAsBc,QAAgBd;KAE5C8G;KACAO,QAAQ5F,SAASC,GAAG,EAAE,CAAC,EAAEC,OAAOb,QAAQa;KACxCrB;KAEAgH,cAAcH,SAASI,QAAQzG,QAAQa,EAAE,IAAI;KAC7C6F,aAAaL,SAASM;KAEtB7E,QACEqE,aAAapD,cAAc/C,QAAQa,KAAKsF,cAAcjE,KAAAA;IAC1D;GACF;GACAmB,YAAYlC,aAAa,KAAKwD,eAAetB,UAAUlC,QAAQ;EACjE,CAAC,GACD,KAAKwD,cACP;CACF;CAEA,6CAAqC,IAAIkC,IAGvC;CAEF,YACErC,OACArD,UACa;EACb,IAAI2F,UAAU,KAAKF,2BAA2BG,IAAIvC,KAAK;EACvD,IAAI,CAACsC,SAAS;GACZA,UAAU,IAAI7H,yBAAiD;IAC7DuF;IACAwC,SAAS,KAAKrC;GAChB,CAAC;GACD,KAAKiC,2BAA2BK,IAAIzC,OAAOsC,OAAO;EACpD;EACA,OAAOA,QAAQzD,UAAUlC,QAAuC;CAClE;AACF"}
|
|
1
|
+
{"version":3,"file":"thread-runtime.js","names":["ThreadSuggestion","RuntimeCapabilities","ThreadRuntimeCore","SpeechState","VoiceSessionState","ThreadRuntimeEventCallback","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ExportedMessageRepository","ThreadMessageLike","MessageRuntime","MessageRuntimeImpl","MessageState","NestedSubscriptionSubject","ShallowMemoizeSubject","SKIP_UPDATE","SubscribableWithState","ThreadComposerRuntime","ThreadComposerRuntimeImpl","MessageRuntimePath","ThreadListItemRuntimePath","ThreadRuntimePath","ThreadListItemState","AppendMessage","ThreadMessage","Unsubscribe","isMessageNotSentError","RunConfig","EventSubscriptionSubject","symbolInnerMessage","ModelContext","ChatModelRunOptions","ChatModelRunResult","ReadonlyJSONValue","CreateStartRunConfig","parentId","sourceId","runConfig","CreateResumeRunConfig","stream","options","AsyncGenerator","toResumeRunConfig","message","toStartRunConfig","CreateAppendMessage","role","content","attachments","metadata","createdAt","Date","startRun","toAppendMessage","messages","at","id","type","text","custom","ThreadRuntimeCoreBinding","outerSubscribe","callback","ThreadListItemRuntimeBinding","ThreadState","threadId","isDisabled","isLoading","isRunning","capabilities","state","suggestions","extras","speech","voice","getThreadRuntimeCoreIsRunning","runtime","Pick","undefined","lastMessage","status","getThreadState","threadListItemState","Object","freeze","ThreadRuntime","path","composer","getState","append","deleteMessage","messageId","Promise","config","resumeRun","exportExternalState","importExternalState","subscribe","cancelRun","unstable_notifySessionReset","getModelContext","export","import","repository","reset","initialMessages","getMessageByIndex","idx","getMessageById","stopSpeaking","connectVoice","disconnectVoice","getVoiceVolume","subscribeVoiceVolume","muteVoice","unmuteVoice","unstable_on","event","E","ThreadRuntimeImpl","_threadBinding","__internal_threadBinding","getStateState","_stateBinding","constructor","threadBinding","threadListItemBinding","stateBinding","sub1","sub2","ref","composerSource","__internal_bindMethods","bind","task","resolve","catch","error","data","Error","_getMessageRuntime","messageSelector","index","JSON","stringify","speechState","thread","branches","getBranches","isLast","branchNumber","indexOf","branchCount","length","_eventSubscriptionSubjects","Map","subject","get","binding","set","payload"],"sources":["../../../src/runtime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { isMessageNotSentError } from \"../../types/error\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\n/**\n * The canonical `isRunning` derivation. A runtime that tracks run state itself\n * reports it directly; the rest fall back to the trailing assistant message.\n */\nexport const getThreadRuntimeCoreIsRunning = (\n runtime: Pick<ThreadRuntimeCore, \"isRunning\" | \"messages\">,\n): boolean => {\n if (runtime.isRunning !== undefined) return runtime.isRunning;\n const lastMessage = runtime.messages.at(-1);\n return (\n lastMessage?.role === \"assistant\" && lastMessage.status.type === \"running\"\n );\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning: getThreadRuntimeCoreIsRunning(runtime),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n deleteMessage(messageId: string): void | Promise<void>;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n /**\n * Notifies the runtime that the adapter discarded its backing session.\n * Clears session-scoped tool-invocation state without run-cancel side\n * effects such as composer draft restoration. Internal API for\n * external-store adapter authors.\n */\n unstable_notifySessionReset(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n\n connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n private readonly _stateBinding: ShallowMemoizeSubject<\n ThreadState,\n ThreadRuntimePath\n >;\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => {\n sub1();\n sub2();\n };\n },\n });\n\n this._stateBinding = stateBinding;\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.deleteMessage = this.deleteMessage.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.unstable_notifySessionReset =\n this.unstable_notifySessionReset.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\n }\n\n public readonly composer;\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n const task = this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n // An undispatched send is reported to the composer, so it is a control\n // signal rather than a failure to surface; every other rejection keeps\n // reaching the host untouched.\n void Promise.resolve(task).catch((error) => {\n if (!isMessageNotSentError(error)) throw error;\n });\n }\n\n public deleteMessage(messageId: string) {\n return this._threadBinding.getState().deleteMessage(messageId);\n }\n\n public subscribe(callback: () => void) {\n return this._stateBinding.subscribe(callback);\n }\n\n public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public unstable_notifySessionReset() {\n this._threadBinding.getState().unstable_notifySessionReset();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n}\n"],"mappings":";;;;;;AA2DA,MAAM2C,qBAAqBC,YAAoD;CAC7E,OAAO;EACLR,UAAUQ,QAAQR,YAAY;EAC9BC,UAAUO,QAAQP,YAAY;EAC9BC,WAAWM,QAAQN,aAAa,CAAC;EACjC,GAAIM,QAAQJ,SAAS,EAAEA,QAAQI,QAAQJ,OAAO,IAAI,CAAC;CACrD;AACF;AAEA,MAAMK,oBAAoBD,YAAkD;CAC1E,OAAO;EACLR,UAAUQ,QAAQR,YAAY;EAC9BC,UAAUO,QAAQP,YAAY;EAC9BC,WAAWM,QAAQN,aAAa,CAAC;CACnC;AACF;AAgBA,MAAMgB,mBACJC,UACAX,YACkB;CAClB,IAAI,OAAOA,YAAY,UACrB,OAAO;EACLO,2BAAW,IAAIC,KAAK;EACpBhB,UAAUmB,SAASC,GAAG,EAAE,CAAC,EAAEC,MAAM;EACjCpB,UAAU;EACVC,WAAW,CAAC;EACZS,MAAM;EACNC,SAAS,CAAC;GAAEU,MAAM;GAAQC,MAAMf;EAAQ,CAAC;EACzCK,aAAa,CAAA;EACbC,UAAU,EAAEU,QAAQ,CAAC,EAA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,GAAG,EAAE,CAAC,EAAEC,OAAOb,QAAQa;KACxCrB;KAEAmH,cAAcH,SAASI,QAAQ5G,QAAQa,EAAE,IAAI;KAC7CgG,aAAaL,SAASM;KAEtBhF,QACEwE,aAAatD,cAAchD,QAAQa,KAAKyF,cAAcnE,KAAAA;IAC1D;GACF;GACAmB,YAAYnC,aAAa,KAAK0D,eAAevB,UAAUnC,QAAQ;EACjE,CAAC,GACD,KAAK0D,cACP;CACF;CAEA,6CAAqC,IAAImC,IAGvC;CAEF,YACEtC,OACAvD,UACa;EACb,IAAI8F,UAAU,KAAKF,2BAA2BG,IAAIxC,KAAK;EACvD,IAAI,CAACuC,SAAS;GACZA,UAAU,IAAIhI,yBAAiD;IAC7DyF;IACAyC,SAAS,KAAKtC;GAChB,CAAC;GACD,KAAKkC,2BAA2BK,IAAI1C,OAAOuC,OAAO;EACpD;EACA,OAAOA,QAAQ3D,UAAUnC,QAAuC;CAClE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":";;;;;;;;;;uBA2CsB,gCACZ,4BACG;WAEK;qBAEG,wBAAwB;qBACxB,uBAAuB;YAEhC,2BACR;IAAY;MAAa,SAAS;;KAClC,SAAS,GAAG,kBAAkB,sCAAsC;MAW3D;UAIH;MACG,wBAAW;YAIZ,eAAe,gBAAgB;eAKrB;eACA;MAET;UAIH;MAEJ;UAII;MAEJ;UAII;MAEJ,aAAS;UAIL;MAEJ,SAAK;EAIF,SAAS,OAAO;EAOhB,QAAQ;UAWP;EASD,QAAQ,MAAM;EAOd,aAAa,WAAW;YAOrB;UACF;UACA;UACA;UAEA;UAQA;UAOA;UAMM;EAQD,SAAK;EA8BL,oBAAgB;EAQhB,KAAK,UAAU,cAAW;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":";;;;;;;;;;uBA2CsB,gCACZ,4BACG;WAEK;qBAEG,wBAAwB;qBACxB,uBAAuB;YAEhC,2BACR;IAAY;MAAa,SAAS;;KAClC,SAAS,GAAG,kBAAkB,sCAAsC;MAW3D;UAIH;MACG,wBAAW;YAIZ,eAAe,gBAAgB;eAKrB;eACA;MAET;UAIH;MAEJ;UAII;MAEJ;UAII;MAEJ,aAAS;UAIL;MAEJ,SAAK;EAIF,SAAS,OAAO;EAOhB,QAAQ;UAWP;EASD,QAAQ,MAAM;EAOd,aAAa,WAAW;YAOrB;UACF;UACA;UACA;UAEA;UAQA;UAOA;UAMM;EAQD,SAAK;EA8BL,oBAAgB;EAQhB,KAAK,UAAU,cAAW;;;;;;;;;EAsGhC,aAAa;IAClB;IACA,QAAQ;IACR,uBAAuB;;;;;;;EAsBlB,aAAa;IAClB;IACA,QAAQ;IACR,uBAAuB;;UAuBjB;EAcD;MAII,kBAAkB;EAItB,cACL,sBACA,YAAY;EAEP,gBAAgB;qBAEJ,WACjB,SAAS,KAAK,yCACd,UAAU,qBACF;qBACS;EAEb,cAAc,kBAAkB,OAAO,mBAAgB;UAuIrD;EAqBF,iBAAiB,uBAAoB;UAmCnC;UACA;UACA;UACA;UACA;UACA;UACA;UACA;MAEG,aAAa;UAIhB;EAUD;EA6FA;UASC;UAuBA;YAKE,wBAAwB,UAAU,0BAC1C,OAAO,GACP,SAAS,4BAA4B;EAQhC,YAAY,UAAU,0BAC3B,OAAO,GACP,UAAU,6BAA6B"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { notifyEventListeners } from "../../utils/notify-event-listeners.js";
|
|
2
|
+
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
1
3
|
import { generateId } from "../../utils/id.js";
|
|
2
4
|
import { fileMatchesAccept } from "../../adapters/attachment.js";
|
|
3
5
|
import { isMessageNotSentError } from "../../types/error.js";
|
|
4
6
|
import { EMPTY_QUEUE_ITEMS } from "../../store/scopes/queue-item.js";
|
|
5
|
-
import { notifyEventListeners } from "../../utils/notify-event-listeners.js";
|
|
6
|
-
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
7
7
|
import { isCreateAttachment } from "../../types/attachment.js";
|
|
8
8
|
//#region src/runtime/base/base-composer-runtime-core.ts
|
|
9
9
|
const isAttachmentComplete = (a) => a.status.type === "complete";
|
|
@@ -144,6 +144,8 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
144
144
|
const originalAttachments = this.attachments;
|
|
145
145
|
const text = this.text;
|
|
146
146
|
const quote = this._quote;
|
|
147
|
+
const role = this.role;
|
|
148
|
+
const runConfig = this.runConfig;
|
|
147
149
|
this._quote = void 0;
|
|
148
150
|
this._text = "";
|
|
149
151
|
this._isSending = true;
|
|
@@ -178,13 +180,13 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
178
180
|
this._removedDuringSend.clear();
|
|
179
181
|
const message = {
|
|
180
182
|
createdAt: /* @__PURE__ */ new Date(),
|
|
181
|
-
role
|
|
183
|
+
role,
|
|
182
184
|
content: text ? [{
|
|
183
185
|
type: "text",
|
|
184
186
|
text
|
|
185
187
|
}] : [],
|
|
186
188
|
attachments: finalAttachments,
|
|
187
|
-
runConfig
|
|
189
|
+
runConfig,
|
|
188
190
|
metadata: { custom: { ...quote ? { quote } : {} } }
|
|
189
191
|
};
|
|
190
192
|
const draft = {
|
|
@@ -461,9 +463,8 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
461
463
|
if (!this._dictationSession) return;
|
|
462
464
|
const session = this._dictationSession;
|
|
463
465
|
const sessionId = this._activeDictationSessionId;
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
});
|
|
466
|
+
const cleanup = () => this._cleanupDictation({ sessionId });
|
|
467
|
+
session.stop().then(cleanup, cleanup);
|
|
467
468
|
}
|
|
468
469
|
_cleanupDictation(options) {
|
|
469
470
|
if (options?.sessionId !== void 0 && options.sessionId !== this._activeDictationSessionId || this._isCleaningDictation) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-composer-runtime-core.js","names":["isCreateAttachment","Attachment","CompleteAttachment","CreateAttachment","PendingAttachment","MessageRole","AppendMessage","isMessageNotSentError","QuoteInfo","Unsubscribe","RunConfig","BaseSubscribable","AttachmentAdapter","fileMatchesAccept","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","SendOptions","DictationAdapter","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","generateId","notifyEventListeners","isAttachmentComplete","a","status","type","AttachmentAddOperation","cancelled","attachmentIds","Set","BaseComposerRuntimeCore","isEditing","getAttachmentAdapter","getDictationAdapter","enrichWithComposerMetadata","metadata","custom","Record","message","T","composerMetadata","attachmentAccept","accept","_attachments","attachments","setAttachments","value","_notifySubscribers","canCancel","canSend","isEmpty","text","trim","length","_text","_role","role","_runConfig","runConfig","_quote","undefined","quote","setQuote","setText","_rebaseDictation","_dictation","_dictationBaseText","_currentInterimText","inputDisabled","setRole","setRunConfig","_isSending","_removedDuringSend","_sendGeneration","_attachmentAddOperations","_cancelAttachmentAdd","attachmentId","operation","has","delete","_cancelAllAttachmentAdds","clear","_emptyTextAndAttachments","_onClearAttachments","adapter","pending","filter","Promise","all","map","remove","reset","Object","keys","task","clearAttachments","send","options","_dictationSession","cancel","_cleanupDictation","attachmentTasks","Error","result","originalAttachments","generation","resolvedAttachments","e","allSettled","then","sentIds","id","finalAttachments","Omit","createdAt","Date","content","draft","sendTask","handleSend","error","_restoreUnsentDraft","catch","_notifyEventSubscribers","restoreDraft","retractDraft","attachmentsUntouched","handleCancel","queue","moveQueueItem","_queueItemId","_placement","removeQueueItem","addAttachment","fileOrAttachment","File","name","contentType","err","_safeEmitAttachmentAddError","operations","add","upsertAttachment","idx","findIndex","attachment","slice","lastAttachment","promiseOrGenerator","file","Symbol","asyncIterator","r","reason","String","subscriberError","console","removeAttachment","index","candidate","Session","_dictationUnsubscribes","_dictationSessionIdCounter","_activeDictationSessionId","_isCleaningDictation","dictation","_isActiveSession","sessionId","session","startDictation","unsub","oldSession","stop","disableInputDuringDictation","listen","unsubSpeech","onSpeech","isFinal","needsSeparator","endsWith","transcript","separator","_","rest","push","unsubStart","onSpeechStart","unsubEnd","onSpeechEnd","statusInterval","setInterval","clearInterval","stopDictation","finally","isStaleSession","_eventSubscribers","Map","payload","event","E","subscribers","get","unstable_on","callback","wrapped","set"],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"sourcesContent":["import {\n isCreateAttachment,\n type Attachment,\n type CompleteAttachment,\n type CreateAttachment,\n type PendingAttachment,\n} from \"../../types/attachment\";\nimport type { MessageRole, AppendMessage } from \"../../types/message\";\nimport { isMessageNotSentError } from \"../../types/error\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\nimport {\n type AttachmentAdapter,\n fileMatchesAccept,\n} from \"../../adapters/attachment\";\nimport type {\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n SendOptions,\n} from \"../interfaces/composer-runtime-core\";\nimport type { DictationAdapter } from \"../../adapters/speech\";\nimport type { QueuePlacement } from \"../queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport { generateId } from \"../../utils/id\";\nimport { notifyEventListeners } from \"../../utils/notify-event-listeners\";\n\nconst isAttachmentComplete = (a: Attachment): a is CompleteAttachment =>\n a.status.type === \"complete\";\n\ntype AttachmentAddOperation = {\n cancelled: boolean;\n attachmentIds: Set<string>;\n};\n\nexport abstract class BaseComposerRuntimeCore\n extends BaseSubscribable\n implements ComposerRuntimeCore\n{\n public readonly isEditing = true;\n\n protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n protected abstract getDictationAdapter(): DictationAdapter | undefined;\n\n protected enrichWithComposerMetadata<\n T extends { metadata?: { custom?: Record<string, unknown> } },\n >(message: T, composerMetadata: Record<string, unknown> | undefined): T {\n if (!composerMetadata) return message;\n return {\n ...message,\n metadata: {\n ...message.metadata,\n custom: { ...message.metadata?.custom, ...composerMetadata },\n },\n } as T;\n }\n\n public get attachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\n\n private _attachments: readonly Attachment[] = [];\n public get attachments() {\n return this._attachments;\n }\n\n protected setAttachments(value: readonly Attachment[]) {\n this._attachments = value;\n this._notifySubscribers();\n }\n\n public abstract get canCancel(): boolean;\n public abstract get canSend(): boolean;\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\n }\n\n private _text = \"\";\n\n get text() {\n return this._text;\n }\n\n private _role: MessageRole = \"user\";\n\n get role() {\n return this._role;\n }\n\n private _runConfig: RunConfig = {};\n\n get runConfig() {\n return this._runConfig;\n }\n\n private _quote: QuoteInfo | undefined = undefined;\n\n get quote() {\n return this._quote;\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n if (this._quote === quote) return;\n\n this._quote = quote;\n this._notifySubscribers();\n }\n\n public setText(value: string) {\n if (this._text === value) return;\n\n this._text = value;\n this._rebaseDictation(value);\n this._notifySubscribers();\n }\n\n // A live dictation session appends to the text it last saw, so any write\n // that bypasses `setText` has to move that baseline or the next transcript\n // overwrites what was just written.\n private _rebaseDictation(value: string) {\n if (!this._dictation) return;\n\n this._dictationBaseText = value;\n this._currentInterimText = \"\";\n const { status, inputDisabled } = this._dictation;\n this._dictation = inputDisabled ? { status, inputDisabled } : { status };\n }\n\n public setRole(role: MessageRole) {\n if (this._role === role) return;\n\n this._role = role;\n this._notifySubscribers();\n }\n\n public setRunConfig(runConfig: RunConfig) {\n if (this._runConfig === runConfig) return;\n\n this._runConfig = runConfig;\n this._notifySubscribers();\n }\n\n protected _isSending = false;\n private _removedDuringSend = new Set<string>();\n private _sendGeneration = 0;\n private _attachmentAddOperations = new Set<AttachmentAddOperation>();\n\n private _cancelAttachmentAdd(attachmentId: string) {\n for (const operation of [...this._attachmentAddOperations]) {\n if (!operation.attachmentIds.has(attachmentId)) continue;\n operation.cancelled = true;\n this._attachmentAddOperations.delete(operation);\n }\n }\n\n private _cancelAllAttachmentAdds() {\n for (const operation of this._attachmentAddOperations) {\n operation.cancelled = true;\n }\n this._attachmentAddOperations.clear();\n }\n\n private _emptyTextAndAttachments() {\n this._attachments = [];\n this._text = \"\";\n this._notifySubscribers();\n }\n\n private async _onClearAttachments() {\n const adapter = this.getAttachmentAdapter();\n if (adapter) {\n const pending = this._attachments.filter((a) => !isAttachmentComplete(a));\n await Promise.all(pending.map((a) => adapter.remove(a)));\n }\n }\n\n public async reset() {\n this._cancelAllAttachmentAdds();\n\n // A send whose adapter never settles must not brick the composer; reset is\n // the escape hatch that releases the in-flight lock. Bumping the generation\n // invalidates that send entirely so a late-settling upload can neither\n // append the discarded draft nor touch a newer send's lock.\n this._sendGeneration++;\n this._isSending = false;\n this._removedDuringSend.clear();\n\n if (\n this._attachments.length === 0 &&\n this._text === \"\" &&\n this._role === \"user\" &&\n Object.keys(this._runConfig).length === 0 &&\n this._quote === undefined\n ) {\n return;\n }\n\n this._role = \"user\";\n this._runConfig = {};\n this._quote = undefined;\n\n const task = this._onClearAttachments();\n this._emptyTextAndAttachments();\n await task;\n }\n\n public async clearAttachments() {\n this._cancelAllAttachmentAdds();\n const task = this._onClearAttachments();\n this.setAttachments([]);\n\n await task;\n }\n\n public async send(options?: SendOptions) {\n if (!this.canSend || this._isSending) return;\n\n if (this._dictationSession) {\n this._dictationSession.cancel();\n this._cleanupDictation();\n }\n\n const adapter = this.getAttachmentAdapter();\n const attachmentTasks = this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n if (!adapter) throw new Error(\"Attachments are not supported\");\n const result = await adapter.send(a);\n return result as CompleteAttachment;\n });\n\n const originalAttachments = this.attachments;\n const text = this.text;\n const quote = this._quote;\n this._quote = undefined;\n this._text = \"\";\n this._isSending = true;\n const generation = ++this._sendGeneration;\n this._notifySubscribers();\n\n let resolvedAttachments: CompleteAttachment[];\n try {\n resolvedAttachments = await Promise.all(attachmentTasks);\n } catch (e) {\n if (generation === this._sendGeneration) {\n if (!this.text.trim() && this._quote === undefined) {\n this._text = text;\n this._rebaseDictation(text);\n this._quote = quote;\n this._notifySubscribers();\n }\n // Promise.all rejects on the first failure, but sibling uploads from\n // this batch keep running; the send rejects immediately while the\n // retry lock is held until they settle, or a retry could re-send\n // attachments that are still in flight.\n void Promise.allSettled(attachmentTasks).then(() => {\n if (generation !== this._sendGeneration) return;\n this._removedDuringSend.clear();\n this._isSending = false;\n this._notifySubscribers();\n });\n }\n throw e;\n }\n\n // A reset during the upload discarded this send's draft; the settled\n // uploads must not append it or touch the lock a newer send may own.\n if (generation !== this._sendGeneration) return;\n\n // Drop by id, not wholesale: the user may have added or removed chips while\n // the upload was in flight.\n const sentIds = new Set(originalAttachments.map((a) => a.id));\n this._attachments = this._attachments.filter((a) => !sentIds.has(a.id));\n this._isSending = false;\n this._notifySubscribers();\n\n // An attachment removed mid-upload can't be cancelled, but it can still be\n // dropped from the outgoing message instead of silently being sent anyway.\n const finalAttachments = resolvedAttachments.filter(\n (a) => !this._removedDuringSend.has(a.id),\n );\n this._removedDuringSend.clear();\n\n const message: Omit<AppendMessage, \"parentId\" | \"sourceId\"> = {\n createdAt: new Date(),\n role: this.role,\n content: text ? [{ type: \"text\", text }] : [],\n attachments: finalAttachments,\n runConfig: this.runConfig,\n metadata: { custom: { ...(quote ? { quote } : {}) } },\n };\n\n const draft = { text, quote, attachments: finalAttachments };\n let sendTask: void | Promise<void>;\n try {\n sendTask = this.handleSend(message, options);\n } catch (error) {\n this._restoreUnsentDraft(error, generation, draft);\n throw error;\n }\n if (sendTask)\n void sendTask.catch((error) => {\n this._restoreUnsentDraft(error, generation, draft);\n });\n this._notifyEventSubscribers(\"send\", {});\n }\n\n /**\n * Take a message back into the composer when it has nowhere else to live:\n * a send the runtime never dispatched, or a message a cancelled run is\n * removing from the thread. Reports whether the composer accepted it, so a\n * caller that is also removing the message can keep it instead of dropping\n * it. Refused, and left untouched, while the composer holds anything of its\n * own.\n */\n public restoreDraft(draft: {\n text: string;\n quote?: QuoteInfo | undefined;\n attachments?: readonly Attachment[] | undefined;\n }): boolean {\n if (\n this._text.trim() ||\n this._quote !== undefined ||\n this._attachments.length > 0\n )\n return false;\n\n this._text = draft.text;\n this._rebaseDictation(draft.text);\n this._quote = draft.quote;\n this._attachments = draft.attachments ?? [];\n this._notifySubscribers();\n return true;\n }\n\n /**\n * Inverse of `restoreDraft`: clears the composer while it still holds\n * exactly the given draft. A draft the user has edited since is left\n * untouched.\n */\n public retractDraft(draft: {\n text: string;\n quote?: QuoteInfo | undefined;\n attachments?: readonly Attachment[] | undefined;\n }): void {\n const attachmentsUntouched =\n draft.attachments !== undefined\n ? this._attachments === draft.attachments\n : this._attachments.length === 0;\n if (\n this._text !== draft.text ||\n this._quote !== draft.quote ||\n !attachmentsUntouched\n )\n return;\n\n this._text = \"\";\n this._rebaseDictation(\"\");\n this._quote = undefined;\n this._attachments = [];\n this._notifySubscribers();\n }\n\n // The generation check is what a reset and a later send use to invalidate a\n // draft, so of several queued drafts only the most recent one is still\n // restorable.\n private _restoreUnsentDraft(\n error: unknown,\n generation: number,\n draft: {\n text: string;\n quote: QuoteInfo | undefined;\n attachments: readonly CompleteAttachment[];\n },\n ) {\n if (!isMessageNotSentError(error)) return;\n if (generation !== this._sendGeneration) return;\n this.restoreDraft(draft);\n }\n\n public cancel() {\n this.handleCancel();\n }\n\n public get queue(): readonly QueueItemState[] {\n return EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(\n _queueItemId: string,\n _placement: QueuePlacement,\n ): void {}\n public removeQueueItem(_queueItemId: string): void {}\n\n protected abstract handleSend(\n message: Omit<AppendMessage, \"parentId\" | \"sourceId\">,\n options?: SendOptions,\n ): void | Promise<void>;\n protected abstract handleCancel(): void;\n\n async addAttachment(fileOrAttachment: File | CreateAttachment) {\n if (isCreateAttachment(fileOrAttachment)) {\n const adapter = this.getAttachmentAdapter();\n if (\n adapter &&\n !fileMatchesAccept(\n {\n name: fileOrAttachment.name,\n type: fileOrAttachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.contentType || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\n \"not-accepted\",\n message,\n undefined,\n err,\n );\n throw err;\n }\n\n const a: CompleteAttachment = {\n id: fileOrAttachment.id ?? generateId(),\n type: fileOrAttachment.type ?? \"document\",\n name: fileOrAttachment.name,\n contentType: fileOrAttachment.contentType,\n content: fileOrAttachment.content,\n status: { type: \"complete\" },\n };\n this._attachments = [...this._attachments, a];\n this._notifySubscribers();\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n return;\n }\n\n const adapter = this.getAttachmentAdapter();\n if (!adapter) {\n const message = \"Attachments are not supported\";\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"no-adapter\", message, undefined, err);\n throw err;\n }\n\n if (\n !fileMatchesAccept(\n { name: fileOrAttachment.name, type: fileOrAttachment.type },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.type || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"not-accepted\", message, undefined, err);\n throw err;\n }\n\n const operation: AttachmentAddOperation = {\n cancelled: false,\n attachmentIds: new Set(),\n };\n const operations = this._attachmentAddOperations;\n operations.add(operation);\n const upsertAttachment = (a: PendingAttachment) => {\n if (operation.cancelled) return false;\n\n operation.attachmentIds.add(a.id);\n const idx = this._attachments.findIndex(\n (attachment) => attachment.id === a.id,\n );\n if (idx !== -1)\n this._attachments = [\n ...this._attachments.slice(0, idx),\n a,\n ...this._attachments.slice(idx + 1),\n ];\n else {\n this._attachments = [...this._attachments, a];\n }\n\n this._notifySubscribers();\n return true;\n };\n let lastAttachment: PendingAttachment | undefined;\n try {\n const promiseOrGenerator = adapter.add({ file: fileOrAttachment });\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n lastAttachment = r;\n if (!upsertAttachment(r)) break;\n }\n } else {\n lastAttachment = await promiseOrGenerator;\n upsertAttachment(lastAttachment);\n }\n } catch (e) {\n if (operation.cancelled) return;\n if (lastAttachment) {\n upsertAttachment({\n ...lastAttachment,\n status: {\n type: \"incomplete\",\n reason: \"error\",\n message: e instanceof Error ? e.message : String(e),\n },\n });\n }\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n e instanceof Error ? e.message : String(e),\n lastAttachment?.id,\n e instanceof Error ? e : undefined,\n );\n throw e;\n } finally {\n operations.delete(operation);\n }\n\n if (operation.cancelled) return;\n if (\n lastAttachment?.status.type === \"incomplete\" &&\n lastAttachment.status.reason === \"error\"\n ) {\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n lastAttachment.status.message ??\n \"Attachment upload did not complete successfully.\",\n lastAttachment.id,\n );\n } else {\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n }\n }\n\n private _safeEmitAttachmentAddError(\n reason: AttachmentAddErrorReason,\n message: string,\n attachmentId?: string,\n error?: Error,\n ) {\n try {\n this._notifyEventSubscribers(\"attachmentAddError\", {\n reason,\n message,\n ...(attachmentId !== undefined && { attachmentId }),\n ...(error !== undefined && { error }),\n });\n } catch (subscriberError) {\n console.error(\n \"[assistant-ui] attachmentAddError subscriber threw:\",\n subscriberError,\n );\n }\n }\n\n async removeAttachment(attachmentId: string) {\n const index = this._attachments.findIndex((a) => a.id === attachmentId);\n if (index === -1) throw new Error(\"Attachment not found\");\n const attachment = this._attachments[index]!;\n\n this._cancelAttachmentAdd(attachmentId);\n\n // A send in flight may already be uploading this attachment; the upload\n // can't be cancelled, so mark it to be dropped from the outgoing message\n // before any await gives the upload a chance to settle first.\n if (this._isSending) this._removedDuringSend.add(attachmentId);\n\n if (!isAttachmentComplete(attachment)) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n try {\n await adapter.remove(attachment);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this._attachments = this._attachments.map((candidate) =>\n candidate.id === attachmentId && !isAttachmentComplete(candidate)\n ? {\n ...candidate,\n status: { type: \"incomplete\", reason: \"error\", message },\n }\n : candidate,\n );\n this._notifySubscribers();\n throw error;\n }\n }\n this._attachments = this._attachments.filter((a) => a.id !== attachmentId);\n this._notifySubscribers();\n }\n\n private _dictation: DictationState | undefined;\n private _dictationSession: DictationAdapter.Session | undefined;\n private _dictationUnsubscribes: Unsubscribe[] = [];\n private _dictationBaseText = \"\";\n private _currentInterimText = \"\";\n private _dictationSessionIdCounter = 0;\n private _activeDictationSessionId: number | undefined;\n private _isCleaningDictation = false;\n\n public get dictation(): DictationState | undefined {\n return this._dictation;\n }\n\n private _isActiveSession(\n sessionId: number,\n session: DictationAdapter.Session,\n ): boolean {\n return (\n this._activeDictationSessionId === sessionId &&\n this._dictationSession === session\n );\n }\n\n public startDictation(): void {\n const adapter = this.getDictationAdapter();\n if (!adapter) {\n throw new Error(\"Dictation adapter not configured\");\n }\n\n if (this._dictationSession) {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n const oldSession = this._dictationSession;\n oldSession.stop().catch(() => {});\n this._dictationSession = undefined;\n }\n\n const inputDisabled = adapter.disableInputDuringDictation ?? false;\n\n this._dictationBaseText = this._text;\n this._currentInterimText = \"\";\n\n const session = adapter.listen();\n this._dictationSession = session;\n const sessionId = ++this._dictationSessionIdCounter;\n this._activeDictationSessionId = sessionId;\n this._dictation = { status: session.status, inputDisabled };\n this._notifySubscribers();\n\n const unsubSpeech = session.onSpeech((result) => {\n if (!this._isActiveSession(sessionId, session)) return;\n const isFinal = result.isFinal !== false;\n\n const needsSeparator =\n this._dictationBaseText &&\n !this._dictationBaseText.endsWith(\" \") &&\n result.transcript;\n const separator = needsSeparator ? \" \" : \"\";\n\n if (isFinal) {\n this._dictationBaseText =\n this._dictationBaseText + separator + result.transcript;\n this._currentInterimText = \"\";\n this._text = this._dictationBaseText;\n\n if (this._dictation) {\n const { transcript: _, ...rest } = this._dictation;\n this._dictation = rest;\n }\n this._notifySubscribers();\n } else {\n this._currentInterimText = separator + result.transcript;\n this._text = this._dictationBaseText + this._currentInterimText;\n\n if (this._dictation) {\n this._dictation = {\n ...this._dictation,\n transcript: result.transcript,\n };\n }\n this._notifySubscribers();\n }\n });\n this._dictationUnsubscribes.push(unsubSpeech);\n\n const unsubStart = session.onSpeechStart(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n this._dictation = {\n status: { type: \"running\" },\n inputDisabled,\n ...(this._dictation?.transcript && {\n transcript: this._dictation.transcript,\n }),\n };\n this._notifySubscribers();\n });\n this._dictationUnsubscribes.push(unsubStart);\n\n const unsubEnd = session.onSpeechEnd(() => {\n this._cleanupDictation({ sessionId });\n });\n this._dictationUnsubscribes.push(unsubEnd);\n\n const statusInterval = setInterval(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n if (session.status.type === \"ended\") {\n this._cleanupDictation({ sessionId });\n }\n }, 100);\n this._dictationUnsubscribes.push(() => clearInterval(statusInterval));\n }\n\n public stopDictation(): void {\n if (!this._dictationSession) return;\n\n const session = this._dictationSession;\n const sessionId = this._activeDictationSessionId;\n session.stop().finally(() => {\n this._cleanupDictation({ sessionId });\n });\n }\n\n private _cleanupDictation(options?: { sessionId: number | undefined }): void {\n const isStaleSession =\n options?.sessionId !== undefined &&\n options.sessionId !== this._activeDictationSessionId;\n if (isStaleSession || this._isCleaningDictation) return;\n\n this._isCleaningDictation = true;\n try {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n this._dictationSession = undefined;\n this._activeDictationSessionId = undefined;\n this._dictation = undefined;\n this._dictationBaseText = \"\";\n this._currentInterimText = \"\";\n this._notifySubscribers();\n } finally {\n this._isCleaningDictation = false;\n }\n }\n\n private _eventSubscribers = new Map<\n ComposerRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n protected _notifyEventSubscribers<E extends ComposerRuntimeEventType>(\n event: E,\n payload: ComposerRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n notifyEventListeners(subscribers, payload, `Composer runtime \"${event}\"`);\n }\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;;;;;AAmCA,MAAM2B,wBAAwBC,MAC5BA,EAAEC,OAAOC,SAAS;AAOpB,IAAsBK,0BAAtB,cACUxB,iBAEV;CACE,YAA4B;CAK5B,2BAEEgC,SAAYE,kBAA0D;EACtE,IAAI,CAACA,kBAAkB,OAAOF;EAC9B,OAAO;GACL,GAAGA;GACHH,UAAU;IACR,GAAGG,QAAQH;IACXC,QAAQ;KAAE,GAAGE,QAAQH,UAAUC;KAAQ,GAAGI;IAAiB;GAC7D;EACF;CACF;CAEA,IAAWC,mBAA2B;EACpC,OAAO,KAAKT,qBAAqB,CAAC,EAAEU,UAAU;CAChD;CAEA,eAA8C,CAAA;CAC9C,IAAWE,cAAc;EACvB,OAAO,KAAKD;CACd;CAEA,eAAyBG,OAA8B;EACrD,KAAKH,eAAeG;EACpB,KAAKC,mBAAmB;CAC1B;CAKA,IAAWG,UAAU;EACnB,OAAO,CAAC,KAAKC,KAAKC,KAAK,KAAK,CAAC,KAAKR,YAAYS;CAChD;CAEA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AAK,EAAG;CAC1E;CAEA,YACEA,OACAK,UACA;EACA,MAAMC,UAAUD;EAChB,IAAIH,cAAc,KAAKL,kBAAkBM,IAAIH,KAAK;EAClD,IAAI,CAACE,aAAa;GAChBA,8BAAc,IAAI3K,IAAI;GACtB,KAAKsK,kBAAkBU,IAAIP,OAAOE,WAAW;EAC/C;EACAA,YAAY3D,IAAI+D,OAAO;EAEvB,aAAa;GACX,KAAKT,kBAAkBM,IAAIH,KAAK,CAAC,EAAEvH,OAAO6H,OAAO;EACnD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base-composer-runtime-core.js","names":["isCreateAttachment","Attachment","CompleteAttachment","CreateAttachment","PendingAttachment","MessageRole","AppendMessage","isMessageNotSentError","QuoteInfo","Unsubscribe","RunConfig","BaseSubscribable","AttachmentAdapter","fileMatchesAccept","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","SendOptions","DictationAdapter","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","generateId","notifyEventListeners","isAttachmentComplete","a","status","type","AttachmentAddOperation","cancelled","attachmentIds","Set","BaseComposerRuntimeCore","isEditing","getAttachmentAdapter","getDictationAdapter","enrichWithComposerMetadata","metadata","custom","Record","message","T","composerMetadata","attachmentAccept","accept","_attachments","attachments","setAttachments","value","_notifySubscribers","canCancel","canSend","isEmpty","text","trim","length","_text","_role","role","_runConfig","runConfig","_quote","undefined","quote","setQuote","setText","_rebaseDictation","_dictation","_dictationBaseText","_currentInterimText","inputDisabled","setRole","setRunConfig","_isSending","_removedDuringSend","_sendGeneration","_attachmentAddOperations","_cancelAttachmentAdd","attachmentId","operation","has","delete","_cancelAllAttachmentAdds","clear","_emptyTextAndAttachments","_onClearAttachments","adapter","pending","filter","Promise","all","map","remove","reset","Object","keys","task","clearAttachments","send","options","_dictationSession","cancel","_cleanupDictation","attachmentTasks","Error","result","originalAttachments","generation","resolvedAttachments","e","allSettled","then","sentIds","id","finalAttachments","Omit","createdAt","Date","content","draft","sendTask","handleSend","error","_restoreUnsentDraft","catch","_notifyEventSubscribers","restoreDraft","retractDraft","attachmentsUntouched","handleCancel","queue","moveQueueItem","_queueItemId","_placement","removeQueueItem","addAttachment","fileOrAttachment","File","name","contentType","err","_safeEmitAttachmentAddError","operations","add","upsertAttachment","idx","findIndex","attachment","slice","lastAttachment","promiseOrGenerator","file","Symbol","asyncIterator","r","reason","String","subscriberError","console","removeAttachment","index","candidate","Session","_dictationUnsubscribes","_dictationSessionIdCounter","_activeDictationSessionId","_isCleaningDictation","dictation","_isActiveSession","sessionId","session","startDictation","unsub","oldSession","stop","disableInputDuringDictation","listen","unsubSpeech","onSpeech","isFinal","needsSeparator","endsWith","transcript","separator","_","rest","push","unsubStart","onSpeechStart","unsubEnd","onSpeechEnd","statusInterval","setInterval","clearInterval","stopDictation","cleanup","isStaleSession","_eventSubscribers","Map","payload","event","E","subscribers","get","unstable_on","callback","wrapped","set"],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"sourcesContent":["import {\n isCreateAttachment,\n type Attachment,\n type CompleteAttachment,\n type CreateAttachment,\n type PendingAttachment,\n} from \"../../types/attachment\";\nimport type { MessageRole, AppendMessage } from \"../../types/message\";\nimport { isMessageNotSentError } from \"../../types/error\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\nimport {\n type AttachmentAdapter,\n fileMatchesAccept,\n} from \"../../adapters/attachment\";\nimport type {\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n SendOptions,\n} from \"../interfaces/composer-runtime-core\";\nimport type { DictationAdapter } from \"../../adapters/speech\";\nimport type { QueuePlacement } from \"../queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport { generateId } from \"../../utils/id\";\nimport { notifyEventListeners } from \"../../utils/notify-event-listeners\";\n\nconst isAttachmentComplete = (a: Attachment): a is CompleteAttachment =>\n a.status.type === \"complete\";\n\ntype AttachmentAddOperation = {\n cancelled: boolean;\n attachmentIds: Set<string>;\n};\n\nexport abstract class BaseComposerRuntimeCore\n extends BaseSubscribable\n implements ComposerRuntimeCore\n{\n public readonly isEditing = true;\n\n protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n protected abstract getDictationAdapter(): DictationAdapter | undefined;\n\n protected enrichWithComposerMetadata<\n T extends { metadata?: { custom?: Record<string, unknown> } },\n >(message: T, composerMetadata: Record<string, unknown> | undefined): T {\n if (!composerMetadata) return message;\n return {\n ...message,\n metadata: {\n ...message.metadata,\n custom: { ...message.metadata?.custom, ...composerMetadata },\n },\n } as T;\n }\n\n public get attachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\n\n private _attachments: readonly Attachment[] = [];\n public get attachments() {\n return this._attachments;\n }\n\n protected setAttachments(value: readonly Attachment[]) {\n this._attachments = value;\n this._notifySubscribers();\n }\n\n public abstract get canCancel(): boolean;\n public abstract get canSend(): boolean;\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\n }\n\n private _text = \"\";\n\n get text() {\n return this._text;\n }\n\n private _role: MessageRole = \"user\";\n\n get role() {\n return this._role;\n }\n\n private _runConfig: RunConfig = {};\n\n get runConfig() {\n return this._runConfig;\n }\n\n private _quote: QuoteInfo | undefined = undefined;\n\n get quote() {\n return this._quote;\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n if (this._quote === quote) return;\n\n this._quote = quote;\n this._notifySubscribers();\n }\n\n public setText(value: string) {\n if (this._text === value) return;\n\n this._text = value;\n this._rebaseDictation(value);\n this._notifySubscribers();\n }\n\n // A live dictation session appends to the text it last saw, so any write\n // that bypasses `setText` has to move that baseline or the next transcript\n // overwrites what was just written.\n private _rebaseDictation(value: string) {\n if (!this._dictation) return;\n\n this._dictationBaseText = value;\n this._currentInterimText = \"\";\n const { status, inputDisabled } = this._dictation;\n this._dictation = inputDisabled ? { status, inputDisabled } : { status };\n }\n\n public setRole(role: MessageRole) {\n if (this._role === role) return;\n\n this._role = role;\n this._notifySubscribers();\n }\n\n public setRunConfig(runConfig: RunConfig) {\n if (this._runConfig === runConfig) return;\n\n this._runConfig = runConfig;\n this._notifySubscribers();\n }\n\n protected _isSending = false;\n private _removedDuringSend = new Set<string>();\n private _sendGeneration = 0;\n private _attachmentAddOperations = new Set<AttachmentAddOperation>();\n\n private _cancelAttachmentAdd(attachmentId: string) {\n for (const operation of [...this._attachmentAddOperations]) {\n if (!operation.attachmentIds.has(attachmentId)) continue;\n operation.cancelled = true;\n this._attachmentAddOperations.delete(operation);\n }\n }\n\n private _cancelAllAttachmentAdds() {\n for (const operation of this._attachmentAddOperations) {\n operation.cancelled = true;\n }\n this._attachmentAddOperations.clear();\n }\n\n private _emptyTextAndAttachments() {\n this._attachments = [];\n this._text = \"\";\n this._notifySubscribers();\n }\n\n private async _onClearAttachments() {\n const adapter = this.getAttachmentAdapter();\n if (adapter) {\n const pending = this._attachments.filter((a) => !isAttachmentComplete(a));\n await Promise.all(pending.map((a) => adapter.remove(a)));\n }\n }\n\n public async reset() {\n this._cancelAllAttachmentAdds();\n\n // A send whose adapter never settles must not brick the composer; reset is\n // the escape hatch that releases the in-flight lock. Bumping the generation\n // invalidates that send entirely so a late-settling upload can neither\n // append the discarded draft nor touch a newer send's lock.\n this._sendGeneration++;\n this._isSending = false;\n this._removedDuringSend.clear();\n\n if (\n this._attachments.length === 0 &&\n this._text === \"\" &&\n this._role === \"user\" &&\n Object.keys(this._runConfig).length === 0 &&\n this._quote === undefined\n ) {\n return;\n }\n\n this._role = \"user\";\n this._runConfig = {};\n this._quote = undefined;\n\n const task = this._onClearAttachments();\n this._emptyTextAndAttachments();\n await task;\n }\n\n public async clearAttachments() {\n this._cancelAllAttachmentAdds();\n const task = this._onClearAttachments();\n this.setAttachments([]);\n\n await task;\n }\n\n public async send(options?: SendOptions) {\n if (!this.canSend || this._isSending) return;\n\n if (this._dictationSession) {\n this._dictationSession.cancel();\n this._cleanupDictation();\n }\n\n const adapter = this.getAttachmentAdapter();\n const attachmentTasks = this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n if (!adapter) throw new Error(\"Attachments are not supported\");\n const result = await adapter.send(a);\n return result as CompleteAttachment;\n });\n\n const originalAttachments = this.attachments;\n const text = this.text;\n const quote = this._quote;\n const role = this.role;\n const runConfig = this.runConfig;\n this._quote = undefined;\n this._text = \"\";\n this._isSending = true;\n const generation = ++this._sendGeneration;\n this._notifySubscribers();\n\n let resolvedAttachments: CompleteAttachment[];\n try {\n resolvedAttachments = await Promise.all(attachmentTasks);\n } catch (e) {\n if (generation === this._sendGeneration) {\n if (!this.text.trim() && this._quote === undefined) {\n this._text = text;\n this._rebaseDictation(text);\n this._quote = quote;\n this._notifySubscribers();\n }\n // Promise.all rejects on the first failure, but sibling uploads from\n // this batch keep running; the send rejects immediately while the\n // retry lock is held until they settle, or a retry could re-send\n // attachments that are still in flight.\n void Promise.allSettled(attachmentTasks).then(() => {\n if (generation !== this._sendGeneration) return;\n this._removedDuringSend.clear();\n this._isSending = false;\n this._notifySubscribers();\n });\n }\n throw e;\n }\n\n // A reset during the upload discarded this send's draft; the settled\n // uploads must not append it or touch the lock a newer send may own.\n if (generation !== this._sendGeneration) return;\n\n // Drop by id, not wholesale: the user may have added or removed chips while\n // the upload was in flight.\n const sentIds = new Set(originalAttachments.map((a) => a.id));\n this._attachments = this._attachments.filter((a) => !sentIds.has(a.id));\n this._isSending = false;\n this._notifySubscribers();\n\n // An attachment removed mid-upload can't be cancelled, but it can still be\n // dropped from the outgoing message instead of silently being sent anyway.\n const finalAttachments = resolvedAttachments.filter(\n (a) => !this._removedDuringSend.has(a.id),\n );\n this._removedDuringSend.clear();\n\n const message: Omit<AppendMessage, \"parentId\" | \"sourceId\"> = {\n createdAt: new Date(),\n role,\n content: text ? [{ type: \"text\", text }] : [],\n attachments: finalAttachments,\n runConfig,\n metadata: { custom: { ...(quote ? { quote } : {}) } },\n };\n\n const draft = { text, quote, attachments: finalAttachments };\n let sendTask: void | Promise<void>;\n try {\n sendTask = this.handleSend(message, options);\n } catch (error) {\n this._restoreUnsentDraft(error, generation, draft);\n throw error;\n }\n if (sendTask)\n void sendTask.catch((error) => {\n this._restoreUnsentDraft(error, generation, draft);\n });\n this._notifyEventSubscribers(\"send\", {});\n }\n\n /**\n * Take a message back into the composer when it has nowhere else to live:\n * a send the runtime never dispatched, or a message a cancelled run is\n * removing from the thread. Reports whether the composer accepted it, so a\n * caller that is also removing the message can keep it instead of dropping\n * it. Refused, and left untouched, while the composer holds anything of its\n * own.\n */\n public restoreDraft(draft: {\n text: string;\n quote?: QuoteInfo | undefined;\n attachments?: readonly Attachment[] | undefined;\n }): boolean {\n if (\n this._text.trim() ||\n this._quote !== undefined ||\n this._attachments.length > 0\n )\n return false;\n\n this._text = draft.text;\n this._rebaseDictation(draft.text);\n this._quote = draft.quote;\n this._attachments = draft.attachments ?? [];\n this._notifySubscribers();\n return true;\n }\n\n /**\n * Inverse of `restoreDraft`: clears the composer while it still holds\n * exactly the given draft. A draft the user has edited since is left\n * untouched.\n */\n public retractDraft(draft: {\n text: string;\n quote?: QuoteInfo | undefined;\n attachments?: readonly Attachment[] | undefined;\n }): void {\n const attachmentsUntouched =\n draft.attachments !== undefined\n ? this._attachments === draft.attachments\n : this._attachments.length === 0;\n if (\n this._text !== draft.text ||\n this._quote !== draft.quote ||\n !attachmentsUntouched\n )\n return;\n\n this._text = \"\";\n this._rebaseDictation(\"\");\n this._quote = undefined;\n this._attachments = [];\n this._notifySubscribers();\n }\n\n // The generation check is what a reset and a later send use to invalidate a\n // draft, so of several queued drafts only the most recent one is still\n // restorable.\n private _restoreUnsentDraft(\n error: unknown,\n generation: number,\n draft: {\n text: string;\n quote: QuoteInfo | undefined;\n attachments: readonly CompleteAttachment[];\n },\n ) {\n if (!isMessageNotSentError(error)) return;\n if (generation !== this._sendGeneration) return;\n this.restoreDraft(draft);\n }\n\n public cancel() {\n this.handleCancel();\n }\n\n public get queue(): readonly QueueItemState[] {\n return EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(\n _queueItemId: string,\n _placement: QueuePlacement,\n ): void {}\n public removeQueueItem(_queueItemId: string): void {}\n\n protected abstract handleSend(\n message: Omit<AppendMessage, \"parentId\" | \"sourceId\">,\n options?: SendOptions,\n ): void | Promise<void>;\n protected abstract handleCancel(): void;\n\n async addAttachment(fileOrAttachment: File | CreateAttachment) {\n if (isCreateAttachment(fileOrAttachment)) {\n const adapter = this.getAttachmentAdapter();\n if (\n adapter &&\n !fileMatchesAccept(\n {\n name: fileOrAttachment.name,\n type: fileOrAttachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.contentType || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\n \"not-accepted\",\n message,\n undefined,\n err,\n );\n throw err;\n }\n\n const a: CompleteAttachment = {\n id: fileOrAttachment.id ?? generateId(),\n type: fileOrAttachment.type ?? \"document\",\n name: fileOrAttachment.name,\n contentType: fileOrAttachment.contentType,\n content: fileOrAttachment.content,\n status: { type: \"complete\" },\n };\n this._attachments = [...this._attachments, a];\n this._notifySubscribers();\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n return;\n }\n\n const adapter = this.getAttachmentAdapter();\n if (!adapter) {\n const message = \"Attachments are not supported\";\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"no-adapter\", message, undefined, err);\n throw err;\n }\n\n if (\n !fileMatchesAccept(\n { name: fileOrAttachment.name, type: fileOrAttachment.type },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.type || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"not-accepted\", message, undefined, err);\n throw err;\n }\n\n const operation: AttachmentAddOperation = {\n cancelled: false,\n attachmentIds: new Set(),\n };\n const operations = this._attachmentAddOperations;\n operations.add(operation);\n const upsertAttachment = (a: PendingAttachment) => {\n if (operation.cancelled) return false;\n\n operation.attachmentIds.add(a.id);\n const idx = this._attachments.findIndex(\n (attachment) => attachment.id === a.id,\n );\n if (idx !== -1)\n this._attachments = [\n ...this._attachments.slice(0, idx),\n a,\n ...this._attachments.slice(idx + 1),\n ];\n else {\n this._attachments = [...this._attachments, a];\n }\n\n this._notifySubscribers();\n return true;\n };\n let lastAttachment: PendingAttachment | undefined;\n try {\n const promiseOrGenerator = adapter.add({ file: fileOrAttachment });\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n lastAttachment = r;\n if (!upsertAttachment(r)) break;\n }\n } else {\n lastAttachment = await promiseOrGenerator;\n upsertAttachment(lastAttachment);\n }\n } catch (e) {\n if (operation.cancelled) return;\n if (lastAttachment) {\n upsertAttachment({\n ...lastAttachment,\n status: {\n type: \"incomplete\",\n reason: \"error\",\n message: e instanceof Error ? e.message : String(e),\n },\n });\n }\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n e instanceof Error ? e.message : String(e),\n lastAttachment?.id,\n e instanceof Error ? e : undefined,\n );\n throw e;\n } finally {\n operations.delete(operation);\n }\n\n if (operation.cancelled) return;\n if (\n lastAttachment?.status.type === \"incomplete\" &&\n lastAttachment.status.reason === \"error\"\n ) {\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n lastAttachment.status.message ??\n \"Attachment upload did not complete successfully.\",\n lastAttachment.id,\n );\n } else {\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n }\n }\n\n private _safeEmitAttachmentAddError(\n reason: AttachmentAddErrorReason,\n message: string,\n attachmentId?: string,\n error?: Error,\n ) {\n try {\n this._notifyEventSubscribers(\"attachmentAddError\", {\n reason,\n message,\n ...(attachmentId !== undefined && { attachmentId }),\n ...(error !== undefined && { error }),\n });\n } catch (subscriberError) {\n console.error(\n \"[assistant-ui] attachmentAddError subscriber threw:\",\n subscriberError,\n );\n }\n }\n\n async removeAttachment(attachmentId: string) {\n const index = this._attachments.findIndex((a) => a.id === attachmentId);\n if (index === -1) throw new Error(\"Attachment not found\");\n const attachment = this._attachments[index]!;\n\n this._cancelAttachmentAdd(attachmentId);\n\n // A send in flight may already be uploading this attachment; the upload\n // can't be cancelled, so mark it to be dropped from the outgoing message\n // before any await gives the upload a chance to settle first.\n if (this._isSending) this._removedDuringSend.add(attachmentId);\n\n if (!isAttachmentComplete(attachment)) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n try {\n await adapter.remove(attachment);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this._attachments = this._attachments.map((candidate) =>\n candidate.id === attachmentId && !isAttachmentComplete(candidate)\n ? {\n ...candidate,\n status: { type: \"incomplete\", reason: \"error\", message },\n }\n : candidate,\n );\n this._notifySubscribers();\n throw error;\n }\n }\n this._attachments = this._attachments.filter((a) => a.id !== attachmentId);\n this._notifySubscribers();\n }\n\n private _dictation: DictationState | undefined;\n private _dictationSession: DictationAdapter.Session | undefined;\n private _dictationUnsubscribes: Unsubscribe[] = [];\n private _dictationBaseText = \"\";\n private _currentInterimText = \"\";\n private _dictationSessionIdCounter = 0;\n private _activeDictationSessionId: number | undefined;\n private _isCleaningDictation = false;\n\n public get dictation(): DictationState | undefined {\n return this._dictation;\n }\n\n private _isActiveSession(\n sessionId: number,\n session: DictationAdapter.Session,\n ): boolean {\n return (\n this._activeDictationSessionId === sessionId &&\n this._dictationSession === session\n );\n }\n\n public startDictation(): void {\n const adapter = this.getDictationAdapter();\n if (!adapter) {\n throw new Error(\"Dictation adapter not configured\");\n }\n\n if (this._dictationSession) {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n const oldSession = this._dictationSession;\n oldSession.stop().catch(() => {});\n this._dictationSession = undefined;\n }\n\n const inputDisabled = adapter.disableInputDuringDictation ?? false;\n\n this._dictationBaseText = this._text;\n this._currentInterimText = \"\";\n\n const session = adapter.listen();\n this._dictationSession = session;\n const sessionId = ++this._dictationSessionIdCounter;\n this._activeDictationSessionId = sessionId;\n this._dictation = { status: session.status, inputDisabled };\n this._notifySubscribers();\n\n const unsubSpeech = session.onSpeech((result) => {\n if (!this._isActiveSession(sessionId, session)) return;\n const isFinal = result.isFinal !== false;\n\n const needsSeparator =\n this._dictationBaseText &&\n !this._dictationBaseText.endsWith(\" \") &&\n result.transcript;\n const separator = needsSeparator ? \" \" : \"\";\n\n if (isFinal) {\n this._dictationBaseText =\n this._dictationBaseText + separator + result.transcript;\n this._currentInterimText = \"\";\n this._text = this._dictationBaseText;\n\n if (this._dictation) {\n const { transcript: _, ...rest } = this._dictation;\n this._dictation = rest;\n }\n this._notifySubscribers();\n } else {\n this._currentInterimText = separator + result.transcript;\n this._text = this._dictationBaseText + this._currentInterimText;\n\n if (this._dictation) {\n this._dictation = {\n ...this._dictation,\n transcript: result.transcript,\n };\n }\n this._notifySubscribers();\n }\n });\n this._dictationUnsubscribes.push(unsubSpeech);\n\n const unsubStart = session.onSpeechStart(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n this._dictation = {\n status: { type: \"running\" },\n inputDisabled,\n ...(this._dictation?.transcript && {\n transcript: this._dictation.transcript,\n }),\n };\n this._notifySubscribers();\n });\n this._dictationUnsubscribes.push(unsubStart);\n\n const unsubEnd = session.onSpeechEnd(() => {\n this._cleanupDictation({ sessionId });\n });\n this._dictationUnsubscribes.push(unsubEnd);\n\n const statusInterval = setInterval(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n if (session.status.type === \"ended\") {\n this._cleanupDictation({ sessionId });\n }\n }, 100);\n this._dictationUnsubscribes.push(() => clearInterval(statusInterval));\n }\n\n public stopDictation(): void {\n if (!this._dictationSession) return;\n\n const session = this._dictationSession;\n const sessionId = this._activeDictationSessionId;\n const cleanup = () => this._cleanupDictation({ sessionId });\n void session.stop().then(cleanup, cleanup);\n }\n\n private _cleanupDictation(options?: { sessionId: number | undefined }): void {\n const isStaleSession =\n options?.sessionId !== undefined &&\n options.sessionId !== this._activeDictationSessionId;\n if (isStaleSession || this._isCleaningDictation) return;\n\n this._isCleaningDictation = true;\n try {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n this._dictationSession = undefined;\n this._activeDictationSessionId = undefined;\n this._dictation = undefined;\n this._dictationBaseText = \"\";\n this._currentInterimText = \"\";\n this._notifySubscribers();\n } finally {\n this._isCleaningDictation = false;\n }\n }\n\n private _eventSubscribers = new Map<\n ComposerRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n protected _notifyEventSubscribers<E extends ComposerRuntimeEventType>(\n event: E,\n payload: ComposerRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n notifyEventListeners(subscribers, payload, `Composer runtime \"${event}\"`);\n }\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;;;;;AAmCA,MAAM2B,wBAAwBC,MAC5BA,EAAEC,OAAOC,SAAS;AAOpB,IAAsBK,0BAAtB,cACUxB,iBAEV;CACE,YAA4B;CAK5B,2BAEEgC,SAAYE,kBAA0D;EACtE,IAAI,CAACA,kBAAkB,OAAOF;EAC9B,OAAO;GACL,GAAGA;GACHH,UAAU;IACR,GAAGG,QAAQH;IACXC,QAAQ;KAAE,GAAGE,QAAQH,UAAUC;KAAQ,G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;GAC9B,KAAK/D,oBAAoBtC,KAAAA;GACzB,KAAKuG,4BAA4BvG,KAAAA;GACjC,KAAKK,aAAaL,KAAAA;GAClB,KAAKM,qBAAqB;GAC1B,KAAKC,sBAAsB;GAC3B,KAAKpB,mBAAmB;EAC1B,UAAU;GACR,KAAKqH,uBAAuB;EAC9B;CACF;CAEA,oCAA4B,IAAIgC,IAG9B;CAEF,wBACEE,OACAD,SACA;EACA,MAAMG,cAAc,KAAKL,kBAAkBM,IAAIH,KAAK;EACpD,IAAI,CAACE,aAAa;EAElBnL,qBAAqBmL,aAAaH,SAAS,qBAAqBC,MAAK,EAAG;CAC1E;CAEA,YACEA,OACAK,UACA;EACA,MAAMC,UAAUD;EAChB,IAAIH,cAAc,KAAKL,kBAAkBM,IAAIH,KAAK;EAClD,IAAI,CAACE,aAAa;GAChBA,8BAAc,IAAI3K,IAAI;GACtB,KAAKsK,kBAAkBU,IAAIP,OAAOE,WAAW;EAC/C;EACAA,YAAY3D,IAAI+D,OAAO;EAEvB,aAAa;GACX,KAAKT,kBAAkBM,IAAIH,KAAK,CAAC,EAAEvH,OAAO6H,OAAO;EACnD;CACF;AACF"}
|
|
@@ -39,6 +39,7 @@ declare abstract class BaseThreadRuntimeCore implements ThreadRuntimeCore {
|
|
|
39
39
|
abstract cancelRun(): void;
|
|
40
40
|
abstract exportExternalState(): any;
|
|
41
41
|
abstract importExternalState(state: any): void;
|
|
42
|
+
abstract unstable_notifySessionReset(): void;
|
|
42
43
|
protected _voiceMessages: ThreadMessage[];
|
|
43
44
|
protected _voiceGeneration: number;
|
|
44
45
|
private _cachedMergedMessages;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;KAuCK;EACH,SAAS;EACT,WAAW;EACX,cAAc;EACd,QAAQ;;uBAGY,iCAAiC;UAC7C;UACA;qBAEW,YAAU;eACT,YAAY;eACZ;eACA;eACA;eACA,wBAAwB;eACxB;eAEA,gBAAgB;WACpB,OAAO,SAAS;WAChB,cAAc,2BAA2B;WACzC,SAAS,QAAQ;WACjB,UAAU,QAAQ;WAClB,cAAc,SAAS;WACvB,eAAe,SAAS;WACxB,sBACd,SAAS;WAEK;WACA;WACA,oBAAoB;
|
|
1
|
+
{"version":3,"file":"base-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;KAuCK;EACH,SAAS;EACT,WAAW;EACX,cAAc;EACd,QAAQ;;uBAGY,iCAAiC;UAC7C;UACA;qBAEW,YAAU;eACT,YAAY;eACZ;eACA;eACA;eACA,wBAAwB;eACxB;eAEA,gBAAgB;WACpB,OAAO,SAAS;WAChB,cAAc,2BAA2B;WACzC,SAAS,QAAQ;WACjB,UAAU,QAAQ;WAClB,cAAc,SAAS;WACvB,eAAe,SAAS;WACxB,sBACd,SAAS;WAEK;WACA;WACA,oBAAoB;WACpB;YAEN,gBAAgB;YAChB;UACF;UACA;UACA;YAEE;YAKA,6BAA6B;MAI5B,qBAAqB;MAgBrB,sEAAK,sDAAA;WAWA,UAAQ;mBAEP;EAEL,YAAA,kBAAkB;EAIvB,mBAJuB;;;;;;;;;;;;;;YAqBpB,qBACR,SAAS,eACT,2BACC;UAmBK;EACD,gBAAgB,oBAAiB;EAGjC,UAAU;EAeV,eAAe;;;;;EAsBf,YAAY;EAOZ,eAAe;YAKZ;EAIH,wBAAwB,UAAU,wBACvC,OAAO,GACP,SAAS,0BAA0B;EAQ9B,UAAU,uBAAuB;EAKjC,iBAAiB,WAAW,QAAQ;UAqBnC;EACD,QAAQ;EAER,MAAM;EA8BN;UAMC;UACA;EACD,OAAO;UAEN;UACA;EAED;EAEA,uBAAwB,yBAAuB;EAK/C;UAmEC;UAEA;UA8DA;EAaD;EAmBA;EAUA;YAUG;EAOH,UAAM;EAIN,OAAO,MAAM;EAOb,MAAM,2BAA2B;UAIhC;EAKD,YAAY,UAAU,wBAC3B,OAAO,GACP,UAAU,2BAA2B,KAAE"}
|