@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":"external-store-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"external-store-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;;cAwEa,qBACX,oBACA,mBAAmB;cAKR,uCACH,iCACG;UAEH;MAiBG,gBAAY;UAIf;EACD;EACA;MACI;MAIA;YAIQ,6BAA6B;MAI5B,sEAAK,sDAAA;MAId;kBARqC;;;;;;;MAarC,iCAAiC;EAKrC,sBAAsB;EACtB;UAEC;UAEA;UAEA;EAED,mCACL,kBAAkB;UAKZ;;;;;UAMA;EAEQ,UAAU;EAQxB,YAAA,iBAAiB,sBACjB,OAAO;EAMF,sBAAsB,OAAO;;;;;;;UA2M5B;;;;;UAsEA;UACA;;;;;;;UAQA;EAmBQ,eAAe;;;;;;;;;UA6BvB;EAaK,OAAO,YAAY,gBAAgB;EAoEnC,cAAc,oBAAoB;EAoBxC,0BApBwC;EA0BxC,+BANa;EAUb,cAAc,qBAAqB,WAAW;EAI9C,gBAAgB;EAIV,SAAS,QAAQ,iBAAiB;EAYlC,UAAU,QAAQ,kBAAkB;EAO1C;EAOA,oBAAoB;;;;;;EAqBpB;EAKA;UA+EC;EAOD,cAAc,SAAS;EASvB,eAAe,SAAS;EAoBxB,sBAAsB,SAAS;EAStB,MAAM,2BAA2B;EAMjC,OAAO,MAAM;UAQrB"}
|
|
@@ -6,10 +6,16 @@ import { getAutoStatus, isAutoStatus } from "../../runtime/utils/auto-status.js"
|
|
|
6
6
|
import { ExportedMessageRepository, MessageRepository } from "../../runtime/utils/message-repository.js";
|
|
7
7
|
import { EMPTY_QUEUE_ITEMS } from "../../store/scopes/queue-item.js";
|
|
8
8
|
import { BaseThreadRuntimeCore } from "../../runtime/base/base-thread-runtime-core.js";
|
|
9
|
+
import { captureThreadRuntimeGeneration, isThreadRuntimeGenerationCurrent } from "../../runtime/utils/thread-runtime-lifecycle.js";
|
|
9
10
|
import { ThreadMessageConverter } from "./thread-message-converter.js";
|
|
10
11
|
import { ToolInvocationTracker } from "../tool-invocations/ToolInvocationTracker.js";
|
|
11
12
|
//#region src/runtimes/external-store/external-store-thread-runtime-core.ts
|
|
12
13
|
const EMPTY_ARRAY = Object.freeze([]);
|
|
14
|
+
const observeAdapterCallback = (name, result) => {
|
|
15
|
+
Promise.resolve(result).catch((error) => {
|
|
16
|
+
console.error(`[ExternalStoreThreadRuntimeCore] ${name} callback rejected`, error);
|
|
17
|
+
});
|
|
18
|
+
};
|
|
13
19
|
const shallowEqual = (a, b) => {
|
|
14
20
|
const aKeys = Object.keys(a);
|
|
15
21
|
if (aKeys.length !== Object.keys(b).length) return false;
|
|
@@ -65,6 +71,10 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
65
71
|
extras = void 0;
|
|
66
72
|
_converter = new ThreadMessageConverter();
|
|
67
73
|
_store;
|
|
74
|
+
_getInitializePromise;
|
|
75
|
+
__internal_setGetInitializePromise(getPromise) {
|
|
76
|
+
this._getInitializePromise = getPromise;
|
|
77
|
+
}
|
|
68
78
|
_transformedQueue;
|
|
69
79
|
/**
|
|
70
80
|
* Client-side tool-invocations pipeline. Constructed lazily on first
|
|
@@ -210,7 +220,7 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
210
220
|
try {
|
|
211
221
|
const messageId = this._findMessageIdForToolCall(command.toolCallId);
|
|
212
222
|
if (messageId === void 0) return;
|
|
213
|
-
this._store.onAddToolResult?.({
|
|
223
|
+
observeAdapterCallback("onAddToolResult", this._store.onAddToolResult?.({
|
|
214
224
|
messageId,
|
|
215
225
|
toolCallId: command.toolCallId,
|
|
216
226
|
toolName: command.toolName,
|
|
@@ -218,7 +228,7 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
218
228
|
isError: command.isError,
|
|
219
229
|
...command.artifact !== void 0 && { artifact: command.artifact },
|
|
220
230
|
...command.modelContent !== void 0 && { modelContent: command.modelContent }
|
|
221
|
-
});
|
|
231
|
+
}));
|
|
222
232
|
} catch (err) {
|
|
223
233
|
console.error("[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed", err);
|
|
224
234
|
}
|
|
@@ -290,14 +300,20 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
290
300
|
}
|
|
291
301
|
async append(rawMessage) {
|
|
292
302
|
const isEdit = rawMessage.sourceId != null || rawMessage.parentId !== (this.messages.at(-1)?.id ?? null);
|
|
303
|
+
const message = !isEdit && this._store.queue && this._store.queue === this._transformedQueue ? rawMessage : this.enrichAppendMetadata(rawMessage);
|
|
304
|
+
const generation = captureThreadRuntimeGeneration(this);
|
|
305
|
+
this.ensureInitialized();
|
|
306
|
+
const initPromise = this._getInitializePromise?.();
|
|
293
307
|
if (!isEdit && this._store.queue) {
|
|
294
|
-
|
|
295
|
-
if (
|
|
296
|
-
|
|
308
|
+
if (initPromise) await initPromise;
|
|
309
|
+
if (!isThreadRuntimeGenerationCurrent(this, generation)) return;
|
|
310
|
+
if (message.steer ?? this._store.isRunning ?? false) this._store.queue.steer(message);
|
|
311
|
+
else this._store.queue.enqueue(message);
|
|
297
312
|
return;
|
|
298
313
|
}
|
|
299
|
-
|
|
314
|
+
initPromise?.catch(() => {});
|
|
300
315
|
if (message.startRun ?? message.role === "user") await this._toolInvocations?.abort();
|
|
316
|
+
if (!isThreadRuntimeGenerationCurrent(this, generation)) return;
|
|
301
317
|
if (isEdit) {
|
|
302
318
|
if (!this._store.onEdit) throw new Error("Runtime does not support editing messages.");
|
|
303
319
|
await this._store.onEdit(message);
|
|
@@ -341,17 +357,23 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
341
357
|
}
|
|
342
358
|
importExternalState(state) {
|
|
343
359
|
if (!this._store.onLoadExternalState) throw new Error("Runtime does not support importing external states.");
|
|
344
|
-
|
|
345
|
-
this._toolInvocations.reset();
|
|
346
|
-
this._store.setToolStatuses?.({});
|
|
347
|
-
}
|
|
360
|
+
this._toolInvocations?.reset();
|
|
348
361
|
this._store.onLoadExternalState(state);
|
|
349
362
|
}
|
|
363
|
+
/**
|
|
364
|
+
* Adapter-facing notification that the backing session was discarded.
|
|
365
|
+
* Clears session-scoped tool-invocation state and parks queued work,
|
|
366
|
+
* without run-cancel semantics (`onCancel`, composer draft restoration).
|
|
367
|
+
*/
|
|
368
|
+
unstable_notifySessionReset() {
|
|
369
|
+
this._toolInvocations?.reset();
|
|
370
|
+
this._store.queue?.__internal_notifyCancelled?.();
|
|
371
|
+
}
|
|
350
372
|
cancelRun() {
|
|
351
373
|
if (!this._store.onCancel) throw new Error("Runtime does not support cancelling runs.");
|
|
352
374
|
this._toolInvocations?.abort();
|
|
353
375
|
this._store.queue?.__internal_notifyCancelled?.();
|
|
354
|
-
this._store.onCancel();
|
|
376
|
+
observeAdapterCallback("onCancel", this._store.onCancel());
|
|
355
377
|
this.dropEmptyOptimisticHead();
|
|
356
378
|
const messages = this.repository.getMessages();
|
|
357
379
|
const previousMessage = messages[messages.length - 1];
|
|
@@ -388,7 +410,7 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
388
410
|
}
|
|
389
411
|
addToolResult(options) {
|
|
390
412
|
if (!this._store.onAddToolResult) throw new Error("Runtime does not support tool results.");
|
|
391
|
-
this._store.onAddToolResult
|
|
413
|
+
observeAdapterCallback("onAddToolResult", this._store.onAddToolResult(options));
|
|
392
414
|
}
|
|
393
415
|
resumeToolCall(options) {
|
|
394
416
|
if (this._toolInvocations?.resume(options.toolCallId, options.payload) ?? false) return;
|
|
@@ -400,7 +422,7 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
400
422
|
}
|
|
401
423
|
respondToToolApproval(options) {
|
|
402
424
|
if (!this._store.onRespondToToolApproval) throw new Error("Runtime does not support tool approvals.");
|
|
403
|
-
this._store.onRespondToToolApproval(options);
|
|
425
|
+
observeAdapterCallback("onRespondToToolApproval", this._store.onRespondToToolApproval(options));
|
|
404
426
|
}
|
|
405
427
|
reset(initialMessages) {
|
|
406
428
|
const repo = new MessageRepository();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","Attachment","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","ExternalStoreBranchChange","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","ExternalThreadQueueAdapter","QueuePlacement","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","QuoteInfo","EMPTY_ARRAY","Object","freeze","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","unstable_refetchThread","Promise","onRefetchThread","undefined","suggestions","extras","_converter","_transformedQueue","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","__internal_setDispatchTransform","message","parentId","at","id","enrichAppendMetadata","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","incoming","headId","repository","resetHead","getMessages","incomingIds","Set","map","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","seenIds","deduped","i","console","warn","add","push","reverse","parent","ensureInitialized","_notifyEventSubscribers","optimisticId","content","metadata","isOptimistic","type","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","result","isError","artifact","modelContent","err","error","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","clear","visit","Array","isArray","part","set","get","branchId","onBranchChange","unstable_onBranchChange","previousHeadId","canonicalHeadId","updateMessages","_notifyBranchChange","event","visibleMessageIds","append","rawMessage","isEdit","sourceId","queued","steer","enqueue","startRun","abort","onNew","messageIndex","findIndex","filter","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","cancelRun","__internal_notifyCancelled","dropEmptyOptimisticHead","previousMessage","trailingUserLeaf","every","movedLeaf","draft","text","quote","custom","composer","restoreDraft","setTimeout","current","some","retractDraft","head","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Attachment } from \"../../types/attachment\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type {\n ExternalStoreAdapter,\n ExternalStoreBranchChange,\n} from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport type {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"../../runtime/queue/external-thread-queue-adapter\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\nimport type { QuoteInfo } from \"../../types/quote\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n refetchThread: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n // A getter, not a method, so its presence tracks the adapter.\n public get unstable_refetchThread(): (() => Promise<void>) | undefined {\n if (!this._store.onRefetchThread) return undefined;\n return () => this._store.onRefetchThread!();\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n private _transformedQueue: ExternalThreadQueueAdapter | undefined;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (oldStore?.queue !== store.queue) {\n this._transformedQueue = undefined;\n store.queue?.__internal_setDispatchTransform?.((message) => {\n // Re-point at the tail, as LocalThreadRuntimeCore's driver does, so\n // the prefix gated against is the one the message lands on whatever\n // the host routes by. Queuing only ever accepts a tail append, so a\n // later tail is the same intent.\n const parentId = this.messages.at(-1)?.id ?? null;\n return this.enrichAppendMetadata({ ...message, parentId }, parentId);\n });\n if (store.queue?.__internal_setDispatchTransform)\n this._transformedQueue = store.queue;\n }\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n refetchThread: this._store.onRefetchThread !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n const incoming = store.messageRepository.messages;\n const headId =\n store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;\n\n if (oldStore && oldStore.messageRepository === store.messageRepository) {\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n } else {\n const incomingIds = new Set(incoming.map(({ message }) => message.id));\n for (const { message, parentId } of incoming) {\n this.repository.addOrUpdateMessage(parentId, message);\n }\n for (const { message } of this.repository.export().messages) {\n if (!incomingIds.has(message.id)) {\n this.repository.deleteMessage(message.id);\n }\n }\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n }\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n const seenIds = new Set<string>();\n const deduped: ThreadMessage[] = [];\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]!;\n if (seenIds.has(message.id)) {\n console.warn(\n `ExternalStoreThreadRuntimeCore: duplicate message id \"${message.id}\" in the provided messages array; keeping the last occurrence.`,\n );\n continue;\n }\n seenIds.add(message.id);\n deduped.push(message);\n }\n if (deduped.length !== messages.length) messages = deduped.reverse();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n });\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n const onBranchChange = this._store.unstable_onBranchChange;\n const previousHeadId = onBranchChange\n ? this.repository.canonicalHeadId\n : null;\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n if (onBranchChange) {\n this._notifyBranchChange(previousHeadId, onBranchChange);\n }\n }\n\n /**\n * Emit `unstable_onBranchChange` for an explicit branch switch. Reads the\n * canonical head from the repository (which skips optimistic/transient\n * messages) and de-dupes switches that leave the canonical head unchanged.\n * Comparing against the head observed just before the switch — rather than the\n * last emitted head — keeps a switch firing after an adapter resync moved the\n * head elsewhere in the meantime.\n */\n private _notifyBranchChange(\n previousHeadId: string | null,\n onBranchChange: (event: ExternalStoreBranchChange) => void,\n ): void {\n const headId = this.repository.canonicalHeadId;\n if (headId === previousHeadId) return;\n\n onBranchChange({\n headId,\n visibleMessageIds: this.repository.getMessages().map((m) => m.id),\n });\n }\n\n public async append(rawMessage: AppendMessage): Promise<void> {\n // sourceId marks an edit send; the parent may coincide with the head\n // after a resync (e.g. cancelRun dropped the edited message).\n const isEdit =\n rawMessage.sourceId != null ||\n rawMessage.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // Buffering does not start a run, so the tool-abort below must wait until\n // the queue flushes. By then the prior run (and its tools) has settled.\n if (!isEdit && this._store.queue) {\n // Skip only for the queue this core actually installed on: another\n // core's transform would gate against its own thread's messages.\n const queued =\n this._store.queue === this._transformedQueue\n ? rawMessage\n : this.enrichAppendMetadata(rawMessage);\n if (queued.steer ?? this._store.isRunning ?? false)\n this._store.queue.steer(queued);\n else this._store.queue.enqueue(queued);\n return;\n }\n\n const message = this.enrichAppendMetadata(rawMessage);\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems() {\n return this._store?.queue?.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement) {\n this._store?.queue?.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. We only clear adapter-side\n // tool statuses when the tracker is the source of truth — otherwise\n // we'd wipe statuses the adapter is managing on its own.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._store.setToolStatuses?.({});\n }\n\n this._store.onLoadExternalState(state);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n // Before the run is aborted, so the settle it produces keeps the pending\n // items instead of dispatching the next one at the moment the user\n // stopped.\n this._store.queue?.__internal_notifyCancelled?.();\n\n this._store.onCancel();\n\n this.dropEmptyOptimisticHead();\n\n const messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n const trailingUserLeaf =\n this._store.setMessages !== undefined &&\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id && // ensure the previous message is a leaf node\n previousMessage.content.every((part) => part.type === \"text\")\n ? previousMessage\n : undefined;\n\n // Handing the message to the composer and taking it out of the thread are\n // one move: the composer refuses while the user is writing, and removing\n // the message then would leave it nowhere. A message the composer cannot\n // hold whole, carrying content parts it has no home for, is not moved.\n let movedLeaf:\n | {\n id: string;\n draft: {\n text: string;\n attachments: readonly Attachment[];\n quote: QuoteInfo | undefined;\n };\n }\n | undefined;\n if (trailingUserLeaf) {\n const draft = {\n text: getThreadMessageText(trailingUserLeaf),\n attachments: trailingUserLeaf.attachments,\n quote: trailingUserLeaf.metadata.custom.quote as QuoteInfo | undefined,\n };\n if (this.composer.restoreDraft(draft)) {\n this.repository.deleteMessage(trailingUserLeaf.id);\n movedLeaf = { id: trailingUserLeaf.id, draft };\n }\n }\n if (!movedLeaf) this._notifySubscribers();\n\n // The resync commits what the cancel left (a kept optimistic message, the\n // restored branch) back to the store a macrotask later. The store may move\n // in that gap; a server settling the cancelled turn lands in the same\n // tick. Read the repository at flush time and re-apply the rollbacks to\n // it, instead of stamping a snapshot captured above over the newer state.\n setTimeout(() => {\n this.dropEmptyOptimisticHead();\n if (movedLeaf) {\n const current = this.repository.getMessages();\n if (current.at(-1)?.id === movedLeaf.id) {\n // Unanswered tail: the removal has not reached the store yet.\n this.repository.deleteMessage(movedLeaf.id);\n } else if (current.some((m) => m.id === movedLeaf.id)) {\n // The store kept the turn in the thread; take the untouched draft\n // back so the same content does not sit in both places.\n this.composer.retractDraft(movedLeaf.draft);\n }\n }\n this.updateMessages(this.repository.getMessages());\n }, 0);\n }\n\n // Placeholder or pre-stream message; a partially-streamed one is kept and\n // committed to the store by the cancel resync.\n private dropEmptyOptimisticHead(): void {\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult?.(options);\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n this._store.onRespondToToolApproval(options);\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage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BiF,SAAuC;EAClE,IAAI,CAAC,KAAKvK,OAAO8K,yBACf,MAAM,IAAI9J,MAAM,0CAA0C;EAC5D,KAAKhB,OAAO8K,wBAAwBP,OAAO;CAC7C;CAEA,MAAsBQ,iBAAgD;EACpE,MAAMC,OAAO,IAAIxN,kBAAkB;EACnCwN,KAAKC,OAAO1N,0BAA0B2N,UAAUH,mBAAmB,CAAA,CAAE,CAAC;EACtE,KAAK7D,eAAe8D,KAAKtI,YAAY,CAAC;CACxC;CAEA,OAAuByI,MAAiC;EACtD,MAAMF,OAAOE,IAAI;EAEjB,IAAI,KAAKnL,OAAOoL,UACd,KAAKpL,OAAOoL,SAAS,KAAK5I,WAAWE,YAAY,CAAC;CAEtD;CAEA,kBAA0BjE,aAAuC;EAE/D,IADqB,KAAKuB,OAAOkD,mBAAmB3C,KAAAA,GAElD,KAAKP,OAAO8B,cAAcrD,SAAS6M,QAAQ7O,wBAAwB,CAAC;OAGpE,KAAKuD,OAAO8B,cAAcrD,QAA2B;CAEzD;AACF"}
|
|
1
|
+
{"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","Attachment","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","ExternalStoreBranchChange","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","ExternalThreadQueueAdapter","QueuePlacement","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","QuoteInfo","captureThreadRuntimeGeneration","isThreadRuntimeGenerationCurrent","EMPTY_ARRAY","Object","freeze","observeAdapterCallback","name","result","Promise","resolve","catch","error","console","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","unstable_refetchThread","onRefetchThread","undefined","suggestions","extras","_converter","_getInitializePromise","__internal_setGetInitializePromise","getPromise","_transformedQueue","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","__internal_setDispatchTransform","message","parentId","at","id","enrichAppendMetadata","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","incoming","headId","repository","resetHead","getMessages","incomingIds","Set","map","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","seenIds","deduped","i","warn","add","push","reverse","parent","ensureInitialized","_notifyEventSubscribers","optimisticId","content","metadata","isOptimistic","type","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","isError","artifact","modelContent","err","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","clear","visit","Array","isArray","part","set","get","branchId","onBranchChange","unstable_onBranchChange","previousHeadId","canonicalHeadId","updateMessages","_notifyBranchChange","event","visibleMessageIds","append","rawMessage","isEdit","sourceId","generation","initPromise","steer","enqueue","startRun","abort","onNew","messageIndex","findIndex","filter","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","unstable_notifySessionReset","__internal_notifyCancelled","cancelRun","dropEmptyOptimisticHead","previousMessage","trailingUserLeaf","every","movedLeaf","draft","text","quote","custom","composer","restoreDraft","setTimeout","current","some","retractDraft","head","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Attachment } from \"../../types/attachment\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type {\n ExternalStoreAdapter,\n ExternalStoreBranchChange,\n} from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport type {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"../../runtime/queue/external-thread-queue-adapter\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport {\n captureThreadRuntimeGeneration,\n isThreadRuntimeGenerationCurrent,\n} from \"../../runtime/utils/thread-runtime-lifecycle\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst observeAdapterCallback = (\n name: \"onAddToolResult\" | \"onRespondToToolApproval\" | \"onCancel\",\n result: Promise<void> | void,\n) => {\n void Promise.resolve(result).catch((error) => {\n console.error(\n `[ExternalStoreThreadRuntimeCore] ${name} callback rejected`,\n error,\n );\n });\n};\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n refetchThread: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n // A getter, not a method, so its presence tracks the adapter.\n public get unstable_refetchThread(): (() => Promise<void>) | undefined {\n if (!this._store.onRefetchThread) return undefined;\n return () => this._store.onRefetchThread!();\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n private _transformedQueue: ExternalThreadQueueAdapter | undefined;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (oldStore?.queue !== store.queue) {\n this._transformedQueue = undefined;\n store.queue?.__internal_setDispatchTransform?.((message) => {\n // Re-point at the tail, as LocalThreadRuntimeCore's driver does, so\n // the prefix gated against is the one the message lands on whatever\n // the host routes by. Queuing only ever accepts a tail append, so a\n // later tail is the same intent.\n const parentId = this.messages.at(-1)?.id ?? null;\n return this.enrichAppendMetadata({ ...message, parentId }, parentId);\n });\n if (store.queue?.__internal_setDispatchTransform)\n this._transformedQueue = store.queue;\n }\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n refetchThread: this._store.onRefetchThread !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n const incoming = store.messageRepository.messages;\n const headId =\n store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;\n\n if (oldStore && oldStore.messageRepository === store.messageRepository) {\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n } else {\n const incomingIds = new Set(incoming.map(({ message }) => message.id));\n for (const { message, parentId } of incoming) {\n this.repository.addOrUpdateMessage(parentId, message);\n }\n for (const { message } of this.repository.export().messages) {\n if (!incomingIds.has(message.id)) {\n this.repository.deleteMessage(message.id);\n }\n }\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n }\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n const seenIds = new Set<string>();\n const deduped: ThreadMessage[] = [];\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]!;\n if (seenIds.has(message.id)) {\n console.warn(\n `ExternalStoreThreadRuntimeCore: duplicate message id \"${message.id}\" in the provided messages array; keeping the last occurrence.`,\n );\n continue;\n }\n seenIds.add(message.id);\n deduped.push(message);\n }\n if (deduped.length !== messages.length) messages = deduped.reverse();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n observeAdapterCallback(\n \"onAddToolResult\",\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n }),\n );\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n const onBranchChange = this._store.unstable_onBranchChange;\n const previousHeadId = onBranchChange\n ? this.repository.canonicalHeadId\n : null;\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n if (onBranchChange) {\n this._notifyBranchChange(previousHeadId, onBranchChange);\n }\n }\n\n /**\n * Emit `unstable_onBranchChange` for an explicit branch switch. Reads the\n * canonical head from the repository (which skips optimistic/transient\n * messages) and de-dupes switches that leave the canonical head unchanged.\n * Comparing against the head observed just before the switch — rather than the\n * last emitted head — keeps a switch firing after an adapter resync moved the\n * head elsewhere in the meantime.\n */\n private _notifyBranchChange(\n previousHeadId: string | null,\n onBranchChange: (event: ExternalStoreBranchChange) => void,\n ): void {\n const headId = this.repository.canonicalHeadId;\n if (headId === previousHeadId) return;\n\n onBranchChange({\n headId,\n visibleMessageIds: this.repository.getMessages().map((m) => m.id),\n });\n }\n\n public async append(rawMessage: AppendMessage): Promise<void> {\n // sourceId marks an edit send; the parent may coincide with the head\n // after a resync (e.g. cancelRun dropped the edited message).\n const isEdit =\n rawMessage.sourceId != null ||\n rawMessage.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // A transformed-queue send is stamped at flush; any other queue's\n // transform would gate against its own thread's messages, so those stamp\n // at send.\n const message =\n !isEdit &&\n this._store.queue &&\n this._store.queue === this._transformedQueue\n ? rawMessage\n : this.enrichAppendMetadata(rawMessage);\n\n const generation = captureThreadRuntimeGeneration(this);\n this.ensureInitialized();\n\n // The getter call is what starts thread initialization.\n const initPromise = this._getInitializePromise?.();\n\n // The queue driver dispatches through the host adapter, outside this\n // core, so the initialization barrier must run before a message can\n // enter the queue.\n if (!isEdit && this._store.queue) {\n if (initPromise) {\n await initPromise;\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n\n // Buffering does not start a run, so the tool-abort below must wait\n // until the queue flushes. By then the prior run (and its tools) has\n // settled.\n if (message.steer ?? this._store.isRunning ?? false)\n this._store.queue.steer(message);\n else this._store.queue.enqueue(message);\n return;\n }\n\n // The optimistic insert lives inside the adapter's dispatch, so holding\n // `onNew` on initialization would keep the message off screen for the\n // whole roundtrip. Seams that need the remote identity await\n // `threadListItem.initialize()` themselves, and a rejection surfaces\n // there.\n void initPromise?.catch(() => {});\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems() {\n return this._store?.queue?.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement) {\n this._store?.queue?.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. The tracker publishes the\n // cleared status map itself, so adapter-side statuses reset only when\n // the tracker is the source of truth.\n this._toolInvocations?.reset();\n\n this._store.onLoadExternalState(state);\n }\n\n /**\n * Adapter-facing notification that the backing session was discarded.\n * Clears session-scoped tool-invocation state and parks queued work,\n * without run-cancel semantics (`onCancel`, composer draft restoration).\n */\n public unstable_notifySessionReset(): void {\n this._toolInvocations?.reset();\n this._store.queue?.__internal_notifyCancelled?.();\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n // Before the run is aborted, so the settle it produces keeps the pending\n // items instead of dispatching the next one at the moment the user\n // stopped.\n this._store.queue?.__internal_notifyCancelled?.();\n\n observeAdapterCallback(\"onCancel\", this._store.onCancel());\n\n this.dropEmptyOptimisticHead();\n\n const messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n const trailingUserLeaf =\n this._store.setMessages !== undefined &&\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id && // ensure the previous message is a leaf node\n previousMessage.content.every((part) => part.type === \"text\")\n ? previousMessage\n : undefined;\n\n // Handing the message to the composer and taking it out of the thread are\n // one move: the composer refuses while the user is writing, and removing\n // the message then would leave it nowhere. A message the composer cannot\n // hold whole, carrying content parts it has no home for, is not moved.\n let movedLeaf:\n | {\n id: string;\n draft: {\n text: string;\n attachments: readonly Attachment[];\n quote: QuoteInfo | undefined;\n };\n }\n | undefined;\n if (trailingUserLeaf) {\n const draft = {\n text: getThreadMessageText(trailingUserLeaf),\n attachments: trailingUserLeaf.attachments,\n quote: trailingUserLeaf.metadata.custom.quote as QuoteInfo | undefined,\n };\n if (this.composer.restoreDraft(draft)) {\n this.repository.deleteMessage(trailingUserLeaf.id);\n movedLeaf = { id: trailingUserLeaf.id, draft };\n }\n }\n if (!movedLeaf) this._notifySubscribers();\n\n // The resync commits what the cancel left (a kept optimistic message, the\n // restored branch) back to the store a macrotask later. The store may move\n // in that gap; a server settling the cancelled turn lands in the same\n // tick. Read the repository at flush time and re-apply the rollbacks to\n // it, instead of stamping a snapshot captured above over the newer state.\n setTimeout(() => {\n this.dropEmptyOptimisticHead();\n if (movedLeaf) {\n const current = this.repository.getMessages();\n if (current.at(-1)?.id === movedLeaf.id) {\n // Unanswered tail: the removal has not reached the store yet.\n this.repository.deleteMessage(movedLeaf.id);\n } else if (current.some((m) => m.id === movedLeaf.id)) {\n // The store kept the turn in the thread; take the untouched draft\n // back so the same content does not sit in both places.\n this.composer.retractDraft(movedLeaf.draft);\n }\n }\n this.updateMessages(this.repository.getMessages());\n }, 0);\n }\n\n // Placeholder or pre-stream message; a partially-streamed one is kept and\n // committed to the store by the cancel resync.\n private dropEmptyOptimisticHead(): void {\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n observeAdapterCallback(\n \"onAddToolResult\",\n this._store.onAddToolResult(options),\n );\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n observeAdapterCallback(\n \"onRespondToToolApproval\",\n this._store.onRespondToToolApproval(options),\n );\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage[]);\n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local-thread-runtime-core.js";
|
|
|
4
4
|
import { LocalThreadFactory, LocalThreadListRuntimeCore } from "./local/local-thread-list-runtime-core.js";
|
|
5
5
|
import { LocalRuntimeCore } from "./local/local-runtime-core.js";
|
|
6
6
|
import { shouldContinue } from "./local/should-continue.js";
|
|
7
|
+
import { RemoteThreadInitializeResponse, RemoteThreadListOptions } from "./remote-thread-list/types.js";
|
|
7
8
|
import { ExternalStoreThreadRuntimeCore, hasUpcomingMessage } from "./external-store/external-store-thread-runtime-core.js";
|
|
8
9
|
import { ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore } from "./external-store/external-store-thread-list-runtime-core.js";
|
|
9
10
|
import { ExternalStoreRuntimeCore } from "./external-store/external-store-runtime-core.js";
|
|
@@ -11,6 +12,5 @@ import { ConverterCallback, ThreadMessageConverter } from "./external-store/thre
|
|
|
11
12
|
import { ReadonlyThreadRuntimeCore } from "./readonly/ReadonlyThreadRuntimeCore.js";
|
|
12
13
|
import { OptimisticState } from "./remote-thread-list/optimistic-state.js";
|
|
13
14
|
import { EMPTY_THREAD_CORE } from "./remote-thread-list/empty-thread-core.js";
|
|
14
|
-
import { RemoteThreadInitializeResponse, RemoteThreadListOptions } from "./remote-thread-list/types.js";
|
|
15
15
|
import { RemoteThreadData, RemoteThreadState, THREAD_MAPPING_ID, createThreadMappingId, getThreadData, updateStatusReducer } from "./remote-thread-list/remote-thread-state.js";
|
|
16
16
|
export { type ConverterCallback, EMPTY_THREAD_CORE, ExternalStoreRuntimeCore, type ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LocalRuntimeCore, type LocalRuntimeOptionsBase, type LocalThreadFactory, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, OptimisticState, ReadonlyThreadRuntimeCore, type RemoteThreadData, type RemoteThreadInitializeResponse, type RemoteThreadListOptions, type RemoteThreadState, type THREAD_MAPPING_ID, ThreadMessageConverter, ToolInvocationTracker, createThreadMappingId, getThreadData, hasUpcomingMessage, shouldContinue, updateStatusReducer };
|
|
@@ -66,17 +66,20 @@ declare class LocalThreadRuntimeCore extends BaseThreadRuntimeCore implements Th
|
|
|
66
66
|
get extras(): undefined;
|
|
67
67
|
__internal_setOptions(options: LocalRuntimeOptionsBase): void;
|
|
68
68
|
private _loadPromise;
|
|
69
|
+
private _loadRequested;
|
|
69
70
|
__internal_load(): Promise<void>;
|
|
70
71
|
append(message: AppendMessage): Promise<void>;
|
|
71
72
|
getQueueItems(): readonly QueueItemState[];
|
|
72
73
|
getSteerQueueItems(): readonly QueueItemState[];
|
|
73
74
|
moveQueueItem(queueItemId: string, placement: QueuePlacement): void;
|
|
74
75
|
removeQueueItem(queueItemId: string): void;
|
|
76
|
+
private _rollbackAppend;
|
|
75
77
|
private _runAppend;
|
|
76
78
|
deleteMessage(messageId: string): Promise<void>;
|
|
77
79
|
resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void>;
|
|
78
80
|
exportExternalState(): any;
|
|
79
81
|
importExternalState(): void;
|
|
82
|
+
unstable_notifySessionReset(): void;
|
|
80
83
|
startRun({ parentId, runConfig }: StartRunConfig, runCallback?: ChatModelAdapter["run"]): Promise<void>;
|
|
81
84
|
private _runLoop;
|
|
82
85
|
private performRoundtrip;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"local-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;;cAmDa,+BACH,iCACG;WAEK;;;;;;;;;;;;;;;;UAiBR;UAEA;UACA;UACA;UACA;UAEA;UAIA;UAuBA;WAYQ;WACA;UAER;MACG;UAIH;UACA;MACG,wBAAwB;MAIxB;;;;;;;;;;EAKT,YAAA,iBAAiB,sBACjB,SAAS;UAMH;UAEA;UAEA;EAED,0BAA0B;UAIzB;EAED,mCACL,kBAAkB;MAKT;EAIJ,sBAAsB,SAAS;UA6F9B;UACA;EACD,mBAAe;EAyCT,OAAO,SAAS,gBAAgB;EAkBtC,0BAA0B;EAM1B,+BAA+B;EAI/B,cAAc,qBAAqB,WAAW;EAI9C,gBAAgB;UAIf;UASM;EA4DD,cAAc,oBAAoB;EAmBxC,YAAY,WAAW,eAAe,kBAAkB;EAMxD;EAIA;EAIA;EAIM,WACT,UAAU,aAAa,gBACzB,cAAc,0BACb;UAuBW;UA2EA;EAkMP;EAWA;EAgBA,gBACL,WACA,YACA,QACA,SACA,YACC;EA6CI,eAAe,UAAU;EAMzB,wBACL,YACA,UACA,UACA,UACC"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { generateId } from "../../utils/id.js";
|
|
2
2
|
import { consumeSuggestionResult } from "../../adapters/suggestion.js";
|
|
3
|
-
import { toAssistantError } from "../../types/error.js";
|
|
3
|
+
import { MessageNotSentError, toAssistantError } from "../../types/error.js";
|
|
4
4
|
import { fromThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
|
|
5
5
|
import { EMPTY_QUEUE_ITEMS } from "../../store/scopes/queue-item.js";
|
|
6
6
|
import { createMessageQueue } from "../../runtime/queue/message-queue.js";
|
|
7
7
|
import { BaseThreadRuntimeCore } from "../../runtime/base/base-thread-runtime-core.js";
|
|
8
8
|
import { shouldContinue } from "./should-continue.js";
|
|
9
|
+
import { captureThreadRuntimeGeneration, invalidateThreadRuntime, isThreadRuntimeGenerationCurrent } from "../../runtime/utils/thread-runtime-lifecycle.js";
|
|
9
10
|
//#region src/runtimes/local/local-thread-runtime-core.ts
|
|
10
11
|
var AbortError = class extends Error {
|
|
11
12
|
name = "AbortError";
|
|
@@ -90,6 +91,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
90
91
|
get extras() {}
|
|
91
92
|
__internal_setOptions(options) {
|
|
92
93
|
if (this._options === options) return;
|
|
94
|
+
const previousHistory = this._options?.adapters.history;
|
|
93
95
|
this._options = options;
|
|
94
96
|
let hasUpdates = false;
|
|
95
97
|
const canSpeak = options.adapters?.speech !== void 0;
|
|
@@ -142,11 +144,17 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
142
144
|
hasUpdates = true;
|
|
143
145
|
}
|
|
144
146
|
if (hasUpdates) this._notifySubscribers();
|
|
147
|
+
if (this._loadRequested && !this._loadPromise && !previousHistory && options.adapters.history && this.messages.length === 0) this.__internal_load().catch((error) => {
|
|
148
|
+
console.error("[assistant-ui] local thread history load failed:", error);
|
|
149
|
+
});
|
|
145
150
|
}
|
|
146
151
|
_loadPromise;
|
|
152
|
+
_loadRequested = false;
|
|
147
153
|
__internal_load() {
|
|
154
|
+
this._loadRequested = true;
|
|
148
155
|
if (this._loadPromise) return this._loadPromise;
|
|
149
|
-
|
|
156
|
+
if (!this.adapters.history) return Promise.resolve();
|
|
157
|
+
const promise = this.adapters.history.load();
|
|
150
158
|
this._isLoading = true;
|
|
151
159
|
this._notifySubscribers();
|
|
152
160
|
this._loadPromise = promise.then((repo) => {
|
|
@@ -189,29 +197,56 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
189
197
|
removeQueueItem(queueItemId) {
|
|
190
198
|
this._queue?.adapter.remove(queueItemId);
|
|
191
199
|
}
|
|
200
|
+
_rollbackAppend(messageId) {
|
|
201
|
+
try {
|
|
202
|
+
this.repository.deleteMessage(messageId);
|
|
203
|
+
} catch {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
this._notifySubscribers();
|
|
207
|
+
}
|
|
192
208
|
async _runAppend(rawMessage) {
|
|
209
|
+
const generation = captureThreadRuntimeGeneration(this);
|
|
193
210
|
const message = this.enrichAppendMetadata(rawMessage);
|
|
194
211
|
this.ensureInitialized();
|
|
195
|
-
const initPromise = this._getInitializePromise?.();
|
|
196
|
-
if (initPromise) await initPromise;
|
|
197
212
|
const newMessage = fromThreadMessageLike(message, generateId(), {
|
|
198
213
|
type: "complete",
|
|
199
214
|
reason: "unknown"
|
|
200
215
|
});
|
|
201
216
|
this.repository.addOrUpdateMessage(message.parentId, newMessage);
|
|
202
|
-
this.
|
|
217
|
+
this._notifySubscribers();
|
|
218
|
+
try {
|
|
219
|
+
const initPromise = this._getInitializePromise?.();
|
|
220
|
+
if (initPromise) await initPromise;
|
|
221
|
+
} catch (error) {
|
|
222
|
+
this._rollbackAppend(newMessage.id);
|
|
223
|
+
if (!isThreadRuntimeGenerationCurrent(this, generation)) return;
|
|
224
|
+
const notSent = new MessageNotSentError();
|
|
225
|
+
notSent.cause = error;
|
|
226
|
+
throw notSent;
|
|
227
|
+
}
|
|
228
|
+
if (!isThreadRuntimeGenerationCurrent(this, generation)) {
|
|
229
|
+
this._rollbackAppend(newMessage.id);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const historyWrite = this._options.adapters.history?.append({
|
|
203
233
|
parentId: message.parentId,
|
|
204
234
|
message: newMessage,
|
|
205
235
|
...message.runConfig !== void 0 && { runConfig: message.runConfig }
|
|
206
236
|
});
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
237
|
+
historyWrite?.catch(() => {});
|
|
238
|
+
if (message.startRun ?? message.role === "user") {
|
|
239
|
+
const [runResult, historyResult] = await Promise.allSettled([this.startRun({
|
|
240
|
+
parentId: newMessage.id,
|
|
241
|
+
sourceId: message.sourceId,
|
|
242
|
+
runConfig: message.runConfig ?? {}
|
|
243
|
+
}), historyWrite]);
|
|
244
|
+
if (runResult.status === "rejected") throw runResult.reason;
|
|
245
|
+
if (historyResult.status === "rejected") throw historyResult.reason;
|
|
246
|
+
} else {
|
|
213
247
|
this.repository.resetHead(newMessage.id);
|
|
214
248
|
this._notifySubscribers();
|
|
249
|
+
await historyWrite;
|
|
215
250
|
}
|
|
216
251
|
}
|
|
217
252
|
async deleteMessage(messageId) {
|
|
@@ -239,6 +274,9 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
239
274
|
importExternalState() {
|
|
240
275
|
throw new Error("Runtime does not support importing external states.");
|
|
241
276
|
}
|
|
277
|
+
unstable_notifySessionReset() {
|
|
278
|
+
throw new Error("Runtime does not support resetting sessions.");
|
|
279
|
+
}
|
|
242
280
|
async startRun({ parentId, runConfig }, runCallback) {
|
|
243
281
|
this.ensureInitialized();
|
|
244
282
|
const message = {
|
|
@@ -263,6 +301,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
263
301
|
const run = { cancelled: false };
|
|
264
302
|
this._activeRun = run;
|
|
265
303
|
this._runGeneration++;
|
|
304
|
+
let active = false;
|
|
266
305
|
try {
|
|
267
306
|
this._queue?.notifyBusy();
|
|
268
307
|
this._suggestions = [];
|
|
@@ -275,11 +314,11 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
275
314
|
} while (shouldContinue(message, this._options.unstable_humanToolNames));
|
|
276
315
|
} finally {
|
|
277
316
|
this._notifyEventSubscribers("runEnd", {});
|
|
278
|
-
|
|
317
|
+
active = this._activeRun === run;
|
|
279
318
|
if (active) this._activeRun = null;
|
|
280
319
|
if (active || run.cancelled) queueMicrotask(() => this._queue?.notifyIdle());
|
|
281
320
|
}
|
|
282
|
-
if (this.adapters.suggestion && message.status?.type !== "requires-action") {
|
|
321
|
+
if (active && this.adapters.suggestion && message.status?.type !== "requires-action") {
|
|
283
322
|
this._suggestionsController = new AbortController();
|
|
284
323
|
const signal = this._suggestionsController.signal;
|
|
285
324
|
const adapter = this.adapters.suggestion;
|
|
@@ -419,6 +458,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
419
458
|
return message;
|
|
420
459
|
}
|
|
421
460
|
detach() {
|
|
461
|
+
invalidateThreadRuntime(this);
|
|
422
462
|
this._queue = null;
|
|
423
463
|
const error = new AbortError(true);
|
|
424
464
|
this.abortController?.abort(error);
|