@assistant-ui/core 0.3.17 → 0.3.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/attachment.d.ts.map +1 -1
- package/dist/adapters/attachment.js +5 -4
- package/dist/adapters/attachment.js.map +1 -1
- package/dist/adapters/speech.d.ts.map +1 -1
- package/dist/adapters/speech.js +13 -3
- package/dist/adapters/speech.js.map +1 -1
- package/dist/adapters/thread-history.d.ts +4 -0
- package/dist/adapters/thread-history.d.ts.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +4 -3
- package/dist/internal.js +3 -2
- package/dist/model-context/frame/host.d.ts.map +1 -1
- package/dist/model-context/frame/host.js +35 -14
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/frame/provider.d.ts +2 -0
- package/dist/model-context/frame/provider.d.ts.map +1 -1
- package/dist/model-context/frame/provider.js +30 -7
- package/dist/model-context/frame/provider.js.map +1 -1
- package/dist/model-context/interactable-composer-metadata.d.ts.map +1 -1
- package/dist/model-context/interactable-composer-metadata.js +27 -18
- package/dist/model-context/interactable-composer-metadata.js.map +1 -1
- package/dist/model-context/registry.d.ts.map +1 -1
- package/dist/model-context/registry.js +3 -5
- package/dist/model-context/registry.js.map +1 -1
- package/dist/model-context/types.d.ts.map +1 -1
- package/dist/model-context/types.js +5 -4
- package/dist/model-context/types.js.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js +45 -7
- package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
- package/dist/react/client/DataRenderers.d.ts.map +1 -1
- package/dist/react/client/DataRenderers.js +20 -15
- package/dist/react/client/DataRenderers.js.map +1 -1
- package/dist/react/client/InMemoryThreadList.d.ts.map +1 -1
- package/dist/react/client/InMemoryThreadList.js +62 -56
- package/dist/react/client/InMemoryThreadList.js.map +1 -1
- package/dist/react/client/Interactables.d.ts.map +1 -1
- package/dist/react/client/Interactables.js +35 -32
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/RemoteThreadList.d.ts +1 -0
- package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
- package/dist/react/client/RemoteThreadList.js +154 -143
- package/dist/react/client/RemoteThreadList.js.map +1 -1
- package/dist/react/client/Tools.d.ts.map +1 -1
- package/dist/react/client/Tools.js +18 -16
- package/dist/react/client/Tools.js.map +1 -1
- package/dist/react/client/interactable-model-context.d.ts.map +1 -1
- package/dist/react/client/interactable-model-context.js +3 -2
- package/dist/react/client/interactable-model-context.js.map +1 -1
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +2 -2
- package/dist/react/interactables-legacy/Interactables.js +242 -121
- package/dist/react/interactables-legacy/Interactables.js.map +1 -1
- package/dist/react/interactables-legacy/useAssistantInteractable.d.ts.map +1 -1
- package/dist/react/interactables-legacy/useAssistantInteractable.js +3 -0
- package/dist/react/interactables-legacy/useAssistantInteractable.js.map +1 -1
- package/dist/react/interactables-shared/useInteractablePersistenceQueue.d.ts.map +1 -1
- package/dist/react/interactables-shared/useInteractablePersistenceQueue.js +11 -9
- package/dist/react/interactables-shared/useInteractablePersistenceQueue.js.map +1 -1
- package/dist/react/model-context/makeAssistantTool.d.ts +2 -2
- package/dist/react/model-context/makeAssistantTool.js +1 -1
- package/dist/react/model-context/makeAssistantTool.js.map +1 -1
- package/dist/react/model-context/useAssistantTool.d.ts +2 -2
- package/dist/react/model-context/useAssistantTool.js +1 -1
- package/dist/react/model-context/useAssistantTool.js.map +1 -1
- package/dist/react/model-context/useInteractable.d.ts.map +1 -1
- package/dist/react/model-context/useInteractable.js +4 -1
- package/dist/react/model-context/useInteractable.js.map +1 -1
- package/dist/react/model-context/useInteractableVersions.js +1 -1
- package/dist/react/model-context/useToolArgsStatus.d.ts.map +1 -1
- package/dist/react/model-context/useToolArgsStatus.js +2 -1
- package/dist/react/model-context/useToolArgsStatus.js.map +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.d.ts +11 -2
- package/dist/react/primitives/message/MessageGroupedParts.d.ts.map +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.js +3 -2
- package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
- package/dist/react/primitives/part/PartMessages.d.ts +1 -0
- package/dist/react/primitives/part/PartMessages.d.ts.map +1 -1
- package/dist/react/primitives/part/PartMessages.js +1 -0
- package/dist/react/primitives/part/PartMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.d.ts.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.js +6 -5
- package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +16 -8
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +5 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +105 -104
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadResource.d.ts +1 -0
- package/dist/react/runtimes/RemoteThreadResource.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadResource.js +13 -11
- package/dist/react/runtimes/RemoteThreadResource.js.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts +5 -24
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +354 -226
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts +1 -0
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js +22 -2
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.d.ts +40 -15
- package/dist/react/runtimes/cloud/auiV0.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.js +62 -15
- package/dist/react/runtimes/cloud/auiV0.js.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts +2 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js +6 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/sdkIdentity.d.ts +6 -0
- package/dist/react/runtimes/cloud/sdkIdentity.d.ts.map +1 -0
- package/dist/react/runtimes/cloud/sdkIdentity.js +9 -0
- package/dist/react/runtimes/cloud/sdkIdentity.js.map +1 -0
- package/dist/react/runtimes/external-message-converter.d.ts +12 -2
- package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
- package/dist/react/runtimes/external-message-converter.js +26 -61
- package/dist/react/runtimes/external-message-converter.js.map +1 -1
- package/dist/react/runtimes/useExternalStoreRuntime.js +75 -46
- package/dist/react/runtimes/useExternalStoreRuntime.js.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.d.ts.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js +64 -24
- package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
- package/dist/react/utils/groupParts.d.ts +6 -1
- package/dist/react/utils/groupParts.d.ts.map +1 -1
- package/dist/react/utils/groupParts.js +6 -0
- package/dist/react/utils/groupParts.js.map +1 -1
- package/dist/react/utils/useJSONEqual.d.ts +3 -1
- package/dist/react/utils/useJSONEqual.d.ts.map +1 -1
- package/dist/react/utils/useJSONEqual.js +6 -1
- package/dist/react/utils/useJSONEqual.js.map +1 -1
- package/dist/react/utils/useJSONSchemaDependency.d.ts +7 -0
- package/dist/react/utils/useJSONSchemaDependency.d.ts.map +1 -0
- package/dist/react/utils/useJSONSchemaDependency.js +20 -0
- package/dist/react/utils/useJSONSchemaDependency.js.map +1 -0
- package/dist/runtime/api/thread-list-item-runtime.d.ts +7 -3
- package/dist/runtime/api/thread-list-item-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-item-runtime.js +2 -2
- package/dist/runtime/api/thread-list-item-runtime.js.map +1 -1
- package/dist/runtime/api/thread-list-runtime.d.ts +3 -0
- package/dist/runtime/api/thread-list-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-runtime.js +18 -14
- package/dist/runtime/api/thread-list-runtime.js.map +1 -1
- package/dist/runtime/api/thread-runtime.d.ts +4 -0
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js +3 -6
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts +1 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +62 -22
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.d.ts +2 -0
- package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js +161 -69
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/interfaces/composer-runtime-core.d.ts +12 -5
- package/dist/runtime/interfaces/composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/interfaces/thread-list-runtime-core.d.ts +4 -1
- package/dist/runtime/interfaces/thread-list-runtime-core.d.ts.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/queue/message-queue.d.ts +5 -0
- package/dist/runtime/queue/message-queue.d.ts.map +1 -1
- package/dist/runtime/queue/message-queue.js +61 -6
- package/dist/runtime/queue/message-queue.js.map +1 -1
- package/dist/runtime/utils/auto-status.d.ts +6 -2
- package/dist/runtime/utils/auto-status.d.ts.map +1 -1
- package/dist/runtime/utils/auto-status.js +12 -4
- package/dist/runtime/utils/auto-status.js.map +1 -1
- package/dist/runtime/utils/external-message-conversion.d.ts +16 -4
- package/dist/runtime/utils/external-message-conversion.d.ts.map +1 -1
- package/dist/runtime/utils/external-message-conversion.js +49 -13
- package/dist/runtime/utils/external-message-conversion.js.map +1 -1
- package/dist/runtime/utils/message-repository.d.ts +1 -0
- package/dist/runtime/utils/message-repository.d.ts.map +1 -1
- package/dist/runtime/utils/message-repository.js +18 -9
- package/dist/runtime/utils/message-repository.js.map +1 -1
- package/dist/runtime/utils/thread-message-like.d.ts +2 -1
- package/dist/runtime/utils/thread-message-like.d.ts.map +1 -1
- package/dist/runtime/utils/thread-message-like.js +5 -3
- package/dist/runtime/utils/thread-message-like.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 +21 -27
- 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.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js +8 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/internal.d.ts +3 -3
- package/dist/runtimes/internal.js +2 -2
- package/dist/runtimes/local/local-thread-runtime-core.d.ts +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +4 -1
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts +18 -1
- package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/remote-thread-state.js +130 -42
- package/dist/runtimes/remote-thread-list/remote-thread-state.js.map +1 -1
- package/dist/runtimes/remote-thread-list/title-generation.d.ts +49 -0
- package/dist/runtimes/remote-thread-list/title-generation.d.ts.map +1 -0
- package/dist/runtimes/remote-thread-list/title-generation.js +197 -0
- package/dist/runtimes/remote-thread-list/title-generation.js.map +1 -0
- package/dist/runtimes/remote-thread-list/title.d.ts +3 -1
- package/dist/runtimes/remote-thread-list/title.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/title.js +9 -1
- package/dist/runtimes/remote-thread-list/title.js.map +1 -1
- package/dist/runtimes/remote-thread-list/types.d.ts +10 -0
- package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +2 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
- package/dist/store/clients/external-thread.d.ts.map +1 -1
- package/dist/store/clients/external-thread.js +260 -203
- package/dist/store/clients/external-thread.js.map +1 -1
- package/dist/store/clients/model-context-client.d.ts.map +1 -1
- package/dist/store/clients/model-context-client.js +2 -1
- package/dist/store/clients/model-context-client.js.map +1 -1
- package/dist/store/clients/single-thread-list.d.ts.map +1 -1
- package/dist/store/clients/single-thread-list.js +1 -0
- package/dist/store/clients/single-thread-list.js.map +1 -1
- package/dist/store/clients/suggestions.d.ts.map +1 -1
- package/dist/store/clients/suggestions.js +5 -4
- package/dist/store/clients/suggestions.js.map +1 -1
- package/dist/store/clients/thread-tasks.d.ts +13 -0
- package/dist/store/clients/thread-tasks.d.ts.map +1 -0
- package/dist/store/clients/thread-tasks.js +69 -0
- package/dist/store/clients/thread-tasks.js.map +1 -0
- package/dist/store/index.d.ts +3 -2
- package/dist/store/index.js +3 -3
- package/dist/store/primitive-predicates.d.ts.map +1 -1
- package/dist/store/primitive-predicates.js +4 -4
- package/dist/store/primitive-predicates.js.map +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.d.ts +1 -0
- package/dist/store/runtime-clients/composer-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.js +97 -61
- package/dist/store/runtime-clients/composer-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/message-runtime-client.d.ts +1 -0
- package/dist/store/runtime-clients/message-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/message-runtime-client.js +221 -144
- package/dist/store/runtime-clients/message-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js +1 -1
- 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 +54 -52
- package/dist/store/runtime-clients/thread-list-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.js +246 -126
- package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
- package/dist/store/scope-registration.d.ts +2 -0
- package/dist/store/scope-registration.d.ts.map +1 -1
- package/dist/store/scopes/composer.d.ts +10 -2
- package/dist/store/scopes/composer.d.ts.map +1 -1
- package/dist/store/scopes/message.d.ts +30 -1
- package/dist/store/scopes/message.d.ts.map +1 -1
- package/dist/store/scopes/task.d.ts +36 -0
- package/dist/store/scopes/task.d.ts.map +1 -0
- package/dist/store/scopes/task.js +0 -0
- package/dist/store/scopes/thread-list-item.d.ts +2 -2
- package/dist/store/scopes/thread-list-item.d.ts.map +1 -1
- package/dist/store/scopes/thread.d.ts +28 -0
- package/dist/store/scopes/thread.d.ts.map +1 -1
- package/dist/store/scopes/threads.d.ts +1 -0
- 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 -15
- package/dist/subscribable/subscribable.js.map +1 -1
- package/dist/types/attachment.d.ts +2 -1
- package/dist/types/attachment.d.ts.map +1 -1
- package/dist/types/attachment.js +2 -1
- package/dist/types/attachment.js.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/message.d.ts +8 -1
- package/dist/types/message.d.ts.map +1 -1
- package/dist/types/message.js.map +1 -1
- package/dist/utils/abortable-iterable.d.ts +19 -0
- package/dist/utils/abortable-iterable.d.ts.map +1 -0
- package/dist/utils/abortable-iterable.js +88 -0
- package/dist/utils/abortable-iterable.js.map +1 -0
- package/dist/utils/composite-context-provider.d.ts.map +1 -1
- package/dist/utils/composite-context-provider.js +20 -2
- package/dist/utils/composite-context-provider.js.map +1 -1
- package/dist/utils/getGroupStatus.d.ts +18 -2
- package/dist/utils/getGroupStatus.d.ts.map +1 -1
- package/dist/utils/getGroupStatus.js +32 -7
- package/dist/utils/getGroupStatus.js.map +1 -1
- package/dist/utils/record.d.ts +11 -0
- package/dist/utils/record.d.ts.map +1 -0
- package/dist/utils/record.js +12 -0
- package/dist/utils/record.js.map +1 -0
- package/dist/utils/wire-media.d.ts.map +1 -1
- package/dist/utils/wire-media.js +2 -2
- package/dist/utils/wire-media.js.map +1 -1
- package/package.json +11 -11
- package/src/adapters/attachment.test.ts +50 -1
- package/src/adapters/attachment.ts +7 -4
- package/src/adapters/speech.test.ts +236 -0
- package/src/adapters/speech.ts +17 -10
- package/src/adapters/thread-history.ts +3 -0
- package/src/index.ts +2 -0
- package/src/internal.ts +4 -0
- package/src/model-context/frame/host.test.ts +137 -1
- package/src/model-context/frame/host.ts +49 -16
- package/src/model-context/frame/provider.test.ts +71 -0
- package/src/model-context/frame/provider.ts +37 -7
- package/src/model-context/interactable-composer-metadata.test.ts +58 -0
- package/src/model-context/interactable-composer-metadata.ts +19 -13
- package/src/model-context/registry.test.ts +12 -0
- package/src/model-context/registry.ts +3 -2
- package/src/model-context/types.test.ts +25 -0
- package/src/model-context/types.ts +9 -4
- package/src/react/RuntimeAdapter.test.ts +34 -0
- package/src/react/adapters/LocalStorageThreadListAdapter.test.ts +244 -0
- package/src/react/adapters/LocalStorageThreadListAdapter.tsx +104 -7
- package/src/react/client/DataRenderers.test.tsx +45 -0
- package/src/react/client/DataRenderers.ts +13 -9
- package/src/react/client/InMemoryThreadList.ts +1 -0
- package/src/react/client/Interactables.test.ts +72 -1
- package/src/react/client/Interactables.ts +22 -14
- package/src/react/client/RemoteThreadList.background.test.ts +148 -6
- package/src/react/client/RemoteThreadList.concurrent.test.tsx +42 -1
- package/src/react/client/RemoteThreadList.test.ts +386 -4
- package/src/react/client/RemoteThreadList.ts +181 -112
- package/src/react/client/Tools.ts +22 -11
- package/src/react/client/interactable-model-context.test.ts +44 -0
- package/src/react/client/interactable-model-context.ts +3 -2
- package/src/react/index.ts +5 -1
- package/src/react/interactables-legacy/Interactables.ts +16 -16
- package/src/react/interactables-legacy/useAssistantInteractable.test.tsx +132 -0
- package/src/react/interactables-legacy/useAssistantInteractable.ts +10 -1
- package/src/react/interactables-shared/useInteractablePersistenceQueue.ts +9 -10
- package/src/react/model-context/makeAssistantTool.ts +2 -2
- package/src/react/model-context/useAssistantTool.ts +2 -2
- package/src/react/model-context/useInteractable.test.tsx +177 -0
- package/src/react/model-context/useInteractable.ts +3 -0
- package/src/react/model-context/useToolArgsStatus.test.tsx +30 -0
- package/src/react/model-context/useToolArgsStatus.ts +2 -1
- package/src/react/primitive-hooks/useActionBarCopy.test.ts +0 -1
- package/src/react/primitive-hooks/useSuggestionTrigger.test.ts +0 -1
- package/src/react/primitives/message/MessageGroupedParts.test.tsx +96 -0
- package/src/react/primitives/message/MessageGroupedParts.tsx +15 -4
- package/src/react/primitives/part/PartMessages.test.tsx +104 -1
- package/src/react/primitives/part/PartMessages.tsx +1 -0
- package/src/react/primitives/thread/ThreadMessages.test.tsx +142 -0
- package/src/react/primitives/thread/ThreadMessages.tsx +8 -5
- package/src/react/providers/ReadonlyThreadProvider.test.tsx +56 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.destroy.test.tsx +172 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.running.test.tsx +33 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.test.tsx +7 -1
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +28 -5
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.load-error.test.ts +132 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.switch-delete.test.ts +105 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +143 -112
- package/src/react/runtimes/RemoteThreadResource.test.ts +9 -0
- package/src/react/runtimes/RemoteThreadResource.ts +19 -12
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.ts +20 -14
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +703 -6
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +492 -402
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.test.ts +77 -0
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.ts +27 -1
- package/src/react/runtimes/cloud/auiV0.ts +160 -25
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.test.ts +36 -0
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.ts +8 -1
- package/src/react/runtimes/cloud/sdkIdentity.ts +9 -0
- package/src/react/runtimes/cloud/useCloudThreadListAdapter.test.tsx +18 -4
- package/src/react/runtimes/external-message-converter.test.ts +136 -1
- package/src/react/runtimes/external-message-converter.ts +39 -93
- package/src/react/runtimes/useExternalStoreRuntime.lifecycle.test.tsx +41 -0
- package/src/react/runtimes/useExternalStoreRuntime.ts +10 -4
- package/src/react/runtimes/useLocalRuntime.test.tsx +20 -0
- package/src/react/runtimes/useRemoteThreadListRuntime.load-error.test.tsx +108 -0
- package/src/react/runtimes/useRemoteThreadListRuntime.ts +34 -1
- package/src/react/utils/groupParts.ts +12 -1
- package/src/react/utils/useJSONEqual.ts +9 -0
- package/src/react/utils/useJSONSchemaDependency.ts +22 -0
- package/src/runtime/api/message-runtime.test.ts +75 -0
- package/src/runtime/api/thread-list-item-runtime.ts +10 -3
- package/src/runtime/api/thread-list-runtime.ts +21 -11
- package/src/runtime/api/thread-runtime.test.ts +136 -0
- package/src/runtime/api/thread-runtime.ts +10 -5
- package/src/runtime/base/base-composer-runtime-core.ts +105 -24
- package/src/runtime/base/base-thread-runtime-core.test.ts +1063 -2
- package/src/runtime/base/base-thread-runtime-core.ts +228 -87
- package/src/runtime/interfaces/composer-runtime-core.ts +10 -5
- package/src/runtime/interfaces/thread-list-runtime-core.ts +5 -1
- package/src/runtime/interfaces/thread-runtime-core.ts +6 -0
- package/src/runtime/queue/message-queue.ts +68 -6
- package/src/runtime/utils/auto-status.test.ts +112 -1
- package/src/runtime/utils/auto-status.ts +31 -5
- package/src/runtime/utils/external-message-conversion.test.ts +202 -0
- package/src/runtime/utils/external-message-conversion.ts +123 -32
- package/src/runtime/utils/message-repository.test.ts +49 -0
- package/src/runtime/utils/message-repository.ts +32 -20
- package/src/runtime/utils/thread-message-like.test.ts +52 -0
- package/src/runtime/utils/thread-message-like.ts +5 -1
- package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +18 -13
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +31 -1
- package/src/runtimes/internal.ts +1 -0
- package/src/runtimes/local/local-thread-runtime-core.test.ts +21 -0
- package/src/runtimes/local/local-thread-runtime-core.ts +11 -1
- package/src/runtimes/remote-thread-list/remote-thread-state.test.ts +128 -2
- package/src/runtimes/remote-thread-list/remote-thread-state.ts +182 -42
- package/src/runtimes/remote-thread-list/title-generation.test.ts +602 -0
- package/src/runtimes/remote-thread-list/title-generation.ts +329 -0
- package/src/runtimes/remote-thread-list/title.test.ts +62 -0
- package/src/runtimes/remote-thread-list/title.ts +13 -0
- package/src/runtimes/remote-thread-list/types.ts +10 -0
- package/src/runtimes/tool-invocations/EDGE_CASES.md +2 -6
- package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +133 -0
- package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +10 -6
- package/src/store/clients/external-thread.ts +67 -4
- package/src/store/clients/model-context-client.ts +5 -1
- package/src/store/clients/single-thread-list.ts +1 -0
- package/src/store/clients/suggestions.test.ts +40 -0
- package/src/store/clients/suggestions.ts +13 -10
- package/src/store/clients/thread-tasks.test.ts +274 -0
- package/src/store/clients/thread-tasks.ts +138 -0
- package/src/store/index.ts +8 -0
- package/src/store/primitive-predicates.test.ts +48 -5
- package/src/store/primitive-predicates.ts +7 -2
- package/src/store/runtime-clients/composer-runtime-client.ts +42 -9
- package/src/store/runtime-clients/message-runtime-client.ts +54 -6
- package/src/store/runtime-clients/thread-list-item-runtime-client.ts +4 -2
- package/src/store/runtime-clients/thread-list-runtime-client.ts +1 -0
- package/src/store/runtime-clients/thread-runtime-client.ts +89 -11
- package/src/store/scope-registration.ts +2 -0
- package/src/store/scopes/composer.ts +16 -4
- package/src/store/scopes/message.ts +14 -0
- package/src/store/scopes/task.ts +34 -0
- package/src/store/scopes/thread-list-item.ts +5 -2
- package/src/store/scopes/thread.ts +20 -0
- package/src/store/scopes/threads.ts +1 -0
- package/src/store/thread-tasks.test.tsx +209 -0
- package/src/subscribable/subscribable.test.ts +156 -1
- package/src/subscribable/subscribable.ts +25 -15
- package/src/tests/MessageRepository.test.ts +117 -5
- package/src/tests/OptimisticState-list-race.test.ts +1 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-initialize-adapter-change.test.ts +38 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-load-race.test.ts +47 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-title-race.test.ts +89 -0
- package/src/tests/attachment-adapters.test.ts +14 -0
- package/src/tests/auiV0Encode.test.ts +300 -0
- package/src/tests/base-composer-runtime-core-send.test.ts +51 -0
- package/src/tests/base-composer-runtime-core.test.ts +353 -2
- package/src/tests/external-store-thread-list-runtime-core.test.ts +83 -0
- package/src/tests/external-store-thread-runtime-core-adapter.test.ts +178 -18
- package/src/tests/external-thread-attachments.test.tsx +208 -0
- package/src/tests/external-thread-parity.test.tsx +57 -0
- package/src/tests/groupParts.test.ts +71 -0
- package/src/tests/message-queue.test.ts +253 -0
- package/src/tests/remote-thread-list-isLoading.test.ts +1 -0
- package/src/tests/remote-thread-list-reactive-threadId.test.ts +51 -0
- package/src/tests/thread-list-runtime-getLoadThreadsPromise.test.ts +1 -0
- package/src/tests/thread-switch-events.test.tsx +78 -0
- package/src/tests/tools-scope-migration.test.tsx +28 -0
- package/src/tests/useRemoteThreadListRuntime-controlled.test.tsx +43 -0
- package/src/types/attachment.ts +4 -0
- package/src/types/index.ts +1 -0
- package/src/types/message.ts +8 -0
- package/src/utils/abortable-iterable.test.ts +328 -0
- package/src/utils/abortable-iterable.ts +104 -0
- package/src/utils/composite-context-provider.test.ts +25 -0
- package/src/utils/composite-context-provider.ts +23 -2
- package/src/utils/getGroupStatus.test.ts +70 -4
- package/src/utils/getGroupStatus.ts +35 -12
- package/src/utils/record.test.ts +48 -0
- package/src/utils/record.ts +11 -0
- package/src/utils/wire-media.test.ts +10 -0
- package/src/utils/wire-media.ts +6 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-message-like.js","names":["parsePartialJsonObject","generateId","parseDataUrl","ReasoningMessagePart","SourceMessagePart","ThreadStep","MessageStatus","ImageMessagePart","ThreadMessage","ThreadAssistantMessagePart","ThreadAssistantMessage","ThreadUserMessagePart","ThreadUserMessage","ThreadSystemMessage","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","Unstable_AudioMessagePart","CompleteAttachment","MessageTiming","PartProviderMetadata","TextMessagePart","ToolCallTiming","ToolCallMessagePart","ToolCallMessagePartMcpMetadata","ReadonlyJSONObject","ReadonlyJSONValue","DataPrefixedPart","type","data","ThreadMessageLike","role","content","toolCallId","toolName","args","argsText","artifact","result","isError","parentId","messages","interrupt","payload","timing","mcp","providerMetadata","approval","NonNullable","id","createdAt","Date","status","attachments","Omit","metadata","unstable_state","unstable_annotations","unstable_data","steps","submittedFeedback","isOptimistic","custom","Record","convertDataPrefixedPart","startsWith","undefined","name","substring","fromThreadMessageLike","like","fallbackId","fallbackStatus","common","const","text","sanitizeImageContent","image","rest","mimeType","test","console","warn","length","Error","map","part","trim","unstable_summary","basePart","commonProps","JSON","stringify","converted","filter","c","att","unsupportedRole"],"sources":["../../../src/runtime/utils/thread-message-like.ts"],"sourcesContent":["import { parsePartialJsonObject } from \"assistant-stream/utils\";\nimport { generateId } from \"../../utils/id\";\nimport { parseDataUrl } from \"../../utils/data-url\";\nimport type {\n ReasoningMessagePart,\n SourceMessagePart,\n ThreadStep,\n MessageStatus,\n ImageMessagePart,\n ThreadMessage,\n ThreadAssistantMessagePart,\n ThreadAssistantMessage,\n ThreadUserMessagePart,\n ThreadUserMessage,\n ThreadSystemMessage,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n Unstable_AudioMessagePart,\n} from \"../../types/message\";\nimport type { CompleteAttachment } from \"../../types/attachment\";\nimport type {\n MessageTiming,\n PartProviderMetadata,\n TextMessagePart,\n ToolCallTiming,\n ToolCallMessagePart,\n ToolCallMessagePartMcpMetadata,\n} from \"../../types/message\";\nimport type {\n ReadonlyJSONObject,\n ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\n\ntype DataPrefixedPart = {\n readonly type: `data-${string}`;\n readonly data: any;\n};\n\nexport type ThreadMessageLike = {\n readonly role: \"assistant\" | \"user\" | \"system\";\n readonly content:\n | string\n | readonly (\n | TextMessagePart\n | ReasoningMessagePart\n | SourceMessagePart\n | ImageMessagePart\n | FileMessagePart\n | DataMessagePart\n | GenerativeUIMessagePart\n | Unstable_AudioMessagePart\n | DataPrefixedPart\n | {\n readonly type: \"tool-call\";\n readonly toolCallId?: string;\n readonly toolName: string;\n readonly args?: ReadonlyJSONObject;\n readonly argsText?: string;\n readonly artifact?: any;\n readonly result?: any | undefined;\n readonly isError?: boolean | undefined;\n readonly parentId?: string | undefined;\n readonly messages?: readonly ThreadMessage[] | undefined;\n readonly interrupt?: { type: \"human\"; payload: unknown };\n readonly timing?: ToolCallTiming;\n readonly mcp?: ToolCallMessagePartMcpMetadata;\n readonly providerMetadata?: PartProviderMetadata;\n readonly approval?: NonNullable<ToolCallMessagePart[\"approval\"]>;\n }\n )[];\n readonly id?: string | undefined;\n readonly createdAt?: Date | undefined;\n readonly status?: MessageStatus | undefined;\n readonly attachments?:\n | readonly (Omit<CompleteAttachment, \"content\"> & {\n readonly content: readonly (ThreadUserMessagePart | DataPrefixedPart)[];\n })[]\n | undefined;\n readonly metadata?:\n | {\n readonly unstable_state?: ReadonlyJSONValue;\n readonly unstable_annotations?:\n | readonly ReadonlyJSONValue[]\n | undefined;\n readonly unstable_data?: readonly ReadonlyJSONValue[] | undefined;\n readonly steps?: readonly ThreadStep[] | undefined;\n readonly timing?: MessageTiming | undefined;\n readonly submittedFeedback?: { readonly type: \"positive\" | \"negative\" };\n readonly isOptimistic?: boolean | undefined;\n readonly custom?: Record<string, unknown> | undefined;\n }\n | undefined;\n};\n\nconst convertDataPrefixedPart = (\n type: string,\n data: unknown,\n): DataMessagePart | undefined => {\n if (!type.startsWith(\"data-\")) return undefined;\n return { type: \"data\", name: type.substring(5), data };\n};\n\n/**\n * @deprecated This API is experimental and may change without notice.\n */\nexport const fromThreadMessageLike = (\n like: ThreadMessageLike,\n fallbackId: string,\n fallbackStatus: MessageStatus,\n): ThreadMessage => {\n const { role, id, createdAt, attachments, status, metadata } = like;\n const common = {\n id: id ?? fallbackId,\n createdAt: createdAt ?? new Date(),\n };\n\n const content =\n typeof like.content === \"string\"\n ? [{ type: \"text\" as const, text: like.content }]\n : like.content;\n\n const sanitizeImageContent = ({\n image,\n ...rest\n }: ImageMessagePart): ImageMessagePart | null => {\n if (typeof image !== \"string\") return null;\n if (parseDataUrl(image)?.mimeType.startsWith(\"image/\")) {\n return { ...rest, image };\n }\n if (/^(https:\\/\\/|blob:)/i.test(image)) {\n return { ...rest, image };\n }\n console.warn(`Invalid image data format detected`);\n return null;\n };\n\n if (role !== \"user\" && attachments?.length)\n throw new Error(\"attachments are only supported for user messages\");\n\n if (role !== \"assistant\" && status)\n throw new Error(\"status is only supported for assistant messages\");\n\n if (role !== \"assistant\" && metadata?.steps)\n throw new Error(\"metadata.steps is only supported for assistant messages\");\n\n switch (role) {\n case \"assistant\":\n return {\n ...common,\n role,\n content: content\n .map((part): ThreadAssistantMessagePart | null => {\n const type = part.type;\n switch (type) {\n case \"text\":\n if (!part.text?.trim()) return null;\n return part;\n\n case \"reasoning\":\n if (!part.text?.trim() && !part.unstable_summary?.trim())\n return null;\n return part;\n\n case \"file\":\n case \"source\":\n return part;\n\n case \"image\":\n return sanitizeImageContent(part);\n\n case \"data\":\n return part;\n\n case \"generative-ui\":\n return part;\n\n case \"tool-call\": {\n const { parentId, messages, ...basePart } = part;\n const commonProps = {\n ...basePart,\n toolCallId: part.toolCallId ?? `tool-${generateId()}`,\n ...(parentId !== undefined && { parentId }),\n ...(messages !== undefined && { messages }),\n };\n\n if (part.args) {\n return {\n ...commonProps,\n args: part.args,\n argsText: part.argsText ?? JSON.stringify(part.args),\n };\n }\n return {\n ...commonProps,\n args: parsePartialJsonObject(part.argsText ?? \"\") ?? {},\n argsText: part.argsText ?? \"\",\n };\n }\n\n default: {\n const converted = convertDataPrefixedPart(\n type,\n (part as DataPrefixedPart).data,\n );\n if (converted) return converted;\n throw new Error(\n `Unsupported assistant message part type: ${type}`,\n );\n }\n }\n })\n .filter((c) => !!c),\n status: status ?? fallbackStatus,\n metadata: {\n unstable_state: metadata?.unstable_state ?? null,\n unstable_annotations: metadata?.unstable_annotations ?? [],\n unstable_data: metadata?.unstable_data ?? [],\n custom: metadata?.custom ?? {},\n steps: metadata?.steps ?? [],\n ...(metadata?.timing && { timing: metadata.timing }),\n ...(metadata?.submittedFeedback && {\n submittedFeedback: metadata.submittedFeedback,\n }),\n ...(metadata?.isOptimistic && { isOptimistic: true }),\n },\n } satisfies ThreadAssistantMessage;\n\n case \"user\":\n return {\n ...common,\n role,\n content: content.map((part): ThreadUserMessagePart => {\n const type = part.type;\n switch (type) {\n case \"text\":\n case \"image\":\n case \"audio\":\n case \"file\":\n case \"data\":\n return part;\n\n default: {\n const converted = convertDataPrefixedPart(\n type,\n (part as DataPrefixedPart).data,\n );\n if (converted) return converted;\n throw new Error(`Unsupported user message part type: ${type}`);\n }\n }\n }),\n attachments: (attachments ?? []).map((att) => ({\n ...att,\n content: att.content.map((part): ThreadUserMessagePart => {\n const converted = convertDataPrefixedPart(\n part.type,\n (part as DataPrefixedPart).data,\n );\n return converted ?? (part as ThreadUserMessagePart);\n }),\n })),\n metadata: {\n custom: metadata?.custom ?? {},\n ...(metadata?.isOptimistic && { isOptimistic: true }),\n },\n } satisfies ThreadUserMessage;\n\n case \"system\":\n if (content.length !== 1 || content[0]!.type !== \"text\")\n throw new Error(\n \"System messages must have exactly one text message part.\",\n );\n\n return {\n ...common,\n role,\n content: content as [TextMessagePart],\n metadata: {\n custom: metadata?.custom ?? {},\n },\n } satisfies ThreadSystemMessage;\n\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n};\n"],"mappings":";;;;AA+FA,MAAMgE,2BACJpC,MACAC,SACgC;CAChC,IAAI,CAACD,KAAKqC,WAAW,OAAO,GAAG,OAAOC,KAAAA;CACtC,OAAO;EAAEtC,MAAM;EAAQuC,MAAMvC,KAAKwC,UAAU,CAAC;EAAGvC;CAAK;AACvD;;;;AAKA,MAAawC,yBACXC,MACAC,YACAC,mBACkB;CAClB,MAAM,EAAEzC,MAAMkB,IAAIC,WAAWG,aAAaD,QAAQG,aAAae;CAC/D,MAAMG,SAAS;EACbxB,IAAIA,MAAMsB;EACVrB,WAAWA,6BAAa,IAAIC,KAAK;CACnC;CAEA,MAAMnB,UACJ,OAAOsC,KAAKtC,YAAY,WACpB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CAAuCxD,MAAM;KAC/D;IACF;GACF,CAAC;GACDyB,cAAcA,eAAe,CAAA,EAAA,CAAIgC,KAAKW,SAAS;IAC7C,GAAGA;IACHhE,SAASgE,IAAIhE,QAAQqD,KAAKC,SAAgC;KAKxD,OAJkBtB,wBAChBsB,KAAK1D,MACJ0D,KAA0BzD,IAEtBgE,KAAcP;IACvB,CAAC;GACH,EAAE;GACF/B,UAAU;IACRO,QAAQP,UAAUO,UAAU,CAAC;IAC7B,GAAIP,UAAUM,gBAAgB,EAAEA,cAAc,KAAK;GACrD;EACF;EAEF,KAAK;GACH,IAAI7B,QAAQmD,WAAW,KAAKnD,QAAQ,EAAE,CAAEJ,SAAS,QAC/C,MAAM,IAAIwD,MACR,0DACF;GAEF,OAAO;IACL,GAAGX;IACH1C;IACSC;IACTuB,UAAU,EACRO,QAAQP,UAAUO,UAAU,CAAC,EAC/B;GACF;EAEF,SAEE,MAAM,IAAIsB,MAAM,yBAAyBa,MAAiB;CAE9D;AACF"}
|
|
1
|
+
{"version":3,"file":"thread-message-like.js","names":["parsePartialJsonObject","generateId","parseDataUrl","ReasoningMessagePart","SourceMessagePart","ThreadStep","MessageStatus","ImageMessagePart","ThreadMessage","ThreadAssistantMessagePart","ThreadAssistantMessage","ThreadUserMessagePart","ThreadUserMessage","ThreadSystemMessage","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","Unstable_AudioMessagePart","CompleteAttachment","MessageModality","MessageTiming","PartProviderMetadata","TextMessagePart","ToolCallTiming","ToolCallMessagePart","ToolCallMessagePartMcpMetadata","ReadonlyJSONObject","ReadonlyJSONValue","DataPrefixedPart","type","data","ThreadMessageLike","role","content","toolCallId","toolName","args","argsText","artifact","result","isError","parentId","messages","interrupt","payload","timing","mcp","providerMetadata","approval","NonNullable","id","createdAt","Date","status","attachments","Omit","metadata","unstable_state","unstable_annotations","unstable_data","steps","submittedFeedback","isOptimistic","modality","custom","Record","convertDataPrefixedPart","startsWith","undefined","name","substring","fromThreadMessageLike","like","fallbackId","fallbackStatus","common","const","text","sanitizeImageContent","image","rest","mimeType","test","console","warn","length","Error","map","part","trim","unstable_summary","basePart","commonProps","JSON","stringify","converted","filter","c","att","unsupportedRole"],"sources":["../../../src/runtime/utils/thread-message-like.ts"],"sourcesContent":["import { parsePartialJsonObject } from \"assistant-stream/utils\";\nimport { generateId } from \"../../utils/id\";\nimport { parseDataUrl } from \"../../utils/data-url\";\nimport type {\n ReasoningMessagePart,\n SourceMessagePart,\n ThreadStep,\n MessageStatus,\n ImageMessagePart,\n ThreadMessage,\n ThreadAssistantMessagePart,\n ThreadAssistantMessage,\n ThreadUserMessagePart,\n ThreadUserMessage,\n ThreadSystemMessage,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n Unstable_AudioMessagePart,\n} from \"../../types/message\";\nimport type { CompleteAttachment } from \"../../types/attachment\";\nimport type {\n MessageModality,\n MessageTiming,\n PartProviderMetadata,\n TextMessagePart,\n ToolCallTiming,\n ToolCallMessagePart,\n ToolCallMessagePartMcpMetadata,\n} from \"../../types/message\";\nimport type {\n ReadonlyJSONObject,\n ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\n\ntype DataPrefixedPart = {\n readonly type: `data-${string}`;\n readonly data: any;\n};\n\nexport type ThreadMessageLike = {\n readonly role: \"assistant\" | \"user\" | \"system\";\n readonly content:\n | string\n | readonly (\n | TextMessagePart\n | ReasoningMessagePart\n | SourceMessagePart\n | ImageMessagePart\n | FileMessagePart\n | DataMessagePart\n | GenerativeUIMessagePart\n | Unstable_AudioMessagePart\n | DataPrefixedPart\n | {\n readonly type: \"tool-call\";\n readonly toolCallId?: string;\n readonly toolName: string;\n readonly args?: ReadonlyJSONObject;\n readonly argsText?: string;\n readonly artifact?: any;\n readonly result?: any | undefined;\n readonly isError?: boolean | undefined;\n readonly parentId?: string | undefined;\n readonly messages?: readonly ThreadMessage[] | undefined;\n readonly interrupt?: { type: \"human\"; payload: unknown };\n readonly timing?: ToolCallTiming;\n readonly mcp?: ToolCallMessagePartMcpMetadata;\n readonly providerMetadata?: PartProviderMetadata;\n readonly approval?: NonNullable<ToolCallMessagePart[\"approval\"]>;\n }\n )[];\n readonly id?: string | undefined;\n readonly createdAt?: Date | undefined;\n readonly status?: MessageStatus | undefined;\n readonly attachments?:\n | readonly (Omit<CompleteAttachment, \"content\"> & {\n readonly content: readonly (ThreadUserMessagePart | DataPrefixedPart)[];\n })[]\n | undefined;\n readonly metadata?:\n | {\n readonly unstable_state?: ReadonlyJSONValue;\n readonly unstable_annotations?:\n | readonly ReadonlyJSONValue[]\n | undefined;\n readonly unstable_data?: readonly ReadonlyJSONValue[] | undefined;\n readonly steps?: readonly ThreadStep[] | undefined;\n readonly timing?: MessageTiming | undefined;\n readonly submittedFeedback?: { readonly type: \"positive\" | \"negative\" };\n readonly isOptimistic?: boolean | undefined;\n readonly modality?: MessageModality | undefined;\n readonly custom?: Record<string, unknown> | undefined;\n }\n | undefined;\n};\n\nconst convertDataPrefixedPart = (\n type: string,\n data: unknown,\n): DataMessagePart | undefined => {\n if (!type.startsWith(\"data-\")) return undefined;\n return { type: \"data\", name: type.substring(5), data };\n};\n\n/**\n * @deprecated This API is experimental and may change without notice.\n */\nexport const fromThreadMessageLike = (\n like: ThreadMessageLike,\n fallbackId: string,\n fallbackStatus: MessageStatus,\n): ThreadMessage => {\n const { role, id, createdAt, attachments, status, metadata } = like;\n const common = {\n id: id ?? fallbackId,\n createdAt: createdAt ?? new Date(),\n };\n\n const content =\n typeof like.content === \"string\"\n ? [{ type: \"text\" as const, text: like.content }]\n : like.content;\n\n const sanitizeImageContent = ({\n image,\n ...rest\n }: ImageMessagePart): ImageMessagePart | null => {\n if (typeof image !== \"string\") return null;\n if (parseDataUrl(image)?.mimeType.startsWith(\"image/\")) {\n return { ...rest, image };\n }\n if (/^(https:\\/\\/|blob:)/i.test(image)) {\n return { ...rest, image };\n }\n console.warn(`Invalid image data format detected`);\n return null;\n };\n\n if (role !== \"user\" && attachments?.length)\n throw new Error(\"attachments are only supported for user messages\");\n\n if (role !== \"assistant\" && status)\n throw new Error(\"status is only supported for assistant messages\");\n\n if (role !== \"assistant\" && metadata?.steps)\n throw new Error(\"metadata.steps is only supported for assistant messages\");\n\n switch (role) {\n case \"assistant\":\n return {\n ...common,\n role,\n content: content\n .map((part): ThreadAssistantMessagePart | null => {\n const type = part.type;\n switch (type) {\n case \"text\":\n if (!part.text?.trim()) return null;\n return part;\n\n case \"reasoning\":\n if (!part.text?.trim() && !part.unstable_summary?.trim())\n return null;\n return part;\n\n case \"file\":\n case \"source\":\n return part;\n\n case \"image\":\n return sanitizeImageContent(part);\n\n case \"data\":\n return part;\n\n case \"generative-ui\":\n return part;\n\n case \"tool-call\": {\n const { parentId, messages, ...basePart } = part;\n const commonProps = {\n ...basePart,\n toolCallId: part.toolCallId || `tool-${generateId()}`,\n ...(parentId !== undefined && { parentId }),\n ...(messages !== undefined && { messages }),\n };\n\n if (part.args) {\n return {\n ...commonProps,\n args: part.args,\n argsText: part.argsText ?? JSON.stringify(part.args),\n };\n }\n return {\n ...commonProps,\n args: parsePartialJsonObject(part.argsText ?? \"\") ?? {},\n argsText: part.argsText ?? \"\",\n };\n }\n\n default: {\n const converted = convertDataPrefixedPart(\n type,\n (part as DataPrefixedPart).data,\n );\n if (converted) return converted;\n throw new Error(\n `Unsupported assistant message part type: ${type}`,\n );\n }\n }\n })\n .filter((c) => !!c),\n status: status ?? fallbackStatus,\n metadata: {\n unstable_state: metadata?.unstable_state ?? null,\n unstable_annotations: metadata?.unstable_annotations ?? [],\n unstable_data: metadata?.unstable_data ?? [],\n custom: metadata?.custom ?? {},\n steps: metadata?.steps ?? [],\n ...(metadata?.timing && { timing: metadata.timing }),\n ...(metadata?.submittedFeedback && {\n submittedFeedback: metadata.submittedFeedback,\n }),\n ...(metadata?.isOptimistic && { isOptimistic: true }),\n ...(metadata?.modality && { modality: metadata.modality }),\n },\n } satisfies ThreadAssistantMessage;\n\n case \"user\":\n return {\n ...common,\n role,\n content: content.map((part): ThreadUserMessagePart => {\n const type = part.type;\n switch (type) {\n case \"text\":\n case \"image\":\n case \"audio\":\n case \"file\":\n case \"data\":\n return part;\n\n default: {\n const converted = convertDataPrefixedPart(\n type,\n (part as DataPrefixedPart).data,\n );\n if (converted) return converted;\n throw new Error(`Unsupported user message part type: ${type}`);\n }\n }\n }),\n attachments: (attachments ?? []).map((att) => ({\n ...att,\n content: att.content.map((part): ThreadUserMessagePart => {\n const converted = convertDataPrefixedPart(\n part.type,\n (part as DataPrefixedPart).data,\n );\n return converted ?? (part as ThreadUserMessagePart);\n }),\n })),\n metadata: {\n custom: metadata?.custom ?? {},\n ...(metadata?.isOptimistic && { isOptimistic: true }),\n ...(metadata?.modality && { modality: metadata.modality }),\n },\n } satisfies ThreadUserMessage;\n\n case \"system\":\n if (content.length !== 1 || content[0]!.type !== \"text\")\n throw new Error(\n \"System messages must have exactly one text message part.\",\n );\n\n return {\n ...common,\n role,\n content: content as [TextMessagePart],\n metadata: {\n custom: metadata?.custom ?? {},\n },\n } satisfies ThreadSystemMessage;\n\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n};\n"],"mappings":";;;;AAiGA,MAAMkE,2BACJrC,MACAC,SACgC;CAChC,IAAI,CAACD,KAAKsC,WAAW,OAAO,GAAG,OAAOC,KAAAA;CACtC,OAAO;EAAEvC,MAAM;EAAQwC,MAAMxC,KAAKyC,UAAU,CAAC;EAAGxC;CAAK;AACvD;;;;AAKA,MAAayC,yBACXC,MACAC,YACAC,mBACkB;CAClB,MAAM,EAAE1C,MAAMkB,IAAIC,WAAWG,aAAaD,QAAQG,aAAagB;CAC/D,MAAMG,SAAS;EACbzB,IAAIA,MAAMuB;EACVtB,WAAWA,6BAAa,IAAIC,KAAK;CACnC;CAEA,MAAMnB,UACJ,OAAOuC,KAAKvC,YAAY,WACpB,CAAC;EAAEJ,MAAM;EAAiBgD,MAAML,KAAKvC;CAAQ,CAAC,IAC9CuC,KAA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KAC/D;IACF;GACF,CAAC;GACDyB,cAAcA,eAAe,CAAA,EAAA,CAAIiC,KAAKW,SAAS;IAC7C,GAAGA;IACHjE,SAASiE,IAAIjE,QAAQsD,KAAKC,SAAgC;KAKxD,OAJkBtB,wBAChBsB,KAAK3D,MACJ2D,KAA0B1D,IAEtBiE,KAAcP;IACvB,CAAC;GACH,EAAE;GACFhC,UAAU;IACRQ,QAAQR,UAAUQ,UAAU,CAAC;IAC7B,GAAIR,UAAUM,gBAAgB,EAAEA,cAAc,KAAK;IACnD,GAAIN,UAAUO,YAAY,EAAEA,UAAUP,SAASO,SAAS;GAC1D;EACF;EAEF,KAAK;GACH,IAAI9B,QAAQoD,WAAW,KAAKpD,QAAQ,EAAE,CAAEJ,SAAS,QAC/C,MAAM,IAAIyD,MACR,0DACF;GAEF,OAAO;IACL,GAAGX;IACH3C;IACSC;IACTuB,UAAU,EACRQ,QAAQR,UAAUQ,UAAU,CAAC,EAC/B;GACF;EAEF,SAEE,MAAM,IAAIsB,MAAM,yBAAyBa,MAAiB;CAE9D;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-list-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"external-store-thread-list-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"mappings":";;;;;KAUY,mCAAmC;cAkBlC,2CACH,4BACG;UAEH;UACA;UACA;UACA;UAEA;MAEG;MAIA;MAIA;MAIA;MAIA,eAAW,SAAA,eAAA;EAIf,yBAAqB;UAIpB;MAEG;UAIH;EAGN,YAAA,SAAS,4CACT,eAAe;EAOV,4BAAwB;EAIxB;EAIA,YAAY,mBAAgB;EAM5B,sBACL,SAAS,gCACT;EAsFW,oBAAoB;EASpB,eACX,kBACA;IAAa;MACZ;EAUU,qBAAqB;EAUrB,OAAO,kBAAkB,mBAAmB;EAQ5C,aACX,kBACA,QAAQ,sCACP;EAUU,UAAU;EAIV,QAAQ,mBAAmB;EAQ3B,UAAU,mBAAmB;EAQ7B,OAAO,mBAAmB;EAQhC,WACL,mBACC;IAAU;IAAkB;;EAIxB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nullProtoRecord } from "../../utils/record.js";
|
|
1
2
|
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
2
3
|
import { invalidateThreadRuntime } from "../../runtime/utils/thread-runtime-lifecycle.js";
|
|
3
4
|
//#region src/runtimes/external-store/external-store-thread-list-runtime-core.ts
|
|
@@ -11,7 +12,7 @@ const DEFAULT_THREAD = Object.freeze({
|
|
|
11
12
|
status: "regular"
|
|
12
13
|
});
|
|
13
14
|
const RESOLVED_PROMISE = Promise.resolve();
|
|
14
|
-
const DEFAULT_THREAD_DATA = Object.freeze({ [DEFAULT_THREAD_ID]: DEFAULT_THREAD });
|
|
15
|
+
const DEFAULT_THREAD_DATA = Object.freeze(nullProtoRecord({ [DEFAULT_THREAD_ID]: DEFAULT_THREAD }));
|
|
15
16
|
var ExternalStoreThreadListRuntimeCore = class extends BaseSubscribable {
|
|
16
17
|
_mainThreadId = DEFAULT_THREAD_ID;
|
|
17
18
|
_threads = DEFAULT_THREADS;
|
|
@@ -51,7 +52,7 @@ var ExternalStoreThreadListRuntimeCore = class extends BaseSubscribable {
|
|
|
51
52
|
throw new Error("Method not implemented.");
|
|
52
53
|
}
|
|
53
54
|
getItemById(threadId) {
|
|
54
|
-
return this._threadData[threadId];
|
|
55
|
+
return Object.hasOwn(this._threadData, threadId) ? this._threadData[threadId] : void 0;
|
|
55
56
|
}
|
|
56
57
|
__internal_setAdapter(adapter, initialLoad = false) {
|
|
57
58
|
const previousAdapter = this.adapter;
|
|
@@ -62,22 +63,18 @@ var ExternalStoreThreadListRuntimeCore = class extends BaseSubscribable {
|
|
|
62
63
|
const previousThreadId = previousAdapter.threadId ?? DEFAULT_THREAD_ID;
|
|
63
64
|
const previousThreads = previousAdapter.threads ?? EMPTY_ARRAY;
|
|
64
65
|
const previousArchivedThreads = previousAdapter.archivedThreads ?? EMPTY_ARRAY;
|
|
65
|
-
if (!initialLoad && previousThreadId === newThreadId && previousThreads === newThreads && previousArchivedThreads === newArchivedThreads) return;
|
|
66
|
-
if (previousThreads !== newThreads || previousArchivedThreads !== newArchivedThreads || previousThreadId !== newThreadId) this._threadData = {
|
|
67
|
-
...
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
externalId: t.externalId,
|
|
78
|
-
status: "archived"
|
|
79
|
-
}]) ?? [])
|
|
80
|
-
};
|
|
66
|
+
if (!initialLoad && (previousAdapter.isLoading ?? false) === (adapter.isLoading ?? false) && previousThreadId === newThreadId && previousThreads === newThreads && previousArchivedThreads === newArchivedThreads) return;
|
|
67
|
+
if (previousThreads !== newThreads || previousArchivedThreads !== newArchivedThreads || previousThreadId !== newThreadId) this._threadData = nullProtoRecord(DEFAULT_THREAD_DATA, Object.fromEntries(adapter.threads?.map((t) => [t.id, {
|
|
68
|
+
...t,
|
|
69
|
+
remoteId: t.remoteId,
|
|
70
|
+
externalId: t.externalId,
|
|
71
|
+
status: "regular"
|
|
72
|
+
}]) ?? []), Object.fromEntries(adapter.archivedThreads?.map((t) => [t.id, {
|
|
73
|
+
...t,
|
|
74
|
+
remoteId: t.remoteId,
|
|
75
|
+
externalId: t.externalId,
|
|
76
|
+
status: "archived"
|
|
77
|
+
}]) ?? []));
|
|
81
78
|
if (previousThreads !== newThreads) this._threads = this.adapter.threads?.map((t) => t.id) ?? EMPTY_ARRAY;
|
|
82
79
|
if (previousArchivedThreads !== newArchivedThreads) this._archivedThreads = this.adapter.archivedThreads?.map((t) => t.id) ?? EMPTY_ARRAY;
|
|
83
80
|
if (initialLoad || previousThreadId !== newThreadId) {
|
|
@@ -85,15 +82,12 @@ var ExternalStoreThreadListRuntimeCore = class extends BaseSubscribable {
|
|
|
85
82
|
this._mainThreadId = newThreadId;
|
|
86
83
|
this._mainThread = this.threadFactory();
|
|
87
84
|
}
|
|
88
|
-
if (!this._threadData
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
status: "regular"
|
|
95
|
-
}
|
|
96
|
-
};
|
|
85
|
+
if (!Object.hasOwn(this._threadData, this._mainThreadId)) this._threadData = nullProtoRecord(this._threadData, { [this._mainThreadId]: {
|
|
86
|
+
id: this._mainThreadId,
|
|
87
|
+
remoteId: void 0,
|
|
88
|
+
externalId: void 0,
|
|
89
|
+
status: "regular"
|
|
90
|
+
} });
|
|
97
91
|
this._notifySubscribers();
|
|
98
92
|
}
|
|
99
93
|
async reloadMainThread() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-list-runtime-core.js","names":["ExternalStoreThreadRuntimeCore","ThreadListItemCoreState","ThreadListRuntimeCore","ExternalStoreThreadListAdapter","invalidateThreadRuntime","BaseSubscribable","ExternalStoreThreadFactory","EMPTY_ARRAY","Object","freeze","DEFAULT_THREAD_ID","DEFAULT_THREADS","DEFAULT_THREAD","id","remoteId","undefined","externalId","status","RESOLVED_PROMISE","Promise","resolve","DEFAULT_THREAD_DATA","ExternalStoreThreadListRuntimeCore","_mainThreadId","_threads","_archivedThreads","_threadData","Readonly","Record","adapter","isLoading","newThreadId","threadIds","archivedThreadIds","threadItems","getLoadThreadsPromise","_mainThread","mainThreadId","threadFactory","constructor","__internal_setAdapter","getMainThreadRuntimeCore","getThreadRuntimeCore","Error","getItemById","threadId","initialLoad","previousAdapter","newThreads","threads","newArchivedThreads","archivedThreads","previousThreadId","previousThreads","previousArchivedThreads","fromEntries","map","t","_notifySubscribers","reloadMainThread","unstable_refetchThread","switchToThread","_options","unarchive","onSwitchToThread","switchToNewThread","onSwitchToNewThread","rename","newTitle","onRename","updateCustom","custom","onUpdateCustom","detach","archive","onArchive","onUnarchive","delete","onDelete","initialize","generateTitle"],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"sourcesContent":["import type { ExternalStoreThreadRuntimeCore } from \"./external-store-thread-runtime-core\";\nimport type {\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"../../runtime/interfaces/thread-list-runtime-core\";\nimport type { ExternalStoreThreadListAdapter } from \"./external-store-adapter\";\nimport { invalidateThreadRuntime } from \"../../runtime/utils/thread-runtime-lifecycle\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\n\nexport type ExternalStoreThreadFactory = () => ExternalStoreThreadRuntimeCore;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst DEFAULT_THREAD_ID = \"DEFAULT_THREAD_ID\";\nconst DEFAULT_THREADS = Object.freeze([DEFAULT_THREAD_ID]);\nconst DEFAULT_THREAD = Object.freeze({\n id: DEFAULT_THREAD_ID,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n});\nconst RESOLVED_PROMISE = Promise.resolve();\nconst DEFAULT_THREAD_DATA = Object.freeze({\n [DEFAULT_THREAD_ID]: DEFAULT_THREAD,\n});\n\nexport class ExternalStoreThreadListRuntimeCore\n extends BaseSubscribable\n implements ThreadListRuntimeCore\n{\n private _mainThreadId: string = DEFAULT_THREAD_ID;\n private _threads: readonly string[] = DEFAULT_THREADS;\n private _archivedThreads: readonly string[] = EMPTY_ARRAY;\n private _threadData: Readonly<Record<string, ThreadListItemCoreState>> =\n DEFAULT_THREAD_DATA;\n private adapter: ExternalStoreThreadListAdapter = {};\n\n public get isLoading() {\n return this.adapter.isLoading ?? false;\n }\n\n public get newThreadId() {\n return undefined;\n }\n\n public get threadIds() {\n return this._threads;\n }\n\n public get archivedThreadIds() {\n return this._archivedThreads;\n }\n\n public get threadItems() {\n return this._threadData;\n }\n\n public getLoadThreadsPromise() {\n return RESOLVED_PROMISE;\n }\n\n private _mainThread!: ExternalStoreThreadRuntimeCore;\n\n public get mainThreadId() {\n return this._mainThreadId;\n }\n\n private threadFactory: ExternalStoreThreadFactory;\n\n constructor(\n adapter: ExternalStoreThreadListAdapter = {},\n threadFactory: ExternalStoreThreadFactory,\n ) {\n super();\n this.threadFactory = threadFactory;\n this.__internal_setAdapter(adapter, true);\n }\n\n public getMainThreadRuntimeCore() {\n return this._mainThread;\n }\n\n public getThreadRuntimeCore(): never {\n throw new Error(\"Method not implemented.\");\n }\n\n public getItemById(threadId: string) {\n return this._threadData[threadId];\n }\n\n public __internal_setAdapter(\n adapter: ExternalStoreThreadListAdapter,\n initialLoad = false,\n ) {\n const previousAdapter = this.adapter;\n this.adapter = adapter;\n\n const newThreadId = adapter.threadId ?? DEFAULT_THREAD_ID;\n const newThreads = adapter.threads ?? EMPTY_ARRAY;\n const newArchivedThreads = adapter.archivedThreads ?? EMPTY_ARRAY;\n\n const previousThreadId = previousAdapter.threadId ?? DEFAULT_THREAD_ID;\n const previousThreads = previousAdapter.threads ?? EMPTY_ARRAY;\n const previousArchivedThreads =\n previousAdapter.archivedThreads ?? EMPTY_ARRAY;\n\n if (\n !initialLoad &&\n previousThreadId === newThreadId &&\n previousThreads === newThreads &&\n previousArchivedThreads === newArchivedThreads\n ) {\n return;\n }\n\n if (\n previousThreads !== newThreads ||\n previousArchivedThreads !== newArchivedThreads ||\n previousThreadId !== newThreadId\n ) {\n this._threadData = {\n ...DEFAULT_THREAD_DATA,\n ...Object.fromEntries(\n adapter.threads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"regular\",\n },\n ]) ?? [],\n ),\n ...Object.fromEntries(\n adapter.archivedThreads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"archived\",\n },\n ]) ?? [],\n ),\n };\n }\n\n if (previousThreads !== newThreads) {\n this._threads = this.adapter.threads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n if (previousArchivedThreads !== newArchivedThreads) {\n this._archivedThreads =\n this.adapter.archivedThreads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n // `initialLoad ||`: `_mainThread!` must be assigned on construction.\n if (initialLoad || previousThreadId !== newThreadId) {\n if (!initialLoad) invalidateThreadRuntime(this._mainThread);\n this._mainThreadId = newThreadId;\n this._mainThread = this.threadFactory();\n }\n\n if (!this._threadData[this._mainThreadId]) {\n this._threadData = {\n ...this._threadData,\n [this._mainThreadId]: {\n id: this._mainThreadId,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n },\n };\n }\n\n this._notifySubscribers();\n }\n\n public async reloadMainThread(): Promise<void> {\n // There is no runtime hook to remount here, so the capability is the only\n // path and an adapter without it has nothing to refetch with.\n if (!this._mainThread.unstable_refetchThread) return;\n // No unsent-thread guard: every entry here is regular or archived, so the\n // \"new\" status the remote thread list has to exclude cannot occur.\n await this._mainThread.unstable_refetchThread();\n }\n\n public async switchToThread(\n threadId: string,\n _options?: { unarchive?: boolean },\n ): Promise<void> {\n if (this._mainThreadId === threadId) return;\n const onSwitchToThread = this.adapter.onSwitchToThread;\n if (!onSwitchToThread)\n throw new Error(\n \"External store adapter does not support switching to thread\",\n );\n await onSwitchToThread(threadId);\n }\n\n public async switchToNewThread(): Promise<void> {\n const onSwitchToNewThread = this.adapter.onSwitchToNewThread;\n if (!onSwitchToNewThread)\n throw new Error(\n \"External store adapter does not support switching to new thread\",\n );\n\n await onSwitchToNewThread();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const onRename = this.adapter.onRename;\n if (!onRename)\n throw new Error(\"External store adapter does not support renaming\");\n\n await onRename(threadId, newTitle);\n }\n\n public async updateCustom(\n threadId: string,\n custom: Record<string, unknown> | undefined,\n ): Promise<void> {\n const onUpdateCustom = this.adapter.onUpdateCustom;\n if (!onUpdateCustom)\n throw new Error(\n \"External store adapter does not support updating custom metadata\",\n );\n\n await onUpdateCustom(threadId, custom);\n }\n\n public async detach(): Promise<void> {\n // no-op\n }\n\n public async archive(threadId: string): Promise<void> {\n const onArchive = this.adapter.onArchive;\n if (!onArchive)\n throw new Error(\"External store adapter does not support archiving\");\n\n await onArchive(threadId);\n }\n\n public async unarchive(threadId: string): Promise<void> {\n const onUnarchive = this.adapter.onUnarchive;\n if (!onUnarchive)\n throw new Error(\"External store adapter does not support unarchiving\");\n\n await onUnarchive(threadId);\n }\n\n public async delete(threadId: string): Promise<void> {\n const onDelete = this.adapter.onDelete;\n if (!onDelete)\n throw new Error(\"External store adapter does not support deleting\");\n\n await onDelete(threadId);\n }\n\n public initialize(\n threadId: string,\n ): Promise<{ remoteId: string; externalId: string | undefined }> {\n return Promise.resolve({ remoteId: threadId, externalId: undefined });\n }\n\n public generateTitle(): never {\n throw new Error(\"Method not implemented.\");\n }\n}\n"],"mappings":";;;AAWA,MAAMO,cAAcC,OAAOC,OAAO,CAAA,CAAE;AACpC,MAAMC,oBAAoB;AAC1B,MAAMC,kBAAkBH,OAAOC,OAAO,CAACC,iBAAiB,CAAC;AACzD,MAAME,iBAAiBJ,OAAOC,OAAO;CACnCI,IAAIH;CACJI,UAAUC,KAAAA;CACVC,YAAYD,KAAAA;CACZE,QAAQ;AACV,CAAC;AACD,MAAMC,mBAAmBC,QAAQC,QAAQ;AACzC,MAAMC,sBAAsBb,OAAOC,OAAO,GACvCC,oBAAoBE,eACvB,CAAC;AAED,IAAaU,qCAAb,cACUjB,iBAEV;CACE,gBAAgCK;CAChC,WAAsCC;CACtC,mBAA8CJ;CAC9C,cACEc;CACF,UAAkD,CAAC;CAEnD,IAAWS,YAAY;EACrB,OAAO,KAAKD,QAAQC,aAAa;CACnC;CAEA,IAAWC,cAAc,CAEzB;CAEA,IAAWC,YAAY;EACrB,OAAO,KAAKR;CACd;CAEA,IAAWS,oBAAoB;EAC7B,OAAO,KAAKR;CACd;CAEA,IAAWS,cAAc;EACvB,OAAO,KAAKR;CACd;CAEA,wBAA+B;EAC7B,OAAOR;CACT;CAEA;CAEA,IAAWmB,eAAe;EACxB,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,IAAI7B,MACR,kEACF;EAEF,MAAM6B,eAAe3B,UAAU0B,MAAM;CACvC;CAEA,MAAaE,SAAwB,CACnC;CAGF,MAAaC,QAAQ7B,UAAiC;EACpD,MAAM8B,YAAY,KAAK9C,QAAQ8C;EAC/B,IAAI,CAACA,WACH,MAAM,IAAIhC,MAAM,mDAAmD;EAErE,MAAMgC,UAAU9B,QAAQ;CAC1B;CAEA,MAAakB,UAAUlB,UAAiC;EACtD,MAAM+B,cAAc,KAAK/C,QAAQ+C;EACjC,IAAI,CAACA,aACH,MAAM,IAAIjC,MAAM,qDAAqD;EAEvE,MAAMiC,YAAY/B,QAAQ;CAC5B;CAEA,MAAagC,OAAOhC,UAAiC;EACnD,MAAMiC,WAAW,KAAKjD,QAAQiD;EAC9B,IAAI,CAACA,UACH,MAAM,IAAInC,MAAM,kDAAkD;EAEpE,MAAMmC,SAASjC,QAAQ;CACzB;CAEA,WACEA,UAC+D;EAC/D,OAAO1B,QAAQC,QAAQ;GAAEN,UAAU+B;GAAU7B,YAAYD,KAAAA;EAAU,CAAC;CACtE;CAEA,gBAA8B;EAC5B,MAAM,IAAI4B,MAAM,yBAAyB;CAC3C;AACF"}
|
|
1
|
+
{"version":3,"file":"external-store-thread-list-runtime-core.js","names":["ExternalStoreThreadRuntimeCore","ThreadListItemCoreState","ThreadListRuntimeCore","ExternalStoreThreadListAdapter","invalidateThreadRuntime","BaseSubscribable","nullProtoRecord","ExternalStoreThreadFactory","EMPTY_ARRAY","Object","freeze","DEFAULT_THREAD_ID","DEFAULT_THREADS","DEFAULT_THREAD","id","remoteId","undefined","externalId","status","RESOLVED_PROMISE","Promise","resolve","DEFAULT_THREAD_DATA","ExternalStoreThreadListRuntimeCore","_mainThreadId","_threads","_archivedThreads","_threadData","Readonly","Record","adapter","isLoading","newThreadId","threadIds","archivedThreadIds","threadItems","getLoadThreadsPromise","_mainThread","mainThreadId","threadFactory","constructor","__internal_setAdapter","getMainThreadRuntimeCore","getThreadRuntimeCore","Error","getItemById","threadId","hasOwn","initialLoad","previousAdapter","newThreads","threads","newArchivedThreads","archivedThreads","previousThreadId","previousThreads","previousArchivedThreads","fromEntries","map","t","_notifySubscribers","reloadMainThread","unstable_refetchThread","switchToThread","_options","unarchive","onSwitchToThread","switchToNewThread","onSwitchToNewThread","rename","newTitle","onRename","updateCustom","custom","onUpdateCustom","detach","archive","onArchive","onUnarchive","delete","onDelete","initialize","generateTitle"],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"sourcesContent":["import type { ExternalStoreThreadRuntimeCore } from \"./external-store-thread-runtime-core\";\nimport type {\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"../../runtime/interfaces/thread-list-runtime-core\";\nimport type { ExternalStoreThreadListAdapter } from \"./external-store-adapter\";\nimport { invalidateThreadRuntime } from \"../../runtime/utils/thread-runtime-lifecycle\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\nimport { nullProtoRecord } from \"../../utils/record\";\n\nexport type ExternalStoreThreadFactory = () => ExternalStoreThreadRuntimeCore;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst DEFAULT_THREAD_ID = \"DEFAULT_THREAD_ID\";\nconst DEFAULT_THREADS = Object.freeze([DEFAULT_THREAD_ID]);\nconst DEFAULT_THREAD = Object.freeze({\n id: DEFAULT_THREAD_ID,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n});\nconst RESOLVED_PROMISE = Promise.resolve();\nconst DEFAULT_THREAD_DATA = Object.freeze(\n nullProtoRecord<ThreadListItemCoreState>({\n [DEFAULT_THREAD_ID]: DEFAULT_THREAD,\n }),\n);\n\nexport class ExternalStoreThreadListRuntimeCore\n extends BaseSubscribable\n implements ThreadListRuntimeCore\n{\n private _mainThreadId: string = DEFAULT_THREAD_ID;\n private _threads: readonly string[] = DEFAULT_THREADS;\n private _archivedThreads: readonly string[] = EMPTY_ARRAY;\n private _threadData: Readonly<Record<string, ThreadListItemCoreState>> =\n DEFAULT_THREAD_DATA;\n private adapter: ExternalStoreThreadListAdapter = {};\n\n public get isLoading() {\n return this.adapter.isLoading ?? false;\n }\n\n public get newThreadId() {\n return undefined;\n }\n\n public get threadIds() {\n return this._threads;\n }\n\n public get archivedThreadIds() {\n return this._archivedThreads;\n }\n\n public get threadItems() {\n return this._threadData;\n }\n\n public getLoadThreadsPromise() {\n return RESOLVED_PROMISE;\n }\n\n private _mainThread!: ExternalStoreThreadRuntimeCore;\n\n public get mainThreadId() {\n return this._mainThreadId;\n }\n\n private threadFactory: ExternalStoreThreadFactory;\n\n constructor(\n adapter: ExternalStoreThreadListAdapter = {},\n threadFactory: ExternalStoreThreadFactory,\n ) {\n super();\n this.threadFactory = threadFactory;\n this.__internal_setAdapter(adapter, true);\n }\n\n public getMainThreadRuntimeCore() {\n return this._mainThread;\n }\n\n public getThreadRuntimeCore(): never {\n throw new Error(\"Method not implemented.\");\n }\n\n public getItemById(threadId: string) {\n return Object.hasOwn(this._threadData, threadId)\n ? this._threadData[threadId]\n : undefined;\n }\n\n public __internal_setAdapter(\n adapter: ExternalStoreThreadListAdapter,\n initialLoad = false,\n ) {\n const previousAdapter = this.adapter;\n this.adapter = adapter;\n\n const newThreadId = adapter.threadId ?? DEFAULT_THREAD_ID;\n const newThreads = adapter.threads ?? EMPTY_ARRAY;\n const newArchivedThreads = adapter.archivedThreads ?? EMPTY_ARRAY;\n\n const previousThreadId = previousAdapter.threadId ?? DEFAULT_THREAD_ID;\n const previousThreads = previousAdapter.threads ?? EMPTY_ARRAY;\n const previousArchivedThreads =\n previousAdapter.archivedThreads ?? EMPTY_ARRAY;\n\n if (\n !initialLoad &&\n (previousAdapter.isLoading ?? false) === (adapter.isLoading ?? false) &&\n previousThreadId === newThreadId &&\n previousThreads === newThreads &&\n previousArchivedThreads === newArchivedThreads\n ) {\n return;\n }\n\n if (\n previousThreads !== newThreads ||\n previousArchivedThreads !== newArchivedThreads ||\n previousThreadId !== newThreadId\n ) {\n this._threadData = nullProtoRecord(\n DEFAULT_THREAD_DATA,\n Object.fromEntries(\n adapter.threads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"regular\",\n },\n ]) ?? [],\n ),\n Object.fromEntries(\n adapter.archivedThreads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"archived\",\n },\n ]) ?? [],\n ),\n );\n }\n\n if (previousThreads !== newThreads) {\n this._threads = this.adapter.threads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n if (previousArchivedThreads !== newArchivedThreads) {\n this._archivedThreads =\n this.adapter.archivedThreads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n // `initialLoad ||`: `_mainThread!` must be assigned on construction.\n if (initialLoad || previousThreadId !== newThreadId) {\n if (!initialLoad) invalidateThreadRuntime(this._mainThread);\n this._mainThreadId = newThreadId;\n this._mainThread = this.threadFactory();\n }\n\n if (!Object.hasOwn(this._threadData, this._mainThreadId)) {\n this._threadData = nullProtoRecord(this._threadData, {\n [this._mainThreadId]: {\n id: this._mainThreadId,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n },\n });\n }\n\n this._notifySubscribers();\n }\n\n public async reloadMainThread(): Promise<void> {\n // There is no runtime hook to remount here, so the capability is the only\n // path and an adapter without it has nothing to refetch with.\n if (!this._mainThread.unstable_refetchThread) return;\n // No unsent-thread guard: every entry here is regular or archived, so the\n // \"new\" status the remote thread list has to exclude cannot occur.\n await this._mainThread.unstable_refetchThread();\n }\n\n public async switchToThread(\n threadId: string,\n _options?: { unarchive?: boolean },\n ): Promise<void> {\n if (this._mainThreadId === threadId) return;\n const onSwitchToThread = this.adapter.onSwitchToThread;\n if (!onSwitchToThread)\n throw new Error(\n \"External store adapter does not support switching to thread\",\n );\n await onSwitchToThread(threadId);\n }\n\n public async switchToNewThread(): Promise<void> {\n const onSwitchToNewThread = this.adapter.onSwitchToNewThread;\n if (!onSwitchToNewThread)\n throw new Error(\n \"External store adapter does not support switching to new thread\",\n );\n\n await onSwitchToNewThread();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const onRename = this.adapter.onRename;\n if (!onRename)\n throw new Error(\"External store adapter does not support renaming\");\n\n await onRename(threadId, newTitle);\n }\n\n public async updateCustom(\n threadId: string,\n custom: Record<string, unknown> | undefined,\n ): Promise<void> {\n const onUpdateCustom = this.adapter.onUpdateCustom;\n if (!onUpdateCustom)\n throw new Error(\n \"External store adapter does not support updating custom metadata\",\n );\n\n await onUpdateCustom(threadId, custom);\n }\n\n public async detach(): Promise<void> {\n // no-op\n }\n\n public async archive(threadId: string): Promise<void> {\n const onArchive = this.adapter.onArchive;\n if (!onArchive)\n throw new Error(\"External store adapter does not support archiving\");\n\n await onArchive(threadId);\n }\n\n public async unarchive(threadId: string): Promise<void> {\n const onUnarchive = this.adapter.onUnarchive;\n if (!onUnarchive)\n throw new Error(\"External store adapter does not support unarchiving\");\n\n await onUnarchive(threadId);\n }\n\n public async delete(threadId: string): Promise<void> {\n const onDelete = this.adapter.onDelete;\n if (!onDelete)\n throw new Error(\"External store adapter does not support deleting\");\n\n await onDelete(threadId);\n }\n\n public initialize(\n threadId: string,\n ): Promise<{ remoteId: string; externalId: string | undefined }> {\n return Promise.resolve({ remoteId: threadId, externalId: undefined });\n }\n\n public generateTitle(): never {\n throw new Error(\"Method not implemented.\");\n }\n}\n"],"mappings":";;;;AAYA,MAAMQ,cAAcC,OAAOC,OAAO,CAAA,CAAE;AACpC,MAAMC,oBAAoB;AAC1B,MAAMC,kBAAkBH,OAAOC,OAAO,CAACC,iBAAiB,CAAC;AACzD,MAAME,iBAAiBJ,OAAOC,OAAO;CACnCI,IAAIH;CACJI,UAAUC,KAAAA;CACVC,YAAYD,KAAAA;CACZE,QAAQ;AACV,CAAC;AACD,MAAMC,mBAAmBC,QAAQC,QAAQ;AACzC,MAAMC,sBAAsBb,OAAOC,OACjCJ,gBAAyC,GACtCK,oBAAoBE,eACvB,CAAC,CACH;AAE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,yBAAyB;CAC3C;AACF"}
|
|
@@ -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":";;;;;;;;;;;;;;;;cAyEa,qBACX,oBACA,mBAAmB;cAKR,uCACH,iCACG;UAEH;MAiBG,gBAAY;UAIf;EACD;EACA;MACI;MAIA;YAKQ,6BAA6B;MAI5B,sEAAK,sDAAA;MAId;kBARqC;;;;;;;MAarC,iCAAiC;EAKrC,sBAAsB;EACtB;UAEC;UAUA;UAKA;UAEA;UAEA;EAED,mCACL,kBAAkB;UAKZ;;;;;UAMA;UACA;UACA;UACA;UACA;;;;;;;;UASA;UAaA;UAQA;UASA;EAIQ,UAAU;EAQxB,YAAA,iBAAiB,sBACjB,OAAO;EAMF,sBAAsB,OAAO;UAM5B;;;;;;;UA4PA;;;;;UAoFA;UACA;;;;;;;UAQA;EAWQ,eAAe;;;;;;;;;UA8BvB;EAaK,OAAO,YAAY,gBAAgB;
|
|
1
|
+
{"version":3,"file":"external-store-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;;cAyEa,qBACX,oBACA,mBAAmB;cAKR,uCACH,iCACG;UAEH;MAiBG,gBAAY;UAIf;EACD;EACA;MACI;MAIA;YAKQ,6BAA6B;MAI5B,sEAAK,sDAAA;MAId;kBARqC;;;;;;;MAarC,iCAAiC;EAKrC,sBAAsB;EACtB;UAEC;UAUA;UAKA;UAEA;UAEA;EAED,mCACL,kBAAkB;UAKZ;;;;;UAMA;UACA;UACA;UACA;UACA;;;;;;;;UASA;UAaA;UAQA;UASA;EAIQ,UAAU;EAQxB,YAAA,iBAAiB,sBACjB,OAAO;EAMF,sBAAsB,OAAO;UAM5B;;;;;;;UA4PA;;;;;UAoFA;UACA;;;;;;;UAQA;EAWQ,eAAe;;;;;;;;;UA8BvB;EAaK,OAAO,YAAY,gBAAgB;EAuEnC,cAAc,oBAAoB;UA0CvC;EAkBD,0BA5DwC;EAkExC,+BANa;EAUb,cAAc,qBAAqB,WAAW;EAI9C,gBAAgB;EAIV,SAAS,QAAQ,iBAAiB;EAgBlC,UAAU,QAAQ,kBAAkB;EAS1C;EAOA,oBAAoB;;;;;;EAqBpB;EAKA;UAmFC;EAOD,cAAc,SAAS;EASvB,eAAe,SAAS;EAoBxB,sBACL,SAAS,+BACR;EAkCa,MAAM,2BAA2B;EAMjC,OAAO,MAAM;UAQrB"}
|
|
@@ -382,6 +382,7 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
382
382
|
});
|
|
383
383
|
}
|
|
384
384
|
async append(rawMessage) {
|
|
385
|
+
if (this._isVoiceMessage(rawMessage.sourceId)) throw new Error("Voice transcript messages cannot be edited");
|
|
385
386
|
const isEdit = rawMessage.sourceId != null || rawMessage.parentId !== (this.messages.at(-1)?.id ?? null);
|
|
386
387
|
const message = !isEdit && this._store.queue && this._store.queue === this._transformedQueue ? rawMessage : this.enrichAppendMetadata(rawMessage);
|
|
387
388
|
const generation = captureThreadRuntimeGeneration(this);
|
|
@@ -447,12 +448,14 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
447
448
|
}
|
|
448
449
|
async startRun(config) {
|
|
449
450
|
if (!this._store.onReload) throw new Error("Runtime does not support reloading messages.");
|
|
451
|
+
if (this._isVoiceMessage(config.sourceId)) throw new Error("Voice transcript messages cannot be reloaded");
|
|
450
452
|
this._pendingDeleteEvictions.clear();
|
|
451
453
|
await this._toolInvocations?.abort({ discardPending: true });
|
|
452
454
|
await this._store.onReload(config.parentId, config);
|
|
453
455
|
}
|
|
454
456
|
async resumeRun(config) {
|
|
455
457
|
if (!this._store.onResume) throw new Error("Runtime does not support resuming runs.");
|
|
458
|
+
if (this._isVoiceMessage(config.sourceId)) throw new Error("Voice transcript messages cannot be reloaded");
|
|
456
459
|
await this._store.onResume(config);
|
|
457
460
|
}
|
|
458
461
|
exportExternalState() {
|
|
@@ -528,8 +531,12 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
528
531
|
}
|
|
529
532
|
respondToToolApproval(options) {
|
|
530
533
|
if (!this._store.onRespondToToolApproval) throw new Error("Runtime does not support tool approvals.");
|
|
534
|
+
const message = this.messages.findLast((candidate) => candidate.role === "assistant" && candidate.content.some((part) => part.type === "tool-call" && part.approval?.id === options.approvalId));
|
|
535
|
+
const toolCall = message?.content.find((part) => part.type === "tool-call" && part.approval?.id === options.approvalId);
|
|
531
536
|
try {
|
|
532
|
-
return Promise.resolve(this._store.onRespondToToolApproval(options))
|
|
537
|
+
return Promise.resolve(this._store.onRespondToToolApproval(options)).then(() => {
|
|
538
|
+
if (message && toolCall?.type === "tool-call") this._notifyToolApprovalAnswered(message.id, toolCall.toolCallId, toolCall.toolName, options.approved);
|
|
539
|
+
});
|
|
533
540
|
} catch (error) {
|
|
534
541
|
return Promise.reject(error);
|
|
535
542
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-runtime-core.js","names":["shallowEqual","AppendMessage","ThreadMessage","Attachment","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","ExternalStoreBranchChange","getExternalStoreMessages","bindExternalStoreMessage","FALLBACK_ID_PREFIX","ThreadMessageConverter","getContentAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","shallowArrayEqual","RuntimeCapabilities","ThreadRuntimeCore","ExternalThreadQueueAdapter","QueuePlacement","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","walkToolCallTree","ToolInvocationTracker","ToolExecutionStatus","EMPTY_QUEUE_ITEMS","QuoteInfo","captureThreadRuntimeGeneration","isThreadRuntimeGenerationCurrent","EMPTY_ARRAY","Object","freeze","observeAdapterCallback","name","result","Promise","resolve","catch","error","console","hasUpcomingMessage","isRunning","messages","length","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_hasExecutingTools","_getBaseMessages","state","adapters","unstable_refetchThread","onRefetchThread","undefined","suggestions","extras","_converter","_pendingDeleteEvictions","Set","_optimistic","id","parentId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","_transformedQueue","_toolInvocations","_toolStatuses","ReadonlyMap","Map","_effectiveIsRunning","_inTrackerUpdate","_pendingRunningRefresh","_runTrackerUpdate","fn","_refreshEffectiveIsRunning","_getEffectiveIsRunning","_notifyEventSubscribers","_notifySubscribers","store","unstable_enableToolInvocations","status","values","type","beginEdit","messageId","onEdit","Error","constructor","contextProvider","__internal_setAdapter","_updateStoreSnapshot","previousIsRunning","oldStore","repositoryInstance","unstable_messageRepositoryInstance","repositoryChanged","repository","clear","__internal_setDispatchTransform","message","at","enrichAppendMetadata","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","incoming","headId","resetHead","getMessages","incomingIds","map","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","fallbackId","content","startsWith","updated","messageLike","newMessage","seenIds","deduped","i","warn","add","push","reverse","parent","size","getMessage","ensureInitialized","optimisticId","metadata","isOptimistic","messagesSnapshot","reset","_driveToolInvocations","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","isError","artifact","modelContent","err","onStatusesChange","statuses","hadExecutingTools","fromEntries","toolCall","unstable_isClientToolCall","setState","_toolCallToMessageId","_messagesForToolCallIndex","part","set","get","branchId","onBranchChange","unstable_onBranchChange","previousHeadId","canonicalHeadId","updateMessages","_notifyBranchChange","event","visibleMessageIds","append","rawMessage","isEdit","sourceId","generation","initPromise","steer","enqueue","startRun","abort","discardPending","onNew","wasVisible","some","messageIndex","findIndex","filter","_evictDeletedMessage","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","retractDraft","head","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","reject","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import { shallowEqual } from \"@assistant-ui/store/client\";\nimport 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 FALLBACK_ID_PREFIX,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport {\n getContentAutoStatus,\n isAutoStatus,\n} from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport { shallowArrayEqual } from \"../../runtime/utils/external-message-conversion\";\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 { walkToolCallTree } from \"../../runtime/utils/tool-call-tree\";\nimport {\n ToolInvocationTracker,\n type ToolExecutionStatus,\n} from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../runtime/queue/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\" | \"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\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 if (this._hasExecutingTools(this._store)) return true;\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 // Ids the host was asked to delete via onDelete. The snapshot pass evicts\n // them from the repository once the host's array no longer carries them;\n // an id the host kept is dropped from the set without eviction.\n // Branch-changing mutations (edit, branch switch, reload) invalidate the\n // set, because after them the incoming array omits off-branch ids for\n // reasons unrelated to deletion. Plain tail sends do not clear: a tail\n // append cannot make a visible id absent, so id-absence stays unambiguous\n // and a delete whose confirmation races a send keeps its eviction.\n private _pendingDeleteEvictions = new Set<string>();\n\n // Placeholder id for the upcoming assistant message, reused across snapshot\n // passes while the same tail message awaits its response so the placeholder\n // keeps one identity per response.\n private _optimistic: { id: string; parentId: string | null } | null = null;\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 private _toolStatuses: ReadonlyMap<string, ToolExecutionStatus> = new Map();\n private _effectiveIsRunning = false;\n private _inTrackerUpdate = false;\n private _pendingRunningRefresh = false;\n\n /**\n * Tracker mutations initiated by this class (setState, reset) can publish\n * status changes synchronously. Re-entering the snapshot pipeline from\n * inside them would feed the tracker a stale snapshot and consume the\n * restore arming a reset just installed, so the running refresh is\n * deferred until the mutation returns and stays off the tracker.\n */\n private _runTrackerUpdate(fn: () => void): void {\n this._inTrackerUpdate = true;\n try {\n fn();\n } finally {\n this._inTrackerUpdate = false;\n }\n if (this._pendingRunningRefresh) {\n this._pendingRunningRefresh = false;\n this._refreshEffectiveIsRunning();\n }\n }\n\n private _refreshEffectiveIsRunning(): void {\n const isRunning = this._getEffectiveIsRunning(this._store);\n if (this._effectiveIsRunning === isRunning) return;\n this._effectiveIsRunning = isRunning;\n this._notifyEventSubscribers(isRunning ? \"runStart\" : \"runEnd\", {});\n this._notifySubscribers();\n }\n\n private _hasExecutingTools(store: ExternalStoreAdapter<any>): boolean {\n if (store.unstable_enableToolInvocations !== true) return false;\n if (this._toolInvocations === null) return false;\n for (const status of this._toolStatuses.values()) {\n if (status.type === \"executing\") return true;\n }\n return false;\n }\n\n private _getEffectiveIsRunning(store: ExternalStoreAdapter<any>): boolean {\n return (store.isRunning ?? false) || this._hasExecutingTools(store);\n }\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 this._updateStoreSnapshot(store);\n }\n\n private _updateStoreSnapshot(store: ExternalStoreAdapter<any>) {\n const previousIsRunning = this._effectiveIsRunning;\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 const isRunning = this._getEffectiveIsRunning(store);\n const repositoryInstance = store.unstable_messageRepositoryInstance;\n const repositoryChanged =\n repositoryInstance !== undefined &&\n repositoryInstance !== this.repository;\n if (repositoryChanged) {\n this.repository = repositoryInstance;\n this._pendingDeleteEvictions.clear();\n }\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 !repositoryChanged &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository &&\n previousIsRunning === isRunning\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 (\n oldStore &&\n !repositoryChanged &&\n oldStore.messageRepository === store.messageRepository\n ) {\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._pendingDeleteEvictions.clear();\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 !repositoryChanged &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages &&\n previousIsRunning === isRunning\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 fallbackId = `${FALLBACK_ID_PREFIX}${idx}`;\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status ===\n getContentAutoStatus(cache.content, isLast, isRunning))\n ) {\n if (\n cache.id.startsWith(FALLBACK_ID_PREFIX) &&\n cache.id !== fallbackId\n ) {\n const updated = { ...cache, id: fallbackId };\n bindExternalStoreMessage(updated, m);\n return updated;\n }\n return cache;\n }\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n fallbackId,\n getContentAutoStatus(messageLike.content, isLast, isRunning),\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\n if (this._pendingDeleteEvictions.size > 0) {\n const incomingIds = new Set(messages.map((m) => m.id));\n for (const id of this._pendingDeleteEvictions) {\n this._pendingDeleteEvictions.delete(id);\n if (incomingIds.has(id)) continue;\n try {\n this.repository.getMessage(id);\n } catch {\n continue;\n }\n this.repository.deleteMessage(id);\n }\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 this._effectiveIsRunning = isRunning;\n if (previousIsRunning !== isRunning) {\n if (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 const parentId = messages.at(-1)?.id ?? null;\n if (this._optimistic?.parentId !== parentId) {\n this._optimistic = { id: generateId(), parentId };\n }\n optimisticId = this._optimistic.id;\n this.repository.addOrUpdateMessage(\n parentId,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n if (optimisticId === null) this._optimistic = null;\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n const messagesSnapshot = this.repository.getMessages();\n if (\n !this._messages ||\n !shallowArrayEqual(this._messages, messagesSnapshot)\n ) {\n this._messages = messagesSnapshot;\n }\n\n if (repositoryChanged) {\n this._runTrackerUpdate(() => this._toolInvocations?.reset());\n }\n this._runTrackerUpdate(() => 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._toolStatuses = new Map();\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 const hadExecutingTools = this._hasExecutingTools(this._store);\n this._toolStatuses = statuses;\n try {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n } finally {\n if (hadExecutingTools !== this._hasExecutingTools(this._store)) {\n if (this._inTrackerUpdate) {\n this._pendingRunningRefresh = true;\n } else {\n this._updateStoreSnapshot(this._store);\n }\n }\n }\n },\n },\n (toolCall) => this._store.unstable_isClientToolCall?.(toolCall),\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._getEffectiveIsRunning(this._store),\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 for (const { part, messageId } of walkToolCallTree(this._messages)) {\n this._toolCallToMessageId.set(part.toolCallId, messageId);\n }\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._getEffectiveIsRunning(this._store)) {\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._pendingDeleteEvictions.clear();\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._getEffectiveIsRunning(this._store))\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({ discardPending: true });\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 this._pendingDeleteEvictions.clear();\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 // The host owns deletion here, and it may decline (fail a server call,\n // cancel a confirm dialog, ignore an off-branch id). The eviction is\n // therefore deferred to the snapshot pass, which evicts only once the\n // host's own array no longer carries the id. Registered before the\n // callback because an optimistic host publishes that snapshot while\n // the callback is still awaited.\n const wasVisible = this.repository\n .getMessages()\n .some((m) => m.id === messageId);\n if (wasVisible) this._pendingDeleteEvictions.add(messageId);\n try {\n await this._store.onDelete(messageId);\n } catch (error) {\n this._pendingDeleteEvictions.delete(messageId);\n throw error;\n }\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._getEffectiveIsRunning(this._store)) {\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._pendingDeleteEvictions.clear();\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n this._evictDeletedMessage(messageId);\n }\n\n // The snapshot pass only relinks incoming messages; it never evicts, so\n // without this the deleted message survives as a sibling branch that the\n // branch picker can resurrect into the host store. `_messages` is refreshed\n // before notifying so `messages` and the branch graph agree at notify time,\n // mirroring the end of the snapshot pass.\n private _evictDeletedMessage(messageId: string) {\n // Positional fallback ids are remapped in the snapshot pass; evicting\n // them first leaves the pre-renumber node as a sibling of the new head.\n if (messageId.startsWith(FALLBACK_ID_PREFIX)) return;\n // A synchronous host update (e.g. a setMessages that re-entered the\n // snapshot pass) may have evicted the message already; only that case is\n // skipped, so genuine repository errors still propagate.\n try {\n this.repository.getMessage(messageId);\n } catch {\n return;\n }\n\n this.repository.deleteMessage(messageId);\n this._messages = this.repository.getMessages();\n this._notifySubscribers();\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 this._pendingDeleteEvictions.clear();\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({ discardPending: true });\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._runTrackerUpdate(() => 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._runTrackerUpdate(() => 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 const generation = captureThreadRuntimeGeneration(this);\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({ discardPending: true });\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 if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n\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(\n options: RespondToToolApprovalOptions,\n ): Promise<void> {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n try {\n return Promise.resolve(this._store.onRespondToToolApproval(options));\n } catch (error) {\n return Promise.reject(error);\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 }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2DA,MAAMsC,cAA2CC,OAAOC,OAAO,CAAA,CAAE;AAEjE,MAAMC,0BACJC,MACAC,WACG;CACH,QAAaE,QAAQF,MAAM,CAAC,CAACG,OAAOC,UAAU;EAC5CC,QAAQD,MACN,oCAAoCL,KAAI,qBACxCK,KACF;CACF,CAAC;AACH;AAEA,MAAaE,sBACXC,WACAC,aACG;CACH,OAAOD,aAAaC,SAASA,SAASC,SAAS,EAAE,EAAEC,SAAS;AAC9D;AAEA,IAAaC,iCAAb,cACU5B,sBAEV;CACE,gBAA6C;EAC3C8B,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,IAAWC,eAAe;EACxB,OAAO,KAAKf;CACd;CAEA;CACA;CACA;CACA,IAAWmB,YAAY;EACrB,OAAO,KAAKC,OAAOD,aAAa;CAClC;CAEA,IAAWxB,YAAiC;EAC1C,IAAI,KAAK0B,mBAAmB,KAAKD,MAAM,GAAG,OAAO;EACjD,OAAO,KAAKA,OAAOzB;CACrB;CAEA,mBAAgE;EAC9D,OAAO,KAAKqB;CACd;CAEA,IAAoBO,QAAQ;EAC1B,OAAO,KAAKH,OAAOG,SAAS,MAAMA;CACpC;CAEA,IAAWC,WAAW;EACpB,OAAO,KAAKJ,OAAOI;CACrB;CAGA,IAAWC,yBAA4D;EACrE,IAAI,CAAC,KAAKL,OAAOM,iBAAiB,OAAOC,KAAAA;EACzC,aAAa,KAAKP,OAAOM,gBAAiB;CAC5C;CAEA,cAAkD,CAAA;CAClD,SAAyBC,KAAAA;CAEzB,aAAqB,IAAInE,uBAAuB;CAUhD,0CAAkC,I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OAAOxE,QAAQC,QAAQ,KAAK8B,OAAOwM,wBAAwBP,OAAO,CAAC;EACrE,SAAS7N,OAAO;GACd,OAAOH,QAAQwO,OAAOrO,KAAK;EAC7B;CACF;CAEA,MAAsBsO,iBAAgD;EACpE,MAAMC,OAAO,IAAIzP,kBAAkB;EACnCyP,KAAKC,OAAO3P,0BAA0B4P,UAAUH,mBAAmB,CAAA,CAAE,CAAC;EACtE,KAAKnE,eAAeoE,KAAKtI,YAAY,CAAC;CACxC;CAEA,OAAuByI,MAAiC;EACtD,MAAMF,OAAOE,IAAI;EAEjB,IAAI,KAAK9M,OAAO+M,UACd,KAAK/M,OAAO+M,SAAS,KAAK5J,WAAWkB,YAAY,CAAC;CAEtD;CAEA,kBAA0B7F,aAAuC;EAE/D,IADqB,KAAKwB,OAAO4E,mBAAmBrE,KAAAA,GAElD,KAAKP,OAAO2D,cAAcnF,SAASyO,QAAQhR,wBAAwB,CAAC;OAGpE,KAAK+D,OAAO2D,cAAcnF,QAA2B;CAEzD;AACF"}
|
|
1
|
+
{"version":3,"file":"external-store-thread-runtime-core.js","names":["shallowEqual","AppendMessage","ThreadMessage","Attachment","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","ExternalStoreBranchChange","getExternalStoreMessages","bindExternalStoreMessage","FALLBACK_ID_PREFIX","ThreadMessageConverter","getContentAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","shallowArrayEqual","RuntimeCapabilities","ThreadRuntimeCore","ExternalThreadQueueAdapter","QueuePlacement","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","walkToolCallTree","ToolInvocationTracker","ToolExecutionStatus","EMPTY_QUEUE_ITEMS","QuoteInfo","captureThreadRuntimeGeneration","isThreadRuntimeGenerationCurrent","EMPTY_ARRAY","Object","freeze","observeAdapterCallback","name","result","Promise","resolve","catch","error","console","hasUpcomingMessage","isRunning","messages","length","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_hasExecutingTools","_getBaseMessages","state","adapters","unstable_refetchThread","onRefetchThread","undefined","suggestions","extras","_converter","_pendingDeleteEvictions","Set","_optimistic","id","parentId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","_transformedQueue","_toolInvocations","_toolStatuses","ReadonlyMap","Map","_effectiveIsRunning","_inTrackerUpdate","_pendingRunningRefresh","_runTrackerUpdate","fn","_refreshEffectiveIsRunning","_getEffectiveIsRunning","_notifyEventSubscribers","_notifySubscribers","store","unstable_enableToolInvocations","status","values","type","beginEdit","messageId","onEdit","Error","constructor","contextProvider","__internal_setAdapter","_updateStoreSnapshot","previousIsRunning","oldStore","repositoryInstance","unstable_messageRepositoryInstance","repositoryChanged","repository","clear","__internal_setDispatchTransform","message","at","enrichAppendMetadata","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","incoming","headId","resetHead","getMessages","incomingIds","map","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","fallbackId","content","startsWith","updated","messageLike","newMessage","seenIds","deduped","i","warn","add","push","reverse","parent","size","getMessage","ensureInitialized","optimisticId","metadata","isOptimistic","messagesSnapshot","reset","_driveToolInvocations","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","isError","artifact","modelContent","err","onStatusesChange","statuses","hadExecutingTools","fromEntries","toolCall","unstable_isClientToolCall","setState","_toolCallToMessageId","_messagesForToolCallIndex","part","set","get","branchId","onBranchChange","unstable_onBranchChange","previousHeadId","canonicalHeadId","updateMessages","_notifyBranchChange","event","visibleMessageIds","append","rawMessage","_isVoiceMessage","sourceId","isEdit","generation","initPromise","steer","enqueue","startRun","abort","discardPending","onNew","wasVisible","some","messageIndex","findIndex","filter","_evictDeletedMessage","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","retractDraft","head","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","findLast","candidate","approval","approvalId","find","then","_notifyToolApprovalAnswered","approved","reject","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import { shallowEqual } from \"@assistant-ui/store/client\";\nimport 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 FALLBACK_ID_PREFIX,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport {\n getContentAutoStatus,\n isAutoStatus,\n} from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport { shallowArrayEqual } from \"../../runtime/utils/external-message-conversion\";\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 { walkToolCallTree } from \"../../runtime/utils/tool-call-tree\";\nimport {\n ToolInvocationTracker,\n type ToolExecutionStatus,\n} from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../runtime/queue/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\" | \"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\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 if (this._hasExecutingTools(this._store)) return true;\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 // Ids the host was asked to delete via onDelete. The snapshot pass evicts\n // them from the repository once the host's array no longer carries them;\n // an id the host kept is dropped from the set without eviction.\n // Branch-changing mutations (edit, branch switch, reload) invalidate the\n // set, because after them the incoming array omits off-branch ids for\n // reasons unrelated to deletion. Plain tail sends do not clear: a tail\n // append cannot make a visible id absent, so id-absence stays unambiguous\n // and a delete whose confirmation races a send keeps its eviction.\n private _pendingDeleteEvictions = new Set<string>();\n\n // Placeholder id for the upcoming assistant message, reused across snapshot\n // passes while the same tail message awaits its response so the placeholder\n // keeps one identity per response.\n private _optimistic: { id: string; parentId: string | null } | null = null;\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 private _toolStatuses: ReadonlyMap<string, ToolExecutionStatus> = new Map();\n private _effectiveIsRunning = false;\n private _inTrackerUpdate = false;\n private _pendingRunningRefresh = false;\n\n /**\n * Tracker mutations initiated by this class (setState, reset) can publish\n * status changes synchronously. Re-entering the snapshot pipeline from\n * inside them would feed the tracker a stale snapshot and consume the\n * restore arming a reset just installed, so the running refresh is\n * deferred until the mutation returns and stays off the tracker.\n */\n private _runTrackerUpdate(fn: () => void): void {\n this._inTrackerUpdate = true;\n try {\n fn();\n } finally {\n this._inTrackerUpdate = false;\n }\n if (this._pendingRunningRefresh) {\n this._pendingRunningRefresh = false;\n this._refreshEffectiveIsRunning();\n }\n }\n\n private _refreshEffectiveIsRunning(): void {\n const isRunning = this._getEffectiveIsRunning(this._store);\n if (this._effectiveIsRunning === isRunning) return;\n this._effectiveIsRunning = isRunning;\n this._notifyEventSubscribers(isRunning ? \"runStart\" : \"runEnd\", {});\n this._notifySubscribers();\n }\n\n private _hasExecutingTools(store: ExternalStoreAdapter<any>): boolean {\n if (store.unstable_enableToolInvocations !== true) return false;\n if (this._toolInvocations === null) return false;\n for (const status of this._toolStatuses.values()) {\n if (status.type === \"executing\") return true;\n }\n return false;\n }\n\n private _getEffectiveIsRunning(store: ExternalStoreAdapter<any>): boolean {\n return (store.isRunning ?? false) || this._hasExecutingTools(store);\n }\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 this._updateStoreSnapshot(store);\n }\n\n private _updateStoreSnapshot(store: ExternalStoreAdapter<any>) {\n const previousIsRunning = this._effectiveIsRunning;\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 const isRunning = this._getEffectiveIsRunning(store);\n const repositoryInstance = store.unstable_messageRepositoryInstance;\n const repositoryChanged =\n repositoryInstance !== undefined &&\n repositoryInstance !== this.repository;\n if (repositoryChanged) {\n this.repository = repositoryInstance;\n this._pendingDeleteEvictions.clear();\n }\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 !repositoryChanged &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository &&\n previousIsRunning === isRunning\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 (\n oldStore &&\n !repositoryChanged &&\n oldStore.messageRepository === store.messageRepository\n ) {\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._pendingDeleteEvictions.clear();\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 !repositoryChanged &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages &&\n previousIsRunning === isRunning\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 fallbackId = `${FALLBACK_ID_PREFIX}${idx}`;\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status ===\n getContentAutoStatus(cache.content, isLast, isRunning))\n ) {\n if (\n cache.id.startsWith(FALLBACK_ID_PREFIX) &&\n cache.id !== fallbackId\n ) {\n const updated = { ...cache, id: fallbackId };\n bindExternalStoreMessage(updated, m);\n return updated;\n }\n return cache;\n }\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n fallbackId,\n getContentAutoStatus(messageLike.content, isLast, isRunning),\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\n if (this._pendingDeleteEvictions.size > 0) {\n const incomingIds = new Set(messages.map((m) => m.id));\n for (const id of this._pendingDeleteEvictions) {\n this._pendingDeleteEvictions.delete(id);\n if (incomingIds.has(id)) continue;\n try {\n this.repository.getMessage(id);\n } catch {\n continue;\n }\n this.repository.deleteMessage(id);\n }\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 this._effectiveIsRunning = isRunning;\n if (previousIsRunning !== isRunning) {\n if (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 const parentId = messages.at(-1)?.id ?? null;\n if (this._optimistic?.parentId !== parentId) {\n this._optimistic = { id: generateId(), parentId };\n }\n optimisticId = this._optimistic.id;\n this.repository.addOrUpdateMessage(\n parentId,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n if (optimisticId === null) this._optimistic = null;\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n const messagesSnapshot = this.repository.getMessages();\n if (\n !this._messages ||\n !shallowArrayEqual(this._messages, messagesSnapshot)\n ) {\n this._messages = messagesSnapshot;\n }\n\n if (repositoryChanged) {\n this._runTrackerUpdate(() => this._toolInvocations?.reset());\n }\n this._runTrackerUpdate(() => 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._toolStatuses = new Map();\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 const hadExecutingTools = this._hasExecutingTools(this._store);\n this._toolStatuses = statuses;\n try {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n } finally {\n if (hadExecutingTools !== this._hasExecutingTools(this._store)) {\n if (this._inTrackerUpdate) {\n this._pendingRunningRefresh = true;\n } else {\n this._updateStoreSnapshot(this._store);\n }\n }\n }\n },\n },\n (toolCall) => this._store.unstable_isClientToolCall?.(toolCall),\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._getEffectiveIsRunning(this._store),\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 for (const { part, messageId } of walkToolCallTree(this._messages)) {\n this._toolCallToMessageId.set(part.toolCallId, messageId);\n }\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._getEffectiveIsRunning(this._store)) {\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._pendingDeleteEvictions.clear();\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 if (this._isVoiceMessage(rawMessage.sourceId))\n throw new Error(\"Voice transcript messages cannot be edited\");\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._getEffectiveIsRunning(this._store))\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({ discardPending: true });\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 this._pendingDeleteEvictions.clear();\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 // The host owns deletion here, and it may decline (fail a server call,\n // cancel a confirm dialog, ignore an off-branch id). The eviction is\n // therefore deferred to the snapshot pass, which evicts only once the\n // host's own array no longer carries the id. Registered before the\n // callback because an optimistic host publishes that snapshot while\n // the callback is still awaited.\n const wasVisible = this.repository\n .getMessages()\n .some((m) => m.id === messageId);\n if (wasVisible) this._pendingDeleteEvictions.add(messageId);\n try {\n await this._store.onDelete(messageId);\n } catch (error) {\n this._pendingDeleteEvictions.delete(messageId);\n throw error;\n }\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._getEffectiveIsRunning(this._store)) {\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._pendingDeleteEvictions.clear();\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n this._evictDeletedMessage(messageId);\n }\n\n // The snapshot pass only relinks incoming messages; it never evicts, so\n // without this the deleted message survives as a sibling branch that the\n // branch picker can resurrect into the host store. `_messages` is refreshed\n // before notifying so `messages` and the branch graph agree at notify time,\n // mirroring the end of the snapshot pass.\n private _evictDeletedMessage(messageId: string) {\n // Positional fallback ids are remapped in the snapshot pass; evicting\n // them first leaves the pre-renumber node as a sibling of the new head.\n if (messageId.startsWith(FALLBACK_ID_PREFIX)) return;\n // A synchronous host update (e.g. a setMessages that re-entered the\n // snapshot pass) may have evicted the message already; only that case is\n // skipped, so genuine repository errors still propagate.\n try {\n this.repository.getMessage(messageId);\n } catch {\n return;\n }\n\n this.repository.deleteMessage(messageId);\n this._messages = this.repository.getMessages();\n this._notifySubscribers();\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 if (this._isVoiceMessage(config.sourceId))\n throw new Error(\"Voice transcript messages cannot be reloaded\");\n\n this._pendingDeleteEvictions.clear();\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({ discardPending: true });\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 if (this._isVoiceMessage(config.sourceId))\n throw new Error(\"Voice transcript messages cannot be reloaded\");\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._runTrackerUpdate(() => 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._runTrackerUpdate(() => 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 const generation = captureThreadRuntimeGeneration(this);\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({ discardPending: true });\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 if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n\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(\n options: RespondToToolApprovalOptions,\n ): Promise<void> {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n const message = this.messages.findLast(\n (candidate) =>\n candidate.role === \"assistant\" &&\n candidate.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n part.approval?.id === options.approvalId,\n ),\n );\n const toolCall = message?.content.find(\n (part) =>\n part.type === \"tool-call\" && part.approval?.id === options.approvalId,\n );\n try {\n return Promise.resolve(this._store.onRespondToToolApproval(options)).then(\n () => {\n if (message && toolCall?.type === \"tool-call\") {\n this._notifyToolApprovalAnswered(\n message.id,\n toolCall.toolCallId,\n toolCall.toolName,\n options.approved,\n );\n }\n },\n );\n } catch (error) {\n return Promise.reject(error);\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 }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2DA,MAAMsC,cAA2CC,OAAOC,OAAO,CAAA,CAAE;AAEjE,MAAMC,0BACJC,MACAC,WACG;CACH,QAAaE,QAAQF,MAAM,CAAC,CAACG,OAAOC,UAAU;EAC5CC,QAAQD,MACN,oCAAoCL,KAAI,qBACxCK,KACF;CACF,CAAC;AACH;AAEA,MAAaE,sBACXC,WACAC,aACG;CACH,OAAOD,aAAaC,SAASA,SAASC,SAAS,EAAE,EAAEC,SAAS;AAC9D;AAEA,IAAaC,iCAAb,cACU5B,sBAEV;CACE,gBAA6C;EAC3C8B,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,IAAWC,eAAe;EACxB,OAAO,KAAKf;CACd;CAEA;CACA;CACA;CACA,IAAWmB,YAAY;EACrB,OAAO,K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J,CACF;EACF,SAAS7O,OAAO;GACd,OAAOH,QAAQiP,OAAO9O,KAAK;EAC7B;CACF;CAEA,MAAsB+O,iBAAgD;EACpE,MAAMC,OAAO,IAAIlQ,kBAAkB;EACnCkQ,KAAKC,OAAOpQ,0BAA0BqQ,UAAUH,mBAAmB,CAAA,CAAE,CAAC;EACtE,KAAK5E,eAAe6E,KAAK/I,YAAY,CAAC;CACxC;CAEA,OAAuBkJ,MAAiC;EACtD,MAAMF,OAAOE,IAAI;EAEjB,IAAI,KAAKvN,OAAOwN,UACd,KAAKxN,OAAOwN,SAAS,KAAKrK,WAAWkB,YAAY,CAAC;CAEtD;CAEA,kBAA0B7F,aAAuC;EAE/D,IADqB,KAAKwB,OAAO4E,mBAAmBrE,KAAAA,GAElD,KAAKP,OAAO2D,cAAcnF,SAASkP,QAAQzR,wBAAwB,CAAC;OAGpE,KAAK+D,OAAO2D,cAAcnF,QAA2B;CAEzD;AACF"}
|
|
@@ -5,12 +5,12 @@ import { LocalThreadFactory, LocalThreadListRuntimeCore } from "./local/local-th
|
|
|
5
5
|
import { LocalRuntimeCore } from "./local/local-runtime-core.js";
|
|
6
6
|
import { shouldContinue } from "./local/should-continue.js";
|
|
7
7
|
import { RemoteThreadInitializeResponse, RemoteThreadListOptions } from "./remote-thread-list/types.js";
|
|
8
|
+
import { ConverterCallback, ThreadMessageConverter } from "./external-store/thread-message-converter.js";
|
|
8
9
|
import { ExternalStoreThreadRuntimeCore, hasUpcomingMessage } from "./external-store/external-store-thread-runtime-core.js";
|
|
9
10
|
import { ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore } from "./external-store/external-store-thread-list-runtime-core.js";
|
|
10
11
|
import { ExternalStoreRuntimeCore } from "./external-store/external-store-runtime-core.js";
|
|
11
|
-
import { ConverterCallback, ThreadMessageConverter } from "./external-store/thread-message-converter.js";
|
|
12
12
|
import { ReadonlyThreadRuntimeCore } from "./readonly/ReadonlyThreadRuntimeCore.js";
|
|
13
13
|
import { OptimisticState } from "./remote-thread-list/optimistic-state.js";
|
|
14
14
|
import { EMPTY_THREAD_CORE } from "./remote-thread-list/empty-thread-core.js";
|
|
15
|
-
import { RemoteThreadData, RemoteThreadState, THREAD_MAPPING_ID, createThreadMappingId, getThreadData, updateStatusReducer } from "./remote-thread-list/remote-thread-state.js";
|
|
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 };
|
|
15
|
+
import { RemoteThreadData, RemoteThreadState, THREAD_MAPPING_ID, createThreadMappingId, getThreadData, promoteNewThreadReducer, updateStatusReducer } from "./remote-thread-list/remote-thread-state.js";
|
|
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, promoteNewThreadReducer, shouldContinue, updateStatusReducer };
|
|
@@ -10,5 +10,5 @@ import { ExternalStoreRuntimeCore } from "./external-store/external-store-runtim
|
|
|
10
10
|
import { ReadonlyThreadRuntimeCore } from "./readonly/ReadonlyThreadRuntimeCore.js";
|
|
11
11
|
import { OptimisticState } from "./remote-thread-list/optimistic-state.js";
|
|
12
12
|
import { EMPTY_THREAD_CORE } from "./remote-thread-list/empty-thread-core.js";
|
|
13
|
-
import { createThreadMappingId, getThreadData, updateStatusReducer } from "./remote-thread-list/remote-thread-state.js";
|
|
14
|
-
export { EMPTY_THREAD_CORE, ExternalStoreRuntimeCore, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LocalRuntimeCore, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, OptimisticState, ReadonlyThreadRuntimeCore, ThreadMessageConverter, ToolInvocationTracker, createThreadMappingId, getThreadData, hasUpcomingMessage, shouldContinue, updateStatusReducer };
|
|
13
|
+
import { createThreadMappingId, getThreadData, promoteNewThreadReducer, updateStatusReducer } from "./remote-thread-list/remote-thread-state.js";
|
|
14
|
+
export { EMPTY_THREAD_CORE, ExternalStoreRuntimeCore, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LocalRuntimeCore, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, OptimisticState, ReadonlyThreadRuntimeCore, ThreadMessageConverter, ToolInvocationTracker, createThreadMappingId, getThreadData, hasUpcomingMessage, promoteNewThreadReducer, shouldContinue, updateStatusReducer };
|