@assistant-ui/core 0.2.6 → 0.2.7

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.
Files changed (70) hide show
  1. package/dist/index.d.ts +3 -1
  2. package/dist/index.js +6 -0
  3. package/dist/index.js.map +1 -0
  4. package/dist/internal/duplicate-detection.d.ts +5 -0
  5. package/dist/internal/duplicate-detection.d.ts.map +1 -0
  6. package/dist/internal/duplicate-detection.js +11 -0
  7. package/dist/internal/duplicate-detection.js.map +1 -0
  8. package/dist/react/AssistantProvider.d.ts.map +1 -1
  9. package/dist/react/AssistantProvider.js.map +1 -1
  10. package/dist/react/index.d.ts +2 -2
  11. package/dist/react/index.js +1 -2
  12. package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js.map +1 -1
  13. package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
  14. package/dist/react/runtimes/external-message-converter.d.ts +1 -1
  15. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  16. package/dist/runtime/api/attachment-runtime.d.ts.map +1 -1
  17. package/dist/runtime/api/attachment-runtime.js.map +1 -1
  18. package/dist/runtime/interfaces/thread-runtime-core.d.ts +8 -0
  19. package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
  20. package/dist/runtimes/external-store/external-store-adapter.d.ts +31 -0
  21. package/dist/runtimes/external-store/external-store-adapter.d.ts.map +1 -1
  22. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
  23. package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
  24. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +25 -0
  25. package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
  26. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +94 -3
  27. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  28. package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts +168 -0
  29. package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -0
  30. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +449 -0
  31. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -0
  32. package/dist/subscribable/subscribable.d.ts.map +1 -1
  33. package/dist/subscribable/subscribable.js.map +1 -1
  34. package/package.json +3 -3
  35. package/src/adapters/index.ts +1 -4
  36. package/src/index.ts +10 -0
  37. package/src/internal/duplicate-detection.ts +26 -0
  38. package/src/react/AssistantProvider.tsx +2 -3
  39. package/src/react/index.ts +1 -6
  40. package/src/react/primitives/chainOfThought/ChainOfThoughtParts.tsx +1 -2
  41. package/src/react/primitives/message/MessageAttachments.test.tsx +1 -1
  42. package/src/react/primitives/message/MessageGroupedParts.tsx +1 -1
  43. package/src/react/runtimes/external-message-converter.ts +1 -1
  44. package/src/runtime/api/attachment-runtime.ts +1 -2
  45. package/src/runtime/interfaces/thread-runtime-core.ts +8 -0
  46. package/src/runtime/internal.ts +1 -4
  47. package/src/runtimes/external-store/external-store-adapter.ts +33 -0
  48. package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +1 -3
  49. package/src/runtimes/external-store/external-store-thread-runtime-core.ts +161 -4
  50. package/src/runtimes/tool-invocations/EDGE_CASES.md +194 -0
  51. package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +1054 -0
  52. package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +783 -0
  53. package/src/subscribable/subscribable.ts +3 -3
  54. package/src/tests/OptimisticState-delete-crash.test.ts +2 -0
  55. package/src/tests/OptimisticState-list-race.test.ts +2 -0
  56. package/src/tests/RemoteThreadListThreadListRuntimeCore-loadMore.test.ts +5 -5
  57. package/src/tests/auiV0Encode.test.ts +1 -1
  58. package/src/tests/composer-can-send.test.ts +8 -4
  59. package/src/tests/duplicate-detection.test.ts +34 -0
  60. package/src/tests/external-store-thread-list-runtime-core.test.ts +1 -1
  61. package/src/tests/external-store-thread-runtime-core.test.ts +7 -6
  62. package/src/tests/no-unsafe-process-env.test.ts +1 -0
  63. package/src/tests/remote-thread-list-isLoading.test.ts +2 -0
  64. package/src/tests/thread-message-like.test.ts +4 -1
  65. package/src/types/index.ts +1 -4
  66. package/dist/react/runtimes/useToolInvocations.d.ts +0 -53
  67. package/dist/react/runtimes/useToolInvocations.d.ts.map +0 -1
  68. package/dist/react/runtimes/useToolInvocations.js +0 -380
  69. package/dist/react/runtimes/useToolInvocations.js.map +0 -1
  70. package/src/react/runtimes/useToolInvocations.ts +0 -694
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference path="./store/scope-registration.d.ts" />
1
2
  import { AppendMessage, DataMessagePart, FileMessagePart, GenerativeUIMessagePart, GenerativeUINode, GenerativeUISpec, ImageMessagePart, MCP_APP_URI_SCHEME, McpAppMetadata, MessagePartStatus, MessageRole, MessageStatus, MessageTiming, ReasoningMessagePart, RunConfig, SourceMessagePart, SourceProviderMetadata, TextMessagePart, ThreadAssistantMessage, ThreadAssistantMessagePart, ThreadMessage, ThreadStep, ThreadSystemMessage, ThreadUserMessage, ThreadUserMessagePart, ToolCallMessagePart, ToolCallMessagePartMcpMetadata, ToolCallMessagePartStatus, ToolModelContentPart, Unstable_AudioMessagePart, isMcpAppUri } from "./types/message.js";
2
3
  import { Attachment, AttachmentStatus, CompleteAttachment, CompleteAttachmentStatus, CreateAttachment, PendingAttachment, PendingAttachmentStatus } from "./types/attachment.js";
3
4
  import { AttachmentAdapter, CompositeAttachmentAdapter, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter } from "./adapters/attachment.js";
@@ -19,6 +20,7 @@ import { SuggestionAdapter } from "./adapters/suggestion.js";
19
20
  import { Unstable_TriggerAdapter } from "./adapters/trigger.js";
20
21
  import { GenericThreadHistoryAdapter, MessageFormatAdapter, MessageFormatItem, MessageFormatRepository, MessageStorageEntry, ThreadHistoryAdapter } from "./adapters/thread-history.js";
21
22
  import { tool } from "./model-context/tool.js";
23
+ import { ToolExecutionStatus } from "./runtimes/tool-invocations/ToolInvocationTracker.js";
22
24
  import { ModelContextRegistryInstructionHandle, ModelContextRegistryProviderHandle, ModelContextRegistryToolHandle } from "./model-context/registry-handles.js";
23
25
  import { ModelContextRegistry } from "./model-context/registry.js";
24
26
  import { AssistantFrameHost } from "./model-context/frame/host.js";
@@ -42,4 +44,4 @@ import { CreateAppendMessage, CreateResumeRunConfig, CreateStartRunConfig, Threa
42
44
  import { AssistantRuntime } from "./runtime/api/assistant-runtime.js";
43
45
  import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
44
46
  import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
45
- export { type AddToolResultOptions, type AppendMessage, type AssistantContextConfig, AssistantFrameHost, AssistantFrameProvider, type AssistantInstructionsConfig, type AssistantRuntime, type AssistantRuntimeCore, type AssistantToolProps, type Attachment, type AttachmentAdapter, type AttachmentAddErrorEvent, type AttachmentAddErrorReason, type AttachmentRuntime, type AttachmentRuntimePath, type AttachmentState, type AttachmentStatus, type ChatModelAdapter, type ChatModelRunOptions, type ChatModelRunResult, type ChatModelRunUpdate, type CompleteAttachment, type CompleteAttachmentStatus, type ComposerRuntime, type ComposerRuntimeCore, type ComposerRuntimeEventCallback, type ComposerRuntimeEventPayload, type ComposerRuntimeEventType, type ComposerRuntimePath, type ComposerState, CompositeAttachmentAdapter, type CoreChatModelRunResult, type CreateAppendMessage, type CreateAttachment, type CreateResumeRunConfig, type CreateStartRunConfig, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreMessageConverter, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, FRAME_MESSAGE_CHANNEL, type FeedbackAdapter, type FileMessagePart, type FrameMessage, type FrameMessageType, type GenerativeUIMessagePart, type GenerativeUINode, type GenerativeUISpec, type GenericThreadHistoryAdapter, type ImageMessagePart, InMemoryThreadListAdapter, type LanguageModelConfig, type LanguageModelV1CallSettings, type LocalRuntimeOptionsBase, MCP_APP_URI_SCHEME, type McpAppMetadata, type MessageFormatAdapter, type MessageFormatItem, type MessageFormatRepository, type MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, type MessageRole, type MessageRuntime, type MessageRuntimePath, type MessageState, type MessageStatus, type MessageStorageEntry, type MessageTiming, type ModelContext, type ModelContextProvider, ModelContextRegistry, type ModelContextRegistryInstructionHandle, type ModelContextRegistryProviderHandle, type ModelContextRegistryToolHandle, type PendingAttachment, type PendingAttachmentStatus, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, type ThreadListItemRuntime, type ThreadListItemRuntimePath, type ThreadListItemState, type ThreadListItemStatus, type ThreadListRuntime, type ThreadListRuntimeCore, type ThreadListState, type ThreadMessage, type ThreadMessageLike, type ThreadRuntime, type ThreadRuntimeCore, type ThreadRuntimeEventCallback, type ThreadRuntimeEventPayload, type ThreadRuntimeEventType, type ThreadRuntimePath, type ThreadState, type ThreadStep, type ThreadSuggestion, type ThreadSystemMessage, type ThreadUserMessage, type ThreadUserMessagePart, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, tool, unstable_defaultDirectiveFormatter };
47
+ export { type AddToolResultOptions, type AppendMessage, type AssistantContextConfig, AssistantFrameHost, AssistantFrameProvider, type AssistantInstructionsConfig, type AssistantRuntime, type AssistantRuntimeCore, type AssistantToolProps, type Attachment, type AttachmentAdapter, type AttachmentAddErrorEvent, type AttachmentAddErrorReason, type AttachmentRuntime, type AttachmentRuntimePath, type AttachmentState, type AttachmentStatus, type ChatModelAdapter, type ChatModelRunOptions, type ChatModelRunResult, type ChatModelRunUpdate, type CompleteAttachment, type CompleteAttachmentStatus, type ComposerRuntime, type ComposerRuntimeCore, type ComposerRuntimeEventCallback, type ComposerRuntimeEventPayload, type ComposerRuntimeEventType, type ComposerRuntimePath, type ComposerState, CompositeAttachmentAdapter, type CoreChatModelRunResult, type CreateAppendMessage, type CreateAttachment, type CreateResumeRunConfig, type CreateStartRunConfig, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreMessageConverter, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, FRAME_MESSAGE_CHANNEL, type FeedbackAdapter, type FileMessagePart, type FrameMessage, type FrameMessageType, type GenerativeUIMessagePart, type GenerativeUINode, type GenerativeUISpec, type GenericThreadHistoryAdapter, type ImageMessagePart, InMemoryThreadListAdapter, type LanguageModelConfig, type LanguageModelV1CallSettings, type LocalRuntimeOptionsBase, MCP_APP_URI_SCHEME, type McpAppMetadata, type MessageFormatAdapter, type MessageFormatItem, type MessageFormatRepository, type MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, type MessageRole, type MessageRuntime, type MessageRuntimePath, type MessageState, type MessageStatus, type MessageStorageEntry, type MessageTiming, type ModelContext, type ModelContextProvider, ModelContextRegistry, type ModelContextRegistryInstructionHandle, type ModelContextRegistryProviderHandle, type ModelContextRegistryToolHandle, type PendingAttachment, type PendingAttachmentStatus, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, type ThreadListItemRuntime, type ThreadListItemRuntimePath, type ThreadListItemState, type ThreadListItemStatus, type ThreadListRuntime, type ThreadListRuntimeCore, type ThreadListState, type ThreadMessage, type ThreadMessageLike, type ThreadRuntime, type ThreadRuntimeCore, type ThreadRuntimeEventCallback, type ThreadRuntimeEventPayload, type ThreadRuntimeEventType, type ThreadRuntimePath, type ThreadState, type ThreadStep, type ThreadSuggestion, type ThreadSystemMessage, type ThreadUserMessage, type ThreadUserMessagePart, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolExecutionStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, tool, unstable_defaultDirectiveFormatter };
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { checkDuplicateCore } from "./internal/duplicate-detection.js";
1
2
  import { MCP_APP_URI_SCHEME, isMcpAppUri } from "./types/message.js";
2
3
  import { mergeModelContexts } from "./model-context/types.js";
3
4
  import { tool } from "./model-context/tool.js";
@@ -13,4 +14,9 @@ import { bindExternalStoreMessage, getExternalStoreMessages } from "./runtime/ut
13
14
  import { ExportedMessageRepository } from "./runtime/utils/message-repository.js";
14
15
  import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
15
16
  import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
17
+ //#region src/index.ts
18
+ if (process.env.NODE_ENV !== "production") checkDuplicateCore();
19
+ //#endregion
16
20
  export { AssistantFrameHost, AssistantFrameProvider, CompositeAttachmentAdapter, ExportedMessageRepository, FRAME_MESSAGE_CHANNEL, InMemoryThreadListAdapter, MCP_APP_URI_SCHEME, ModelContextRegistry, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, tool, unstable_defaultDirectiveFormatter };
21
+
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["// @assistant-ui/core - Framework-agnostic core runtime (public API)\n\n/// <reference path=\"./store/scope-registration.ts\" />\n\nimport { checkDuplicateCore } from \"./internal/duplicate-detection\";\n\nif (process.env.NODE_ENV !== \"production\") {\n checkDuplicateCore();\n}\n\nexport type {\n // Message parts\n TextMessagePart,\n ReasoningMessagePart,\n SourceProviderMetadata,\n SourceMessagePart,\n ImageMessagePart,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n GenerativeUINode,\n GenerativeUISpec,\n Unstable_AudioMessagePart,\n ToolCallMessagePart,\n ToolCallMessagePartMcpMetadata,\n McpAppMetadata,\n ToolModelContentPart,\n ThreadUserMessagePart,\n ThreadAssistantMessagePart,\n // Message status\n MessagePartStatus,\n ToolCallMessagePartStatus,\n MessageStatus,\n // Thread messages\n MessageTiming,\n ThreadStep,\n ThreadSystemMessage,\n ThreadUserMessage,\n ThreadAssistantMessage,\n ThreadMessage,\n MessageRole,\n // Config\n RunConfig,\n AppendMessage,\n} from \"./types/message\";\n\nexport { MCP_APP_URI_SCHEME, isMcpAppUri } from \"./types/message\";\n\nexport type {\n Attachment,\n PendingAttachment,\n PendingAttachmentStatus,\n CompleteAttachment,\n CompleteAttachmentStatus,\n AttachmentStatus,\n CreateAttachment,\n} from \"./types/attachment\";\n\nexport type { Unsubscribe } from \"./types/unsubscribe\";\n\nexport type { QuoteInfo } from \"./types/quote\";\n\nexport type {\n Unstable_DirectiveSegment,\n Unstable_DirectiveFormatter,\n} from \"./types/directive\";\n\nexport type {\n Unstable_TriggerItem,\n Unstable_TriggerCategory,\n} from \"./types/trigger\";\n\nexport type { Unstable_TriggerAdapter } from \"./adapters/trigger\";\n\nexport type {\n // Language model settings\n LanguageModelV1CallSettings,\n LanguageModelConfig,\n // Model context\n ModelContext,\n ModelContextProvider,\n // Tool & instruction config\n AssistantToolProps,\n AssistantInstructionsConfig,\n AssistantContextConfig,\n} from \"./model-context/types\";\nexport { mergeModelContexts } from \"./model-context/types\";\n\nexport { tool } from \"./model-context/tool\";\n\nexport type { ToolExecutionStatus } from \"./runtimes/tool-invocations/ToolInvocationTracker\";\n\nexport { ModelContextRegistry } from \"./model-context/registry\";\nexport type {\n ModelContextRegistryToolHandle,\n ModelContextRegistryInstructionHandle,\n ModelContextRegistryProviderHandle,\n} from \"./model-context/registry-handles\";\n\nexport { AssistantFrameHost } from \"./model-context/frame/host\";\nexport { AssistantFrameProvider } from \"./model-context/frame/provider\";\nexport type {\n SerializedTool,\n SerializedModelContext,\n FrameMessageType,\n FrameMessage,\n} from \"./model-context/frame/types\";\nexport { FRAME_MESSAGE_CHANNEL } from \"./model-context/frame/types\";\n\n// Attachment adapters\nexport type { AttachmentAdapter } from \"./adapters/attachment\";\nexport {\n SimpleImageAttachmentAdapter,\n SimpleTextAttachmentAdapter,\n CompositeAttachmentAdapter,\n} from \"./adapters/attachment\";\n\n// Speech adapters\nexport type {\n SpeechSynthesisAdapter,\n DictationAdapter,\n} from \"./adapters/speech\";\nexport {\n WebSpeechSynthesisAdapter,\n WebSpeechDictationAdapter,\n} from \"./adapters/speech\";\n\n// Voice adapter\nexport type { RealtimeVoiceAdapter } from \"./adapters/voice\";\nexport { createVoiceSession } from \"./adapters/voice\";\nexport type {\n VoiceSessionControls,\n VoiceSessionHelpers,\n} from \"./adapters/voice\";\n\n// Feedback adapter\nexport type { FeedbackAdapter } from \"./adapters/feedback\";\n\n// Suggestion adapter\nexport type { SuggestionAdapter } from \"./adapters/suggestion\";\n\n// Directive formatter\nexport { unstable_defaultDirectiveFormatter } from \"./adapters/directive-formatter\";\n\n// Thread history adapters\nexport type {\n ThreadHistoryAdapter,\n GenericThreadHistoryAdapter,\n MessageFormatAdapter,\n MessageFormatItem,\n MessageFormatRepository,\n MessageStorageEntry,\n} from \"./adapters/thread-history\";\n\n// Path Types\nexport type {\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n MessageRuntimePath,\n MessagePartRuntimePath,\n AttachmentRuntimePath,\n ComposerRuntimePath,\n} from \"./runtime/api/paths\";\n\n// Runtime Core Interface Types\nexport type {\n AttachmentAddErrorEvent,\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n EditComposerRuntimeCore,\n SendOptions,\n ThreadComposerRuntimeCore,\n} from \"./runtime/interfaces/composer-runtime-core\";\n\nexport type {\n RuntimeCapabilities,\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n SubmitFeedbackOptions,\n ThreadSuggestion,\n SpeechState,\n VoiceSessionState,\n SubmittedFeedback,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventPayload,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n ThreadRuntimeCore,\n} from \"./runtime/interfaces/thread-runtime-core\";\n\nexport type {\n ThreadListItemStatus,\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"./runtime/interfaces/thread-list-runtime-core\";\n\nexport type { AssistantRuntimeCore } from \"./runtime/interfaces/assistant-runtime-core\";\n\n// Public Runtime Types\nexport type { AssistantRuntime } from \"./runtime/api/assistant-runtime\";\n\nexport type {\n CreateStartRunConfig,\n CreateResumeRunConfig,\n CreateAppendMessage,\n ThreadState,\n ThreadRuntime,\n} from \"./runtime/api/thread-runtime\";\n\nexport type {\n ThreadListState,\n ThreadListRuntime,\n} from \"./runtime/api/thread-list-runtime\";\n\nexport type {\n ThreadListItemEventCallback,\n ThreadListItemEventPayload,\n ThreadListItemEventType,\n ThreadListItemRuntime,\n} from \"./runtime/api/thread-list-item-runtime\";\n\nexport type { ThreadListItemState } from \"./runtime/api/bindings\";\n\nexport type {\n MessageState,\n MessageRuntime,\n} from \"./runtime/api/message-runtime\";\nexport type {\n MessagePartState,\n MessagePartRuntime,\n} from \"./runtime/api/message-part-runtime\";\n\nexport type {\n ThreadComposerState,\n EditComposerState,\n ComposerState,\n ComposerRuntime,\n ThreadComposerRuntime,\n EditComposerRuntime,\n} from \"./runtime/api/composer-runtime\";\n\nexport type {\n AttachmentState,\n AttachmentRuntime,\n} from \"./runtime/api/attachment-runtime\";\n\n// ChatModel Types\nexport type {\n ChatModelRunUpdate,\n ChatModelRunResult,\n CoreChatModelRunResult,\n ChatModelRunOptions,\n ChatModelAdapter,\n} from \"./runtime/utils/chat-model-adapter\";\n\n// ThreadMessageLike\nexport type { ThreadMessageLike } from \"./runtime/utils/thread-message-like\";\n\n// External Store Message Utilities\nexport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"./runtime/utils/external-store-message\";\n\n// ExportedMessageRepository\nexport type { ExportedMessageRepositoryItem } from \"./runtime/utils/message-repository\";\nexport { ExportedMessageRepository } from \"./runtime/utils/message-repository\";\n\n// Local Runtime Options\nexport type { LocalRuntimeOptionsBase } from \"./runtimes/local/local-runtime-options\";\n\n// External Store Adapter Types (user-facing)\nexport type {\n ExternalStoreAdapter,\n ExternalStoreMessageConverter,\n ExternalStoreThreadListAdapter,\n ExternalStoreThreadData,\n} from \"./runtimes/external-store/external-store-adapter\";\n\n// Remote Thread List (user-facing)\nexport type {\n RemoteThreadListAdapter,\n RemoteThreadListOptions,\n RemoteThreadInitializeResponse,\n RemoteThreadMetadata,\n RemoteThreadListResponse,\n RemoteThreadListPageOptions,\n} from \"./runtimes/remote-thread-list/types\";\n\nexport { InMemoryThreadListAdapter } from \"./runtimes/remote-thread-list/adapter/in-memory\";\n\n// Assistant Transport Utilities\nexport { createRequestHeaders } from \"./runtimes/assistant-transport/utils\";\n"],"mappings":";;;;;;;;;;;;;;;;;AAMA,IAAI,QAAQ,IAAI,aAAa,cAC3B,mBAAmB"}
@@ -0,0 +1,5 @@
1
+ //#region src/internal/duplicate-detection.d.ts
2
+ declare function checkDuplicateCore(): void;
3
+ //#endregion
4
+ export { checkDuplicateCore };
5
+ //# sourceMappingURL=duplicate-detection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duplicate-detection.d.ts","names":[],"sources":["../../src/internal/duplicate-detection.ts"],"mappings":";iBAYgB,kBAAA,CAAA"}
@@ -0,0 +1,11 @@
1
+ //#region src/internal/duplicate-detection.ts
2
+ const KEY = Symbol.for("@assistant-ui/core.loaded");
3
+ function checkDuplicateCore() {
4
+ const g = globalThis;
5
+ if (g[KEY]) console.warn("[@assistant-ui/core] Multiple copies of @assistant-ui/core are loaded into the same runtime. This causes subtle bugs (tools not reaching the runtime, context lookups returning the wrong provider, instanceof checks failing). Run `npx assistant-ui doctor` to diagnose.");
6
+ g[KEY] = true;
7
+ }
8
+ //#endregion
9
+ export { checkDuplicateCore };
10
+
11
+ //# sourceMappingURL=duplicate-detection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duplicate-detection.js","names":[],"sources":["../../src/internal/duplicate-detection.ts"],"sourcesContent":["// Warns once if a second copy of @assistant-ui/core is loaded into the\n// same runtime. Mismatched transitive versions of core silently break\n// runtime behavior — tools registered via `makeAssistantTool` don't reach\n// the active runtime, context lookups resolve to the wrong provider,\n// `instanceof` checks fail (see issue #4101). The actual version diagnosis\n// lives in `npx assistant-ui doctor`.\n//\n// The caller is responsible for gating on `process.env.NODE_ENV` so this\n// module tree-shakes out of production bundles.\n\nconst KEY = Symbol.for(\"@assistant-ui/core.loaded\");\n\nexport function checkDuplicateCore(): void {\n const g = globalThis as unknown as Record<symbol, boolean | undefined>;\n if (g[KEY]) {\n // eslint-disable-next-line no-console\n console.warn(\n \"[@assistant-ui/core] Multiple copies of @assistant-ui/core are \" +\n \"loaded into the same runtime. This causes subtle bugs (tools not \" +\n \"reaching the runtime, context lookups returning the wrong \" +\n \"provider, instanceof checks failing). Run \" +\n \"`npx assistant-ui doctor` to diagnose.\",\n );\n }\n g[KEY] = true;\n}\n"],"mappings":";AAUA,MAAM,MAAM,OAAO,IAAI,2BAA2B;AAElD,SAAgB,qBAA2B;CACzC,MAAM,IAAI;CACV,IAAI,EAAE,MAEJ,QAAQ,KACN,4QAKF;CAEF,EAAE,OAAO;AACX"}
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantProvider.d.ts","names":[],"sources":["../../src/react/AssistantProvider.tsx"],"mappings":";;;;;cAWa,kBAAA,GAAsB,OAAA,EAAS,gBAAA,KAEtC,aAAa;AAAA,KAIP,0BAAA,GAA6B,iBAAA;EACvC,OAAA,EAAS,gBAAA;EACT,GAAA,GAAM,eAAA;AAAA;AAAA,cAGK,qBAAA,EAAuB,EAAE,CAAC,0BAAA"}
1
+ {"version":3,"file":"AssistantProvider.d.ts","names":[],"sources":["../../src/react/AssistantProvider.tsx"],"mappings":";;;;;cAWa,kBAAA,GAAsB,OAAA,EAAS,gBAAA,KAEnB,aAAa;AAAA,KAG1B,0BAAA,GAA6B,iBAAA;EACvC,OAAA,EAAS,gBAAA;EACT,GAAA,GAAM,eAAA;AAAA;AAAA,cAGK,qBAAA,EAAuB,EAAE,CAAC,0BAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantProvider.js","names":[],"sources":["../../src/react/AssistantProvider.tsx"],"sourcesContent":["import {\n memo,\n type ComponentType,\n type FC,\n type PropsWithChildren,\n} from \"react\";\nimport { useAui, AuiProvider, type AssistantClient } from \"@assistant-ui/store\";\nimport type { AssistantRuntime } from \"../runtime/api/assistant-runtime\";\nimport type { AssistantRuntimeCore } from \"../runtime/interfaces/assistant-runtime-core\";\nimport { RuntimeAdapter } from \"./RuntimeAdapter\";\n\nexport const getRenderComponent = (runtime: AssistantRuntime) => {\n return (runtime as { _core?: AssistantRuntimeCore })._core?.RenderComponent as\n | ComponentType\n | undefined;\n};\n\nexport type AssistantProviderBaseProps = PropsWithChildren<{\n runtime: AssistantRuntime;\n aui?: AssistantClient | null;\n}>;\n\nexport const AssistantProviderBase: FC<AssistantProviderBaseProps> = memo(\n ({ runtime, aui: parent = null, children }) => {\n const aui = useAui({ threads: RuntimeAdapter(runtime) }, { parent });\n const RenderComponent = getRenderComponent(runtime);\n return (\n <AuiProvider value={aui}>\n {RenderComponent && <RenderComponent />}\n {children}\n </AuiProvider>\n );\n },\n);\n"],"mappings":";;;;;AAWA,MAAa,sBAAsB,YAA8B;CAC/D,OAAQ,QAA6C,OAAO;AAG9D;AAOA,MAAa,wBAAwD,MAClE,EAAE,SAAS,KAAK,SAAS,MAAM,eAAe;CAC7C,MAAM,MAAM,OAAO,EAAE,SAAS,eAAe,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC;CACnE,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,OACE,qBAAC,aAAD;EAAa,OAAO;YAApB,CACG,mBAAmB,oBAAC,iBAAD,CAAkB,CAAA,GACrC,QACU;;AAEjB,CACF"}
1
+ {"version":3,"file":"AssistantProvider.js","names":[],"sources":["../../src/react/AssistantProvider.tsx"],"sourcesContent":["import {\n memo,\n type ComponentType,\n type FC,\n type PropsWithChildren,\n} from \"react\";\nimport { useAui, AuiProvider, type AssistantClient } from \"@assistant-ui/store\";\nimport type { AssistantRuntime } from \"../runtime/api/assistant-runtime\";\nimport type { AssistantRuntimeCore } from \"../runtime/interfaces/assistant-runtime-core\";\nimport { RuntimeAdapter } from \"./RuntimeAdapter\";\n\nexport const getRenderComponent = (runtime: AssistantRuntime) => {\n return (runtime as { _core?: AssistantRuntimeCore })._core\n ?.RenderComponent as ComponentType | undefined;\n};\n\nexport type AssistantProviderBaseProps = PropsWithChildren<{\n runtime: AssistantRuntime;\n aui?: AssistantClient | null;\n}>;\n\nexport const AssistantProviderBase: FC<AssistantProviderBaseProps> = memo(\n ({ runtime, aui: parent = null, children }) => {\n const aui = useAui({ threads: RuntimeAdapter(runtime) }, { parent });\n const RenderComponent = getRenderComponent(runtime);\n return (\n <AuiProvider value={aui}>\n {RenderComponent && <RenderComponent />}\n {children}\n </AuiProvider>\n );\n },\n);\n"],"mappings":";;;;;AAWA,MAAa,sBAAsB,YAA8B;CAC/D,OAAQ,QAA6C,OACjD;AACN;AAOA,MAAa,wBAAwD,MAClE,EAAE,SAAS,KAAK,SAAS,MAAM,eAAe;CAC7C,MAAM,MAAM,OAAO,EAAE,SAAS,eAAe,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC;CACnE,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,OACE,qBAAC,aAAD;EAAa,OAAO;YAApB,CACG,mBAAmB,oBAAC,iBAAD,CAAkB,CAAA,GACrC,QACU;;AAEjB,CACF"}
@@ -1,3 +1,4 @@
1
+ /// <reference path="../store/scope-registration.d.ts" />
1
2
  /// <reference path="./types/store-augmentation.d.ts" />
2
3
  import { AssistantContextConfig } from "../model-context/types.js";
3
4
  import { AssistantProviderBase, AssistantProviderBaseProps, getRenderComponent } from "./AssistantProvider.js";
@@ -37,7 +38,6 @@ import { SuggestionByIndexProvider, SuggestionByIndexProviderProps } from "./pro
37
38
  import { QueueItemByIndexProvider, QueueItemByIndexProviderProps } from "./providers/QueueItemByIndexProvider.js";
38
39
  import { ReadonlyThreadProvider } from "./providers/ReadonlyThreadProvider.js";
39
40
  import { RuntimeAdapterProvider, RuntimeAdapters, useRuntimeAdapters } from "./runtimes/RuntimeAdapterProvider.js";
40
- import { AddToolResultCommand, AssistantTransportState, ToolExecutionStatus, useToolInvocations } from "./runtimes/useToolInvocations.js";
41
41
  import { useExternalStoreRuntime } from "./runtimes/useExternalStoreRuntime.js";
42
42
  import { convertExternalMessages, useExternalMessageConverter } from "./runtimes/external-message-converter.js";
43
43
  import { createMessageConverter } from "./runtimes/createMessageConverter.js";
@@ -94,4 +94,4 @@ import { useEditComposerCancel } from "./primitive-hooks/useEditComposerCancel.j
94
94
  import { useEditComposerSend } from "./primitive-hooks/useEditComposerSend.js";
95
95
  import { useMessageError } from "./primitive-hooks/useMessageError.js";
96
96
  import { LocalRuntimeOptions, splitLocalRuntimeOptions, useLocalRuntime } from "./runtimes/useLocalRuntime.js";
97
- export { type AddToolResultCommand, type AssistantContextConfig, type AssistantDataUI, type AssistantDataUIProps, type AssistantInteractableProps, AssistantProviderBase, type AssistantProviderBaseProps, AssistantRuntimeProvider, type AssistantTool, type AssistantToolProps, type AssistantToolUI, type AssistantToolUIProps, type AssistantTransportState, type AsyncStorageLike, ChainOfThoughtByIndicesProvider, ChainOfThoughtPartByIndexProvider, ChainOfThoughtPrimitiveParts, CloudFileAttachmentAdapter, ComposerAttachmentByIndexProvider, ComposerPrimitiveAttachmentByIndex, ComposerPrimitiveAttachments, ComposerPrimitiveIf, ComposerPrimitiveQueue, type DataMessagePartComponent, type DataMessagePartProps, DataRenderers, type DataRenderersClientSchema, type DataRenderersMethods, type DataRenderersState, type EmptyMessagePartComponent, type EmptyMessagePartProps, type EnrichedPartState, type FileMessagePartComponent, type FileMessagePartProps, type GenerativeUIComponentRegistry, type GenerativeUIMessagePartComponent, type GenerativeUIMessagePartProps, GenerativeUIRender, GenerativeUIRenderError, type GenerativeUIRenderProps, type ImageMessagePartComponent, type ImageMessagePartProps, type InteractableDefinition, type InteractablePersistedState, type InteractablePersistenceAdapter, type InteractablePersistenceStatus, type InteractableRegistration, type InteractableStateSchema, Interactables, type InteractablesClientSchema, type InteractablesMethods, type InteractablesState, type LocalRuntimeOptions, type McpAppResourceOutput, MessageAttachmentByIndexProvider, MessageByIndexProvider, MessagePartComponent, MessagePartPrimitiveInProgress, MessagePrimitiveAttachmentByIndex, MessagePrimitiveAttachments, MessagePrimitiveGenerativeUI, MessagePrimitiveGroupedParts, MessagePrimitivePartByIndex, MessagePrimitiveParts, MessagePrimitiveQuote, PartByIndexProvider, PartPrimitiveMessages, PartPrimitiveMessagesImpl, type PartState, QueueItemByIndexProvider, type QueueItemByIndexProviderProps, type QuoteMessagePartComponent, type QuoteMessagePartProps, ReadonlyThreadProvider, type ReasoningGroupComponent, type ReasoningGroupProps, type ReasoningMessagePartComponent, type ReasoningMessagePartProps, RemoteThreadListHookInstanceManager, RemoteThreadListThreadListRuntimeCore, RuntimeAdapter, RuntimeAdapterProvider, type RuntimeAdapters, type SourceMessagePartComponent, type SourceMessagePartProps, SuggestionByIndexProvider, type SuggestionByIndexProviderProps, type TextMessagePartComponent, type TextMessagePartProps, TextMessagePartProvider, ThreadListItemByIndexProvider, ThreadListItemPrimitiveTitle, ThreadListItemRuntimeProvider, ThreadListPrimitiveItemByIndex, ThreadListPrimitiveItems, ThreadPrimitiveMessageByIndex, ThreadPrimitiveMessages, ThreadPrimitiveMessagesImpl, ThreadPrimitiveSuggestionByIndex, ThreadPrimitiveSuggestions, ThreadPrimitiveSuggestionsImpl, type TitleGenerationAdapter, type ToolArgsStatus, type ToolCallMessagePartComponent, type ToolCallMessagePartProps, type ToolDefinition, type ToolExecutionStatus, type Toolkit, Tools, type ToolsClientSchema, type ToolsMethods, type ToolsState, type Unstable_AudioMessagePartComponent, type Unstable_AudioMessagePartProps, type UseActionBarCopyOptions, type UseComposerIfProps, type UseSuggestionTriggerOptions, convertExternalMessages, createLocalStorageAdapter, createMessageConverter, createSimpleTitleAdapter, getMessageQuote, getRenderComponent, groupPartByType, makeAssistantDataUI, makeAssistantTool, makeAssistantToolUI, defaultComponents as messagePartsDefaultComponents, splitLocalRuntimeOptions, useActionBarCopy, useActionBarEdit, useActionBarFeedbackNegative, useActionBarFeedbackPositive, useActionBarReload, useActionBarSpeak, useActionBarStopSpeaking, useAssistantCloudThreadHistoryAdapter, useAssistantContext, useAssistantDataUI, useAssistantInstructions, useAssistantInteractable, useAssistantTool, useAssistantToolUI, useBranchPickerNext, useBranchPickerPrevious, useCloudThreadListAdapter, useComposerAddAttachment, useComposerCancel, useComposerDictate, useComposerSend, useEditComposerCancel, useEditComposerSend, useExternalMessageConverter, useExternalStoreRuntime, useInlineRender, useInteractableState, useLocalRuntime, useMessageBranching, useMessageError, useMessageReload, useRemoteThreadListRuntime, useRuntimeAdapters, useSuggestionTrigger, useThreadIsEmpty, useThreadIsRunning, useThreadListItemArchive, useThreadListItemDelete, useThreadListItemTrigger, useThreadListItemUnarchive, useThreadListLoadMore, useThreadListNew, useThreadMessages, useToolArgsStatus, useToolInvocations, useVoiceControls, useVoiceState, useVoiceVolume };
97
+ export { type AssistantContextConfig, type AssistantDataUI, type AssistantDataUIProps, type AssistantInteractableProps, AssistantProviderBase, type AssistantProviderBaseProps, AssistantRuntimeProvider, type AssistantTool, type AssistantToolProps, type AssistantToolUI, type AssistantToolUIProps, type AsyncStorageLike, ChainOfThoughtByIndicesProvider, ChainOfThoughtPartByIndexProvider, ChainOfThoughtPrimitiveParts, CloudFileAttachmentAdapter, ComposerAttachmentByIndexProvider, ComposerPrimitiveAttachmentByIndex, ComposerPrimitiveAttachments, ComposerPrimitiveIf, ComposerPrimitiveQueue, type DataMessagePartComponent, type DataMessagePartProps, DataRenderers, type DataRenderersClientSchema, type DataRenderersMethods, type DataRenderersState, type EmptyMessagePartComponent, type EmptyMessagePartProps, type EnrichedPartState, type FileMessagePartComponent, type FileMessagePartProps, type GenerativeUIComponentRegistry, type GenerativeUIMessagePartComponent, type GenerativeUIMessagePartProps, GenerativeUIRender, GenerativeUIRenderError, type GenerativeUIRenderProps, type ImageMessagePartComponent, type ImageMessagePartProps, type InteractableDefinition, type InteractablePersistedState, type InteractablePersistenceAdapter, type InteractablePersistenceStatus, type InteractableRegistration, type InteractableStateSchema, Interactables, type InteractablesClientSchema, type InteractablesMethods, type InteractablesState, type LocalRuntimeOptions, type McpAppResourceOutput, MessageAttachmentByIndexProvider, MessageByIndexProvider, MessagePartComponent, MessagePartPrimitiveInProgress, MessagePrimitiveAttachmentByIndex, MessagePrimitiveAttachments, MessagePrimitiveGenerativeUI, MessagePrimitiveGroupedParts, MessagePrimitivePartByIndex, MessagePrimitiveParts, MessagePrimitiveQuote, PartByIndexProvider, PartPrimitiveMessages, PartPrimitiveMessagesImpl, type PartState, QueueItemByIndexProvider, type QueueItemByIndexProviderProps, type QuoteMessagePartComponent, type QuoteMessagePartProps, ReadonlyThreadProvider, type ReasoningGroupComponent, type ReasoningGroupProps, type ReasoningMessagePartComponent, type ReasoningMessagePartProps, RemoteThreadListHookInstanceManager, RemoteThreadListThreadListRuntimeCore, RuntimeAdapter, RuntimeAdapterProvider, type RuntimeAdapters, type SourceMessagePartComponent, type SourceMessagePartProps, SuggestionByIndexProvider, type SuggestionByIndexProviderProps, type TextMessagePartComponent, type TextMessagePartProps, TextMessagePartProvider, ThreadListItemByIndexProvider, ThreadListItemPrimitiveTitle, ThreadListItemRuntimeProvider, ThreadListPrimitiveItemByIndex, ThreadListPrimitiveItems, ThreadPrimitiveMessageByIndex, ThreadPrimitiveMessages, ThreadPrimitiveMessagesImpl, ThreadPrimitiveSuggestionByIndex, ThreadPrimitiveSuggestions, ThreadPrimitiveSuggestionsImpl, type TitleGenerationAdapter, type ToolArgsStatus, type ToolCallMessagePartComponent, type ToolCallMessagePartProps, type ToolDefinition, type Toolkit, Tools, type ToolsClientSchema, type ToolsMethods, type ToolsState, type Unstable_AudioMessagePartComponent, type Unstable_AudioMessagePartProps, type UseActionBarCopyOptions, type UseComposerIfProps, type UseSuggestionTriggerOptions, convertExternalMessages, createLocalStorageAdapter, createMessageConverter, createSimpleTitleAdapter, getMessageQuote, getRenderComponent, groupPartByType, makeAssistantDataUI, makeAssistantTool, makeAssistantToolUI, defaultComponents as messagePartsDefaultComponents, splitLocalRuntimeOptions, useActionBarCopy, useActionBarEdit, useActionBarFeedbackNegative, useActionBarFeedbackPositive, useActionBarReload, useActionBarSpeak, useActionBarStopSpeaking, useAssistantCloudThreadHistoryAdapter, useAssistantContext, useAssistantDataUI, useAssistantInstructions, useAssistantInteractable, useAssistantTool, useAssistantToolUI, useBranchPickerNext, useBranchPickerPrevious, useCloudThreadListAdapter, useComposerAddAttachment, useComposerCancel, useComposerDictate, useComposerSend, useEditComposerCancel, useEditComposerSend, useExternalMessageConverter, useExternalStoreRuntime, useInlineRender, useInteractableState, useLocalRuntime, useMessageBranching, useMessageError, useMessageReload, useRemoteThreadListRuntime, useRuntimeAdapters, useSuggestionTrigger, useThreadIsEmpty, useThreadIsRunning, useThreadListItemArchive, useThreadListItemDelete, useThreadListItemTrigger, useThreadListItemUnarchive, useThreadListLoadMore, useThreadListNew, useThreadMessages, useToolArgsStatus, useVoiceControls, useVoiceState, useVoiceVolume };
@@ -28,7 +28,6 @@ import { SuggestionByIndexProvider } from "./providers/SuggestionByIndexProvider
28
28
  import { QueueItemByIndexProvider } from "./providers/QueueItemByIndexProvider.js";
29
29
  import { ReadonlyThreadProvider } from "./providers/ReadonlyThreadProvider.js";
30
30
  import { RuntimeAdapterProvider, useRuntimeAdapters } from "./runtimes/RuntimeAdapterProvider.js";
31
- import { useToolInvocations } from "./runtimes/useToolInvocations.js";
32
31
  import { useExternalStoreRuntime } from "./runtimes/useExternalStoreRuntime.js";
33
32
  import { convertExternalMessages, useExternalMessageConverter } from "./runtimes/external-message-converter.js";
34
33
  import { createMessageConverter } from "./runtimes/createMessageConverter.js";
@@ -86,4 +85,4 @@ import { useEditComposerCancel } from "./primitive-hooks/useEditComposerCancel.j
86
85
  import { useEditComposerSend } from "./primitive-hooks/useEditComposerSend.js";
87
86
  import { useMessageError } from "./primitive-hooks/useMessageError.js";
88
87
  import { splitLocalRuntimeOptions, useLocalRuntime } from "./runtimes/useLocalRuntime.js";
89
- export { AssistantProviderBase, AssistantRuntimeProvider, ChainOfThoughtByIndicesProvider, ChainOfThoughtPartByIndexProvider, ChainOfThoughtPrimitiveParts, CloudFileAttachmentAdapter, ComposerAttachmentByIndexProvider, ComposerPrimitiveAttachmentByIndex, ComposerPrimitiveAttachments, ComposerPrimitiveIf, ComposerPrimitiveQueue, DataRenderers, GenerativeUIRender, GenerativeUIRenderError, Interactables, MessageAttachmentByIndexProvider, MessageByIndexProvider, MessagePartComponent, MessagePartPrimitiveInProgress, MessagePrimitiveAttachmentByIndex, MessagePrimitiveAttachments, MessagePrimitiveGenerativeUI, MessagePrimitiveGroupedParts, MessagePrimitivePartByIndex, MessagePrimitiveParts, MessagePrimitiveQuote, PartByIndexProvider, PartPrimitiveMessages, PartPrimitiveMessagesImpl, QueueItemByIndexProvider, ReadonlyThreadProvider, RemoteThreadListHookInstanceManager, RemoteThreadListThreadListRuntimeCore, RuntimeAdapter, RuntimeAdapterProvider, SuggestionByIndexProvider, TextMessagePartProvider, ThreadListItemByIndexProvider, ThreadListItemPrimitiveTitle, ThreadListItemRuntimeProvider, ThreadListPrimitiveItemByIndex, ThreadListPrimitiveItems, ThreadPrimitiveMessageByIndex, ThreadPrimitiveMessages, ThreadPrimitiveMessagesImpl, ThreadPrimitiveSuggestionByIndex, ThreadPrimitiveSuggestions, ThreadPrimitiveSuggestionsImpl, Tools, convertExternalMessages, createLocalStorageAdapter, createMessageConverter, createSimpleTitleAdapter, getMessageQuote, getRenderComponent, groupPartByType, makeAssistantDataUI, makeAssistantTool, makeAssistantToolUI, defaultComponents as messagePartsDefaultComponents, splitLocalRuntimeOptions, useActionBarCopy, useActionBarEdit, useActionBarFeedbackNegative, useActionBarFeedbackPositive, useActionBarReload, useActionBarSpeak, useActionBarStopSpeaking, useAssistantCloudThreadHistoryAdapter, useAssistantContext, useAssistantDataUI, useAssistantInstructions, useAssistantInteractable, useAssistantTool, useAssistantToolUI, useBranchPickerNext, useBranchPickerPrevious, useCloudThreadListAdapter, useComposerAddAttachment, useComposerCancel, useComposerDictate, useComposerSend, useEditComposerCancel, useEditComposerSend, useExternalMessageConverter, useExternalStoreRuntime, useInlineRender, useInteractableState, useLocalRuntime, useMessageBranching, useMessageError, useMessageReload, useRemoteThreadListRuntime, useRuntimeAdapters, useSuggestionTrigger, useThreadIsEmpty, useThreadIsRunning, useThreadListItemArchive, useThreadListItemDelete, useThreadListItemTrigger, useThreadListItemUnarchive, useThreadListLoadMore, useThreadListNew, useThreadMessages, useToolArgsStatus, useToolInvocations, useVoiceControls, useVoiceState, useVoiceVolume };
88
+ export { AssistantProviderBase, AssistantRuntimeProvider, ChainOfThoughtByIndicesProvider, ChainOfThoughtPartByIndexProvider, ChainOfThoughtPrimitiveParts, CloudFileAttachmentAdapter, ComposerAttachmentByIndexProvider, ComposerPrimitiveAttachmentByIndex, ComposerPrimitiveAttachments, ComposerPrimitiveIf, ComposerPrimitiveQueue, DataRenderers, GenerativeUIRender, GenerativeUIRenderError, Interactables, MessageAttachmentByIndexProvider, MessageByIndexProvider, MessagePartComponent, MessagePartPrimitiveInProgress, MessagePrimitiveAttachmentByIndex, MessagePrimitiveAttachments, MessagePrimitiveGenerativeUI, MessagePrimitiveGroupedParts, MessagePrimitivePartByIndex, MessagePrimitiveParts, MessagePrimitiveQuote, PartByIndexProvider, PartPrimitiveMessages, PartPrimitiveMessagesImpl, QueueItemByIndexProvider, ReadonlyThreadProvider, RemoteThreadListHookInstanceManager, RemoteThreadListThreadListRuntimeCore, RuntimeAdapter, RuntimeAdapterProvider, SuggestionByIndexProvider, TextMessagePartProvider, ThreadListItemByIndexProvider, ThreadListItemPrimitiveTitle, ThreadListItemRuntimeProvider, ThreadListPrimitiveItemByIndex, ThreadListPrimitiveItems, ThreadPrimitiveMessageByIndex, ThreadPrimitiveMessages, ThreadPrimitiveMessagesImpl, ThreadPrimitiveSuggestionByIndex, ThreadPrimitiveSuggestions, ThreadPrimitiveSuggestionsImpl, Tools, convertExternalMessages, createLocalStorageAdapter, createMessageConverter, createSimpleTitleAdapter, getMessageQuote, getRenderComponent, groupPartByType, makeAssistantDataUI, makeAssistantTool, makeAssistantToolUI, defaultComponents as messagePartsDefaultComponents, splitLocalRuntimeOptions, useActionBarCopy, useActionBarEdit, useActionBarFeedbackNegative, useActionBarFeedbackPositive, useActionBarReload, useActionBarSpeak, useActionBarStopSpeaking, useAssistantCloudThreadHistoryAdapter, useAssistantContext, useAssistantDataUI, useAssistantInstructions, useAssistantInteractable, useAssistantTool, useAssistantToolUI, useBranchPickerNext, useBranchPickerPrevious, useCloudThreadListAdapter, useComposerAddAttachment, useComposerCancel, useComposerDictate, useComposerSend, useEditComposerCancel, useEditComposerSend, useExternalMessageConverter, useExternalStoreRuntime, useInlineRender, useInteractableState, useLocalRuntime, useMessageBranching, useMessageError, useMessageReload, useRemoteThreadListRuntime, useRuntimeAdapters, useSuggestionTrigger, useThreadIsEmpty, useThreadIsRunning, useThreadListItemArchive, useThreadListItemDelete, useThreadListItemTrigger, useThreadListItemUnarchive, useThreadListLoadMore, useThreadListNew, useThreadMessages, useToolArgsStatus, useVoiceControls, useVoiceState, useVoiceVolume };
@@ -1 +1 @@
1
- {"version":3,"file":"ChainOfThoughtParts.js","names":[],"sources":["../../../../src/react/primitives/chainOfThought/ChainOfThoughtParts.tsx"],"sourcesContent":["import {\n type ComponentType,\n type FC,\n type PropsWithChildren,\n type ReactNode,\n useMemo,\n} from \"react\";\nimport { RenderChildrenWithAccessor, useAuiState } from \"@assistant-ui/store\";\nimport type { PartState } from \"../../../store/scopes/part\";\nimport { ChainOfThoughtPartByIndexProvider } from \"../../providers/ChainOfThoughtPartByIndexProvider\";\nimport { MessagePartComponent } from \"../message/MessageParts\";\nimport type {\n ReasoningMessagePartComponent,\n ToolCallMessagePartComponent,\n} from \"../../types/MessagePartComponentTypes\";\n\ntype ChainOfThoughtPartsComponentConfig = {\n /** Component for rendering reasoning parts */\n Reasoning?: ReasoningMessagePartComponent | undefined;\n /** Fallback component for tool-call parts */\n tools?: {\n Fallback?: ToolCallMessagePartComponent | undefined;\n };\n /** Layout component to wrap the rendered parts when expanded */\n Layout?: ComponentType<PropsWithChildren> | undefined;\n};\n\nexport namespace ChainOfThoughtPrimitiveParts {\n export type Props =\n | {\n /**\n * @deprecated Use the children render function instead.\n */\n components?: ChainOfThoughtPartsComponentConfig;\n children?: never;\n }\n | {\n /** Render function called for each part. Receives the part. */\n children: (value: { part: PartState }) => ReactNode;\n components?: never;\n };\n}\n\nconst ChainOfThoughtPrimitivePartsInner: FC<{\n children: (value: { part: PartState }) => ReactNode;\n}> = ({ children }) => {\n const partsLength = useAuiState((s) => s.chainOfThought.parts.length);\n\n return useMemo(\n () =>\n Array.from({ length: partsLength }, (_, index) => (\n <ChainOfThoughtPartByIndexProvider key={index} index={index}>\n <RenderChildrenWithAccessor\n getItemState={(aui) =>\n aui.chainOfThought().part({ index }).getState()\n }\n >\n {(getItem) =>\n children({\n get part() {\n return getItem();\n },\n })\n }\n </RenderChildrenWithAccessor>\n </ChainOfThoughtPartByIndexProvider>\n )),\n [partsLength, children],\n );\n};\n\n/**\n * Renders the parts within a chain of thought, with support for collapsed/expanded states.\n *\n * When collapsed, no parts are shown. When expanded, all parts are rendered\n * using the provided component configuration through the part scope mechanism.\n */\nexport const ChainOfThoughtPrimitiveParts: FC<\n ChainOfThoughtPrimitiveParts.Props\n> = ({ components, children }) => {\n if (children) {\n return (\n <ChainOfThoughtPrimitivePartsInner>\n {children}\n </ChainOfThoughtPrimitivePartsInner>\n );\n }\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n // biome-ignore lint/correctness/useHookAtTopLevel: intentional conditional/nested hook usage\n const messageComponents = useMemo(\n () => ({\n Reasoning: components?.Reasoning,\n tools: {\n Fallback: components?.tools?.Fallback,\n },\n }),\n [components?.Reasoning, components?.tools?.Fallback],\n );\n\n const Layout = components?.Layout;\n\n return (\n <ChainOfThoughtPrimitivePartsInner>\n {() =>\n Layout ? (\n <Layout>\n <MessagePartComponent components={messageComponents} />\n </Layout>\n ) : (\n <MessagePartComponent components={messageComponents} />\n )\n }\n </ChainOfThoughtPrimitivePartsInner>\n );\n};\n\nChainOfThoughtPrimitiveParts.displayName = \"ChainOfThoughtPrimitive.Parts\";\n"],"mappings":";;;;;;AA2CA,MAAM,qCAEA,EAAE,eAAe;CACrB,MAAM,cAAc,aAAa,MAAM,EAAE,eAAe,MAAM,MAAM;CAEpE,OAAO,cAEH,MAAM,KAAK,EAAE,QAAQ,YAAY,IAAI,GAAG,UACtC,oBAAC,mCAAD;EAAsD;YACpD,oBAAC,4BAAD;GACE,eAAe,QACb,IAAI,eAAe,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,SAAS;cAG9C,YACA,SAAS,EACP,IAAI,OAAO;IACT,OAAO,QAAQ;GACjB,EACF,CAAC;EAEuB,CAAA;CACK,GAdK,KAcL,CACpC,GACH,CAAC,aAAa,QAAQ,CACxB;AACF;;;;;;;AAQA,MAAa,gCAER,EAAE,YAAY,eAAe;CAChC,IAAI,UACF,OACE,oBAAC,mCAAD,EACG,SACgC,CAAA;CAMvC,MAAM,oBAAoB,eACjB;EACL,WAAW,YAAY;EACvB,OAAO,EACL,UAAU,YAAY,OAAO,SAC/B;CACF,IACA,CAAC,YAAY,WAAW,YAAY,OAAO,QAAQ,CACrD;CAEA,MAAM,SAAS,YAAY;CAE3B,OACE,oBAAC,mCAAD,EAAA,gBAEI,SACE,oBAAC,QAAD,EAAA,UACE,oBAAC,sBAAD,EAAsB,YAAY,kBAAoB,CAAA,EAChD,CAAA,IAER,oBAAC,sBAAD,EAAsB,YAAY,kBAAoB,CAAA,EAGzB,CAAA;AAEvC;AAEA,6BAA6B,cAAc"}
1
+ {"version":3,"file":"ChainOfThoughtParts.js","names":[],"sources":["../../../../src/react/primitives/chainOfThought/ChainOfThoughtParts.tsx"],"sourcesContent":["import {\n type ComponentType,\n type FC,\n type PropsWithChildren,\n type ReactNode,\n useMemo,\n} from \"react\";\nimport { RenderChildrenWithAccessor, useAuiState } from \"@assistant-ui/store\";\nimport type { PartState } from \"../../../store/scopes/part\";\nimport { ChainOfThoughtPartByIndexProvider } from \"../../providers/ChainOfThoughtPartByIndexProvider\";\nimport { MessagePartComponent } from \"../message/MessageParts\";\nimport type {\n ReasoningMessagePartComponent,\n ToolCallMessagePartComponent,\n} from \"../../types/MessagePartComponentTypes\";\n\ntype ChainOfThoughtPartsComponentConfig = {\n /** Component for rendering reasoning parts */\n Reasoning?: ReasoningMessagePartComponent | undefined;\n /** Fallback component for tool-call parts */\n tools?: {\n Fallback?: ToolCallMessagePartComponent | undefined;\n };\n /** Layout component to wrap the rendered parts when expanded */\n Layout?: ComponentType<PropsWithChildren> | undefined;\n};\n\nexport namespace ChainOfThoughtPrimitiveParts {\n export type Props =\n | {\n /**\n * @deprecated Use the children render function instead.\n */\n components?: ChainOfThoughtPartsComponentConfig;\n children?: never;\n }\n | {\n /** Render function called for each part. Receives the part. */\n children: (value: { part: PartState }) => ReactNode;\n components?: never;\n };\n}\n\nconst ChainOfThoughtPrimitivePartsInner: FC<{\n children: (value: { part: PartState }) => ReactNode;\n}> = ({ children }) => {\n const partsLength = useAuiState((s) => s.chainOfThought.parts.length);\n\n return useMemo(\n () =>\n Array.from({ length: partsLength }, (_, index) => (\n <ChainOfThoughtPartByIndexProvider key={index} index={index}>\n <RenderChildrenWithAccessor\n getItemState={(aui) =>\n aui.chainOfThought().part({ index }).getState()\n }\n >\n {(getItem) =>\n children({\n get part() {\n return getItem();\n },\n })\n }\n </RenderChildrenWithAccessor>\n </ChainOfThoughtPartByIndexProvider>\n )),\n [partsLength, children],\n );\n};\n\n/**\n * Renders the parts within a chain of thought, with support for collapsed/expanded states.\n *\n * When collapsed, no parts are shown. When expanded, all parts are rendered\n * using the provided component configuration through the part scope mechanism.\n */\nexport const ChainOfThoughtPrimitiveParts: FC<\n ChainOfThoughtPrimitiveParts.Props\n> = ({ components, children }) => {\n if (children) {\n return (\n <ChainOfThoughtPrimitivePartsInner>\n {children}\n </ChainOfThoughtPrimitivePartsInner>\n );\n }\n\n // oxlint-disable-next-line react-hooks/rules-of-hooks -- intentional conditional hook below the early return above\n const messageComponents = useMemo(\n () => ({\n Reasoning: components?.Reasoning,\n tools: {\n Fallback: components?.tools?.Fallback,\n },\n }),\n [components?.Reasoning, components?.tools?.Fallback],\n );\n\n const Layout = components?.Layout;\n\n return (\n <ChainOfThoughtPrimitivePartsInner>\n {() =>\n Layout ? (\n <Layout>\n <MessagePartComponent components={messageComponents} />\n </Layout>\n ) : (\n <MessagePartComponent components={messageComponents} />\n )\n }\n </ChainOfThoughtPrimitivePartsInner>\n );\n};\n\nChainOfThoughtPrimitiveParts.displayName = \"ChainOfThoughtPrimitive.Parts\";\n"],"mappings":";;;;;;AA2CA,MAAM,qCAEA,EAAE,eAAe;CACrB,MAAM,cAAc,aAAa,MAAM,EAAE,eAAe,MAAM,MAAM;CAEpE,OAAO,cAEH,MAAM,KAAK,EAAE,QAAQ,YAAY,IAAI,GAAG,UACtC,oBAAC,mCAAD;EAAsD;YACpD,oBAAC,4BAAD;GACE,eAAe,QACb,IAAI,eAAe,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,SAAS;cAG9C,YACA,SAAS,EACP,IAAI,OAAO;IACT,OAAO,QAAQ;GACjB,EACF,CAAC;EAEuB,CAAA;CACK,GAdK,KAcL,CACpC,GACH,CAAC,aAAa,QAAQ,CACxB;AACF;;;;;;;AAQA,MAAa,gCAER,EAAE,YAAY,eAAe;CAChC,IAAI,UACF,OACE,oBAAC,mCAAD,EACG,SACgC,CAAA;CAKvC,MAAM,oBAAoB,eACjB;EACL,WAAW,YAAY;EACvB,OAAO,EACL,UAAU,YAAY,OAAO,SAC/B;CACF,IACA,CAAC,YAAY,WAAW,YAAY,OAAO,QAAQ,CACrD;CAEA,MAAM,SAAS,YAAY;CAE3B,OACE,oBAAC,mCAAD,EAAA,gBAEI,SACE,oBAAC,QAAD,EAAA,UACE,oBAAC,sBAAD,EAAsB,YAAY,kBAAoB,CAAA,EAChD,CAAA,IAER,oBAAC,sBAAD,EAAsB,YAAY,kBAAoB,CAAA,EAGzB,CAAA;AAEvC;AAEA,6BAA6B,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"MessageGroupedParts.js","names":[],"sources":["../../../../src/react/primitives/message/MessageGroupedParts.tsx"],"sourcesContent":["\"use client\";\n\nimport { Fragment, type FC, type ReactNode, useMemo } from \"react\";\nimport { useAuiState } from \"@assistant-ui/store\";\nimport { useShallow } from \"zustand/shallow\";\nimport type { PartState } from \"../../../store/scopes/part\";\nimport type {\n MessagePartStatus,\n ToolCallMessagePartStatus,\n} from \"../../../types/message\";\nimport {\n buildGroupTree,\n GROUPBY_MEMO_KEY,\n type GroupNode,\n} from \"../../utils/groupParts\";\nimport { MessagePartChildren, type EnrichedPartState } from \"./MessageParts\";\n\nexport namespace MessagePrimitiveGroupedParts {\n /**\n * A coalesced group of adjacent parts. Surfaced through the same\n * `{ part }` channel as a leaf {@link EnrichedPartState} so consumers\n * dispatch on a single `switch (part.type)`. `type` is the group key\n * (always `\"group-…\"`); `status` mirrors the last contained part.\n */\n export type GroupPart<TKey extends `group-${string}` = `group-${string}`> = {\n readonly type: TKey;\n readonly status: MessagePartStatus | ToolCallMessagePartStatus;\n readonly indices: readonly number[];\n };\n\n export type RenderInfo<TKey extends `group-${string}` = `group-${string}`> = {\n /**\n * Either a coalesced group ({@link GroupPart}, identified by a\n * `group-…` `type`) or a single enriched part. Use one switch over\n * `part.type` to handle both.\n */\n readonly part: GroupPart<TKey> | EnrichedPartState;\n /**\n * For group nodes: the recursively-rendered subtree (subgroups +\n * leaf parts). For leaf parts: a sentinel that throws when rendered\n * — accidental fall-through (`default: return children;`) errors\n * loudly instead of silently rendering nothing.\n */\n readonly children: ReactNode;\n };\n\n export type Props<TKey extends `group-${string}` = `group-${string}`> = {\n /**\n * Maps each part to a group-key path. Adjacent parts that share a\n * prefix coalesce into the same group. Return `[]` (or `null`) to\n * leave a part ungrouped.\n *\n * Group keys must start with `\"group-\"` so the renderer's\n * `switch (part.type)` can tell groups apart from real part types.\n *\n * **Prefer {@link groupPartByType}** for the common case of mapping by\n * `part.type` — it ships a stable memo fingerprint so the tree\n * survives unrelated re-renders. Use an inline function only when\n * the helper isn't expressive enough (e.g. branching on\n * `part.toolName` or part metadata).\n *\n * @example\n * ```tsx\n * import { groupPartByType } from \"@assistant-ui/react\";\n *\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * })}\n * >\n * ```\n */\n readonly groupBy: (part: PartState) => readonly TKey[] | null;\n\n /**\n * Render function called once per group node and once per leaf part.\n * Switch on `part.type`: `\"group-…\"` cases wrap `children`; real\n * part types (`\"text\"`, `\"tool-call\"`, …) render the part directly.\n *\n * Leaf parts receive the same {@link EnrichedPartState} that\n * `<MessagePrimitive.Parts>` would produce (`toolUI`, `addResult`,\n * `resume`, `respondToApproval`, `dataRendererUI`).\n */\n readonly children: (info: RenderInfo<TKey>) => ReactNode;\n };\n}\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({ type: \"complete\" });\n\n/**\n * `children` placeholder passed for leaf-part renders. Leaf parts have no\n * inner subtree; rendering this sentinel signals the consumer wrote\n * `default: return children;` and accidentally fell through for a part —\n * surface the bug loudly instead of silently rendering nothing.\n */\nconst PartChildrenSentinel: FC = () => {\n throw new Error(\n \"MessagePrimitive.GroupedParts: rendered `children` under a leaf \" +\n \"part. `children` is only meaningful for `group-…` cases — add a \" +\n \"matching case for the part type or return `null` to skip it.\",\n );\n};\n\nconst renderNode = <TKey extends `group-${string}`>(\n node: GroupNode,\n parts: readonly PartState[],\n render: (info: MessagePrimitiveGroupedParts.RenderInfo<TKey>) => ReactNode,\n): ReactNode => {\n if (node.type === \"part\") {\n // Key by absolute part index, not structural nodeKey — prevents zombie fiber subscriptions when parts reshape (#4051).\n return (\n <MessagePartChildren key={`part-${node.index}`} index={node.index}>\n {({ part }) => render({ part, children: <PartChildrenSentinel /> })}\n </MessagePartChildren>\n );\n }\n\n const status = parts[node.indices.at(-1)!]?.status ?? COMPLETE_STATUS;\n const groupPart: MessagePrimitiveGroupedParts.GroupPart<TKey> = {\n type: node.key as TKey,\n status,\n indices: node.indices,\n };\n\n return (\n <Fragment key={node.nodeKey}>\n {render({\n part: groupPart,\n children: (\n <>{node.children.map((child) => renderNode(child, parts, render))}</>\n ),\n })}\n </Fragment>\n );\n};\n\n/**\n * Groups adjacent message parts into a tree of coalesced runs and\n * renders each node — group or part — through a single `children`\n * function.\n *\n * The render function receives `{ part, children }` where `part.type`\n * is either a `\"group-…\"` literal (for a group, `children` is the\n * recursively-rendered subtree) or a real part type (`\"text\"`,\n * `\"tool-call\"`, …) for a leaf (`children` is a sentinel that throws\n * if rendered — use `part.type` to distinguish).\n *\n * @example\n * ```tsx\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * })}\n * >\n * {({ part, children }) => {\n * switch (part.type) {\n * case \"group-thought\": return <Thought>{children}</Thought>;\n * case \"group-reasoning\": return <Reasoning>{children}</Reasoning>;\n * case \"group-tool\": return <ToolStack>{children}</ToolStack>;\n * case \"text\": return <MarkdownText />;\n * case \"tool-call\": return part.toolUI ?? <ToolFallback {...part} />;\n * default: return null;\n * }\n * }}\n * </MessagePrimitive.GroupedParts>\n * ```\n */\nexport const MessagePrimitiveGroupedParts = <TKey extends `group-${string}`>({\n groupBy,\n children,\n}: MessagePrimitiveGroupedParts.Props<TKey>): ReactNode => {\n const parts = useAuiState(useShallow((s) => s.message.parts));\n\n // Helpers like `groupPartByType` tag the function with `GROUPBY_MEMO_KEY`\n // (a stable string fingerprint of the helper config). When present,\n // memo on `[parts, memoKey]` so the tree survives unrelated renders.\n // For inline `groupBy`, fall back to recomputing each render — O(n)\n // and cheap.\n const memoKey = (groupBy as { [GROUPBY_MEMO_KEY]?: string })[\n GROUPBY_MEMO_KEY\n ];\n const memoDep = memoKey ?? groupBy;\n // biome-ignore lint/correctness/useExhaustiveDependencies: groupBy is captured via memoDep either as its identity (no memoKey) or as the helper's memoKey fingerprint. Listing groupBy directly would defeat the helper-tagged memo path.\n const tree = useMemo(\n () => buildGroupTree(parts.map((part) => groupBy(part) ?? [])),\n [parts, memoDep],\n );\n\n return <>{tree.map((node) => renderNode(node, parts, children))}</>;\n};\n\nMessagePrimitiveGroupedParts.displayName = \"MessagePrimitive.GroupedParts\";\n"],"mappings":";;;;;;;;AAwFA,MAAM,kBAAqC,OAAO,OAAO,EAAE,MAAM,WAAW,CAAC;;;;;;;AAQ7E,MAAM,6BAAiC;CACrC,MAAM,IAAI,MACR,8LAGF;AACF;AAEA,MAAM,cACJ,MACA,OACA,WACc;CACd,IAAI,KAAK,SAAS,QAEhB,OACE,oBAAC,qBAAD;EAAgD,OAAO,KAAK;aACxD,EAAE,WAAW,OAAO;GAAE;GAAM,UAAU,oBAAC,sBAAD,CAAuB,CAAA;EAAE,CAAC;CAC/C,GAFK,QAAQ,KAAK,OAElB;CAIzB,MAAM,SAAS,MAAM,KAAK,QAAQ,GAAG,EAAE,IAAK,UAAU;CAOtD,OACE,oBAAC,UAAD,EAAA,UACG,OAAO;EACN,MAAM;GARV,MAAM,KAAK;GACX;GACA,SAAS,KAAK;EAMI;EACd,UACE,oBAAA,YAAA,EAAA,UAAG,KAAK,SAAS,KAAK,UAAU,WAAW,OAAO,OAAO,MAAM,CAAC,EAAI,CAAA;CAExE,CAAC,EACO,GAPK,KAAK,OAOV;AAEd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,gCAAgE,EAC3E,SACA,eACyD;CACzD,MAAM,QAAQ,YAAY,YAAY,MAAM,EAAE,QAAQ,KAAK,CAAC;CAiB5D,OAAO,oBAAA,YAAA,EAAA,UALM,cACL,eAAe,MAAM,KAAK,SAAS,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,GAC7D,CAAC,OAPc,QACf,qBAEyB,OAIV,CAGJ,EAAE,KAAK,SAAS,WAAW,MAAM,OAAO,QAAQ,CAAC,EAAI,CAAA;AACpE;AAEA,6BAA6B,cAAc"}
1
+ {"version":3,"file":"MessageGroupedParts.js","names":[],"sources":["../../../../src/react/primitives/message/MessageGroupedParts.tsx"],"sourcesContent":["\"use client\";\n\nimport { Fragment, type FC, type ReactNode, useMemo } from \"react\";\nimport { useAuiState } from \"@assistant-ui/store\";\nimport { useShallow } from \"zustand/shallow\";\nimport type { PartState } from \"../../../store/scopes/part\";\nimport type {\n MessagePartStatus,\n ToolCallMessagePartStatus,\n} from \"../../../types/message\";\nimport {\n buildGroupTree,\n GROUPBY_MEMO_KEY,\n type GroupNode,\n} from \"../../utils/groupParts\";\nimport { MessagePartChildren, type EnrichedPartState } from \"./MessageParts\";\n\nexport namespace MessagePrimitiveGroupedParts {\n /**\n * A coalesced group of adjacent parts. Surfaced through the same\n * `{ part }` channel as a leaf {@link EnrichedPartState} so consumers\n * dispatch on a single `switch (part.type)`. `type` is the group key\n * (always `\"group-…\"`); `status` mirrors the last contained part.\n */\n export type GroupPart<TKey extends `group-${string}` = `group-${string}`> = {\n readonly type: TKey;\n readonly status: MessagePartStatus | ToolCallMessagePartStatus;\n readonly indices: readonly number[];\n };\n\n export type RenderInfo<TKey extends `group-${string}` = `group-${string}`> = {\n /**\n * Either a coalesced group ({@link GroupPart}, identified by a\n * `group-…` `type`) or a single enriched part. Use one switch over\n * `part.type` to handle both.\n */\n readonly part: GroupPart<TKey> | EnrichedPartState;\n /**\n * For group nodes: the recursively-rendered subtree (subgroups +\n * leaf parts). For leaf parts: a sentinel that throws when rendered\n * — accidental fall-through (`default: return children;`) errors\n * loudly instead of silently rendering nothing.\n */\n readonly children: ReactNode;\n };\n\n export type Props<TKey extends `group-${string}` = `group-${string}`> = {\n /**\n * Maps each part to a group-key path. Adjacent parts that share a\n * prefix coalesce into the same group. Return `[]` (or `null`) to\n * leave a part ungrouped.\n *\n * Group keys must start with `\"group-\"` so the renderer's\n * `switch (part.type)` can tell groups apart from real part types.\n *\n * **Prefer {@link groupPartByType}** for the common case of mapping by\n * `part.type` — it ships a stable memo fingerprint so the tree\n * survives unrelated re-renders. Use an inline function only when\n * the helper isn't expressive enough (e.g. branching on\n * `part.toolName` or part metadata).\n *\n * @example\n * ```tsx\n * import { groupPartByType } from \"@assistant-ui/react\";\n *\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * })}\n * >\n * ```\n */\n readonly groupBy: (part: PartState) => readonly TKey[] | null;\n\n /**\n * Render function called once per group node and once per leaf part.\n * Switch on `part.type`: `\"group-…\"` cases wrap `children`; real\n * part types (`\"text\"`, `\"tool-call\"`, …) render the part directly.\n *\n * Leaf parts receive the same {@link EnrichedPartState} that\n * `<MessagePrimitive.Parts>` would produce (`toolUI`, `addResult`,\n * `resume`, `respondToApproval`, `dataRendererUI`).\n */\n readonly children: (info: RenderInfo<TKey>) => ReactNode;\n };\n}\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({ type: \"complete\" });\n\n/**\n * `children` placeholder passed for leaf-part renders. Leaf parts have no\n * inner subtree; rendering this sentinel signals the consumer wrote\n * `default: return children;` and accidentally fell through for a part —\n * surface the bug loudly instead of silently rendering nothing.\n */\nconst PartChildrenSentinel: FC = () => {\n throw new Error(\n \"MessagePrimitive.GroupedParts: rendered `children` under a leaf \" +\n \"part. `children` is only meaningful for `group-…` cases — add a \" +\n \"matching case for the part type or return `null` to skip it.\",\n );\n};\n\nconst renderNode = <TKey extends `group-${string}`>(\n node: GroupNode,\n parts: readonly PartState[],\n render: (info: MessagePrimitiveGroupedParts.RenderInfo<TKey>) => ReactNode,\n): ReactNode => {\n if (node.type === \"part\") {\n // Key by absolute part index, not structural nodeKey — prevents zombie fiber subscriptions when parts reshape (#4051).\n return (\n <MessagePartChildren key={`part-${node.index}`} index={node.index}>\n {({ part }) => render({ part, children: <PartChildrenSentinel /> })}\n </MessagePartChildren>\n );\n }\n\n const status = parts[node.indices.at(-1)!]?.status ?? COMPLETE_STATUS;\n const groupPart: MessagePrimitiveGroupedParts.GroupPart<TKey> = {\n type: node.key as TKey,\n status,\n indices: node.indices,\n };\n\n return (\n <Fragment key={node.nodeKey}>\n {render({\n part: groupPart,\n children: (\n <>{node.children.map((child) => renderNode(child, parts, render))}</>\n ),\n })}\n </Fragment>\n );\n};\n\n/**\n * Groups adjacent message parts into a tree of coalesced runs and\n * renders each node — group or part — through a single `children`\n * function.\n *\n * The render function receives `{ part, children }` where `part.type`\n * is either a `\"group-…\"` literal (for a group, `children` is the\n * recursively-rendered subtree) or a real part type (`\"text\"`,\n * `\"tool-call\"`, …) for a leaf (`children` is a sentinel that throws\n * if rendered — use `part.type` to distinguish).\n *\n * @example\n * ```tsx\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * })}\n * >\n * {({ part, children }) => {\n * switch (part.type) {\n * case \"group-thought\": return <Thought>{children}</Thought>;\n * case \"group-reasoning\": return <Reasoning>{children}</Reasoning>;\n * case \"group-tool\": return <ToolStack>{children}</ToolStack>;\n * case \"text\": return <MarkdownText />;\n * case \"tool-call\": return part.toolUI ?? <ToolFallback {...part} />;\n * default: return null;\n * }\n * }}\n * </MessagePrimitive.GroupedParts>\n * ```\n */\nexport const MessagePrimitiveGroupedParts = <TKey extends `group-${string}`>({\n groupBy,\n children,\n}: MessagePrimitiveGroupedParts.Props<TKey>): ReactNode => {\n const parts = useAuiState(useShallow((s) => s.message.parts));\n\n // Helpers like `groupPartByType` tag the function with `GROUPBY_MEMO_KEY`\n // (a stable string fingerprint of the helper config). When present,\n // memo on `[parts, memoKey]` so the tree survives unrelated renders.\n // For inline `groupBy`, fall back to recomputing each render — O(n)\n // and cheap.\n const memoKey = (groupBy as { [GROUPBY_MEMO_KEY]?: string })[\n GROUPBY_MEMO_KEY\n ];\n const memoDep = memoKey ?? groupBy;\n const tree = useMemo(\n () => buildGroupTree(parts.map((part) => groupBy(part) ?? [])),\n // oxlint-disable-next-line tap-hooks/exhaustive-deps -- groupBy is captured via memoDep (either its identity or the helper's memoKey fingerprint); listing it directly would defeat the helper-tagged memo path\n [parts, memoDep],\n );\n\n return <>{tree.map((node) => renderNode(node, parts, children))}</>;\n};\n\nMessagePrimitiveGroupedParts.displayName = \"MessagePrimitive.GroupedParts\";\n"],"mappings":";;;;;;;;AAwFA,MAAM,kBAAqC,OAAO,OAAO,EAAE,MAAM,WAAW,CAAC;;;;;;;AAQ7E,MAAM,6BAAiC;CACrC,MAAM,IAAI,MACR,8LAGF;AACF;AAEA,MAAM,cACJ,MACA,OACA,WACc;CACd,IAAI,KAAK,SAAS,QAEhB,OACE,oBAAC,qBAAD;EAAgD,OAAO,KAAK;aACxD,EAAE,WAAW,OAAO;GAAE;GAAM,UAAU,oBAAC,sBAAD,CAAuB,CAAA;EAAE,CAAC;CAC/C,GAFK,QAAQ,KAAK,OAElB;CAIzB,MAAM,SAAS,MAAM,KAAK,QAAQ,GAAG,EAAE,IAAK,UAAU;CAOtD,OACE,oBAAC,UAAD,EAAA,UACG,OAAO;EACN,MAAM;GARV,MAAM,KAAK;GACX;GACA,SAAS,KAAK;EAMI;EACd,UACE,oBAAA,YAAA,EAAA,UAAG,KAAK,SAAS,KAAK,UAAU,WAAW,OAAO,OAAO,MAAM,CAAC,EAAI,CAAA;CAExE,CAAC,EACO,GAPK,KAAK,OAOV;AAEd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,gCAAgE,EAC3E,SACA,eACyD;CACzD,MAAM,QAAQ,YAAY,YAAY,MAAM,EAAE,QAAQ,KAAK,CAAC;CAiB5D,OAAO,oBAAA,YAAA,EAAA,UANM,cACL,eAAe,MAAM,KAAK,SAAS,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,GAE7D,CAAC,OAPc,QACf,qBAEyB,OAIV,CAGJ,EAAE,KAAK,SAAS,WAAW,MAAM,OAAO,QAAQ,CAAC,EAAI,CAAA;AACpE;AAEA,6BAA6B,cAAc"}
@@ -1,6 +1,6 @@
1
1
  import { MessageTiming, ThreadMessage } from "../../types/message.js";
2
2
  import { ThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
3
- import { ToolExecutionStatus } from "./useToolInvocations.js";
3
+ import { ToolExecutionStatus } from "../../runtimes/tool-invocations/ToolInvocationTracker.js";
4
4
  import { ReadonlyJSONValue } from "assistant-stream/utils";
5
5
 
6
6
  //#region src/react/runtimes/external-message-converter.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"external-message-converter.js","names":["unsupportedRole"],"sources":["../../../src/react/runtimes/external-message-converter.ts"],"sourcesContent":["\"use client\";\n\nimport { useMemo } from \"react\";\nimport { ThreadMessageConverter } from \"../../runtimes/external-store/thread-message-converter\";\nimport {\n getExternalStoreMessages,\n symbolInnerMessage,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport type { ToolExecutionStatus } from \"./useToolInvocations\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { generateErrorMessageId } from \"../../utils/id\";\nimport type {\n ThreadAssistantMessage,\n ThreadMessage,\n ToolCallMessagePart,\n} from \"../../types/message\";\nimport type { MessageTiming } from \"../../types/message\";\n\ntype ThreadMessageLikeContentItem = Exclude<\n ThreadMessageLike[\"content\"],\n string\n>[number];\n\nconst isPendingToolCall = (c: ThreadMessageLikeContentItem): boolean =>\n c.type === \"tool-call\" && c.result === undefined;\n\nconst isInterruptedToolCall = (c: ThreadMessageLikeContentItem): boolean => {\n if (c.type !== \"tool-call\" || c.result !== undefined) return false;\n return (\n c.interrupt != null ||\n (c.approval != null && c.approval.approved === undefined)\n );\n};\n\nexport namespace useExternalMessageConverter {\n export type Message =\n | (ThreadMessageLike & {\n readonly convertConfig?: {\n readonly joinStrategy?: \"concat-content\" | \"none\";\n };\n })\n | {\n role: \"tool\";\n toolCallId: string;\n toolName?: string | undefined;\n result: any;\n artifact?: any;\n isError?: boolean;\n messages?: readonly ThreadMessage[];\n };\n\n export type Metadata = {\n readonly toolStatuses?: Record<string, ToolExecutionStatus>;\n readonly error?: ReadonlyJSONValue;\n readonly messageTiming?: Record<string, MessageTiming>;\n };\n\n export type Callback<T> = (\n message: T,\n metadata: Metadata,\n ) => Message | Message[];\n}\n\ntype CallbackResult<T> = {\n input: T;\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype ChunkResult<T> = {\n inputs: T[];\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\nconst mergeInnerMessages = (existing: object, incoming: object) => ({\n [symbolInnerMessage]: [\n ...((existing as any)[symbolInnerMessage] ?? []),\n ...((incoming as any)[symbolInnerMessage] ?? []),\n ],\n});\n\nconst joinExternalMessages = (\n messages: readonly useExternalMessageConverter.Message[],\n): ThreadMessageLike => {\n const assistantMessage: Mutable<Omit<ThreadMessageLike, \"metadata\">> & {\n content: Exclude<ThreadMessageLike[\"content\"][0], string>[];\n metadata?: Mutable<ThreadMessageLike[\"metadata\"]>;\n } = {\n role: \"assistant\",\n content: [],\n };\n for (const output of messages) {\n if (output.role === \"tool\") {\n const toolCallIdx = assistantMessage.content.findIndex(\n (c) => c.type === \"tool-call\" && c.toolCallId === output.toolCallId,\n );\n // Ignore orphaned tool results so one bad tool message does not\n // prevent rendering the rest of the conversation.\n if (toolCallIdx !== -1) {\n const toolCall = assistantMessage.content[\n toolCallIdx\n ]! as ToolCallMessagePart;\n if (output.toolName !== undefined) {\n if (toolCall.toolName !== output.toolName)\n throw new Error(\n `Tool call name ${output.toolCallId} ${output.toolName} does not match existing tool call ${toolCall.toolName}`,\n );\n }\n assistantMessage.content[toolCallIdx] = {\n ...toolCall,\n ...{\n [symbolInnerMessage]: [\n ...((toolCall as any)[symbolInnerMessage] ?? []),\n output,\n ],\n },\n result: output.result,\n artifact: output.artifact,\n isError: output.isError,\n messages: output.messages,\n };\n }\n } else {\n const role = output.role;\n const content = (\n typeof output.content === \"string\"\n ? [{ type: \"text\" as const, text: output.content }]\n : output.content\n ).map((c) => ({\n ...c,\n ...{ [symbolInnerMessage]: [output] },\n }));\n switch (role) {\n case \"system\":\n case \"user\":\n return {\n ...output,\n content,\n };\n case \"assistant\":\n if (assistantMessage.content.length === 0) {\n assistantMessage.id = output.id;\n assistantMessage.createdAt ??= output.createdAt;\n assistantMessage.status ??= output.status;\n\n if (output.attachments) {\n assistantMessage.attachments = [\n ...(assistantMessage.attachments ?? []),\n ...output.attachments,\n ];\n }\n\n if (output.metadata) {\n assistantMessage.metadata ??= {};\n if (output.metadata.unstable_state) {\n assistantMessage.metadata.unstable_state =\n output.metadata.unstable_state;\n }\n if (output.metadata.unstable_annotations) {\n assistantMessage.metadata.unstable_annotations = [\n ...(assistantMessage.metadata.unstable_annotations ?? []),\n ...output.metadata.unstable_annotations,\n ];\n }\n if (output.metadata.unstable_data) {\n assistantMessage.metadata.unstable_data = [\n ...(assistantMessage.metadata.unstable_data ?? []),\n ...output.metadata.unstable_data,\n ];\n }\n if (output.metadata.steps) {\n assistantMessage.metadata.steps = [\n ...(assistantMessage.metadata.steps ?? []),\n ...output.metadata.steps,\n ];\n }\n if (output.metadata.custom) {\n assistantMessage.metadata.custom = {\n ...(assistantMessage.metadata.custom ?? {}),\n ...output.metadata.custom,\n };\n }\n\n if (output.metadata.timing) {\n assistantMessage.metadata.timing = output.metadata.timing;\n }\n\n if (output.metadata.submittedFeedback) {\n assistantMessage.metadata.submittedFeedback =\n output.metadata.submittedFeedback;\n }\n }\n // TODO keep this in sync\n }\n\n // Add content parts, merging reasoning parts with same parentId\n for (const part of content) {\n if (part.type === \"tool-call\") {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"tool-call\" && c.toolCallId === part.toolCallId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n ...part,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n\n if (\n part.type === \"reasoning\" &&\n \"parentId\" in part &&\n part.parentId\n ) {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"reasoning\" &&\n \"parentId\" in c &&\n c.parentId === part.parentId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n text: `${existing.text}\\n\\n${part.text}`,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n assistantMessage.content.push(part);\n }\n break;\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n }\n }\n return assistantMessage;\n};\n\nconst chunkExternalMessages = <T>(\n callbackResults: CallbackResult<T>[],\n joinStrategy?: \"concat-content\" | \"none\",\n) => {\n const results: ChunkResult<T>[] = [];\n let isAssistant = false;\n let pendingNone = false; // true if the previous assistant message had joinStrategy \"none\"\n let inputs: T[] = [];\n let outputs: useExternalMessageConverter.Message[] = [];\n\n const flush = () => {\n if (outputs.length) {\n results.push({\n inputs,\n outputs,\n });\n }\n inputs = [];\n outputs = [];\n isAssistant = false;\n pendingNone = false;\n };\n\n for (const callbackResult of callbackResults) {\n for (const output of callbackResult.outputs) {\n if (\n (pendingNone && output.role !== \"tool\") ||\n !isAssistant ||\n output.role === \"user\" ||\n output.role === \"system\"\n ) {\n flush();\n }\n isAssistant = output.role === \"assistant\" || output.role === \"tool\";\n\n if (inputs.at(-1) !== callbackResult.input) {\n inputs.push(callbackResult.input);\n }\n outputs.push(output);\n\n if (\n output.role === \"assistant\" &&\n (output.convertConfig?.joinStrategy === \"none\" ||\n joinStrategy === \"none\")\n ) {\n pendingNone = true;\n }\n }\n }\n flush();\n return results;\n};\n\nfunction createErrorAssistantMessage(\n error: ReadonlyJSONValue,\n): ThreadAssistantMessage {\n const msg: ThreadAssistantMessage = {\n id: generateErrorMessageId(),\n role: \"assistant\",\n content: [],\n status: { type: \"incomplete\", reason: \"error\", error },\n createdAt: new Date(),\n metadata: {\n unstable_state: null,\n unstable_annotations: [],\n unstable_data: [],\n custom: {},\n steps: [],\n },\n };\n bindExternalStoreMessage(msg, []);\n return msg;\n}\n\nexport const convertExternalMessages = <T extends WeakKey>(\n messages: T[],\n callback: useExternalMessageConverter.Callback<T>,\n isRunning: boolean,\n metadata: useExternalMessageConverter.Metadata,\n) => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n const output = callback(message, metadata);\n const outputs = Array.isArray(output) ? output : [output];\n const result = { input: message, outputs };\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults);\n\n const result = chunks.map((message, idx) => {\n const isLast = idx === chunks.length - 1;\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? metadata.error : undefined,\n );\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n });\n\n if (metadata.error) {\n const lastMessage = result.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n result.push(createErrorAssistantMessage(metadata.error));\n }\n }\n\n return result;\n};\n\nexport const useExternalMessageConverter = <T extends WeakKey>({\n callback,\n messages,\n isRunning,\n joinStrategy,\n metadata,\n}: {\n callback: useExternalMessageConverter.Callback<T>;\n messages: T[];\n isRunning: boolean;\n joinStrategy?: \"concat-content\" | \"none\" | undefined;\n metadata?: useExternalMessageConverter.Metadata | undefined;\n}) => {\n const state = useMemo(\n () => ({\n metadata: metadata ?? {},\n callback,\n callbackCache: new WeakMap<T, CallbackResult<T>>(),\n chunkCache: new WeakMap<\n useExternalMessageConverter.Message,\n ChunkResult<T>\n >(),\n converterCache: new ThreadMessageConverter(),\n }),\n [callback, metadata],\n );\n\n return useMemo(() => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n let result = state.callbackCache.get(message);\n if (!result) {\n const output = state.callback(message, state.metadata);\n const outputs = Array.isArray(output) ? output : [output];\n result = { input: message, outputs };\n state.callbackCache.set(message, result);\n }\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults, joinStrategy).map(\n (m) => {\n const key = m.outputs[0];\n if (!key) return m;\n\n const cached = state.chunkCache.get(key);\n if (cached && shallowArrayEqual(cached.outputs, m.outputs))\n return cached;\n state.chunkCache.set(key, m);\n return m;\n },\n );\n\n const threadMessages = state.converterCache.convertMessages(\n chunks,\n (cache, message, idx) => {\n const isLast = idx === chunks.length - 1;\n\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? state.metadata.error : undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n ) {\n const inputs = getExternalStoreMessages<T>(cache);\n if (shallowArrayEqual(inputs, message.inputs)) {\n return cache;\n }\n }\n\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n },\n );\n\n bindExternalStoreMessage(threadMessages, messages);\n\n if (state.metadata.error) {\n const lastMessage = threadMessages.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n threadMessages.push(createErrorAssistantMessage(state.metadata.error));\n }\n }\n\n return threadMessages;\n }, [state, messages, isRunning, joinStrategy]);\n};\n\nconst shallowArrayEqual = (a: unknown[], b: unknown[]) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n};\n"],"mappings":";;;;;;;;AA6BA,MAAM,qBAAqB,MACzB,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA;AAEzC,MAAM,yBAAyB,MAA6C;CAC1E,IAAI,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA,GAAW,OAAO;CAC7D,OACE,EAAE,aAAa,QACd,EAAE,YAAY,QAAQ,EAAE,SAAS,aAAa,KAAA;AAEnD;AA6CA,MAAM,sBAAsB,UAAkB,cAAsB,G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,eAAe,YAAY,SAAS,aACvC,eAAe,KAAK,4BAA4B,MAAM,SAAS,KAAK,CAAC;EAEzE;EAEA,OAAO;CACT,GAAG;EAAC;EAAO;EAAU;EAAW;CAAY,CAAC;AAC/C;AAEA,MAAM,qBAAqB,GAAc,MAAiB;CACxD,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,IAAI,EAAE,OAAO,EAAE,IAAI,OAAO;CAE5B,OAAO;AACT"}
1
+ {"version":3,"file":"external-message-converter.js","names":["unsupportedRole"],"sources":["../../../src/react/runtimes/external-message-converter.ts"],"sourcesContent":["\"use client\";\n\nimport { useMemo } from \"react\";\nimport { ThreadMessageConverter } from \"../../runtimes/external-store/thread-message-converter\";\nimport {\n getExternalStoreMessages,\n symbolInnerMessage,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport type { ToolExecutionStatus } from \"../../runtimes/tool-invocations/ToolInvocationTracker\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { generateErrorMessageId } from \"../../utils/id\";\nimport type {\n ThreadAssistantMessage,\n ThreadMessage,\n ToolCallMessagePart,\n} from \"../../types/message\";\nimport type { MessageTiming } from \"../../types/message\";\n\ntype ThreadMessageLikeContentItem = Exclude<\n ThreadMessageLike[\"content\"],\n string\n>[number];\n\nconst isPendingToolCall = (c: ThreadMessageLikeContentItem): boolean =>\n c.type === \"tool-call\" && c.result === undefined;\n\nconst isInterruptedToolCall = (c: ThreadMessageLikeContentItem): boolean => {\n if (c.type !== \"tool-call\" || c.result !== undefined) return false;\n return (\n c.interrupt != null ||\n (c.approval != null && c.approval.approved === undefined)\n );\n};\n\nexport namespace useExternalMessageConverter {\n export type Message =\n | (ThreadMessageLike & {\n readonly convertConfig?: {\n readonly joinStrategy?: \"concat-content\" | \"none\";\n };\n })\n | {\n role: \"tool\";\n toolCallId: string;\n toolName?: string | undefined;\n result: any;\n artifact?: any;\n isError?: boolean;\n messages?: readonly ThreadMessage[];\n };\n\n export type Metadata = {\n readonly toolStatuses?: Record<string, ToolExecutionStatus>;\n readonly error?: ReadonlyJSONValue;\n readonly messageTiming?: Record<string, MessageTiming>;\n };\n\n export type Callback<T> = (\n message: T,\n metadata: Metadata,\n ) => Message | Message[];\n}\n\ntype CallbackResult<T> = {\n input: T;\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype ChunkResult<T> = {\n inputs: T[];\n outputs: useExternalMessageConverter.Message[];\n};\n\ntype Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\nconst mergeInnerMessages = (existing: object, incoming: object) => ({\n [symbolInnerMessage]: [\n ...((existing as any)[symbolInnerMessage] ?? []),\n ...((incoming as any)[symbolInnerMessage] ?? []),\n ],\n});\n\nconst joinExternalMessages = (\n messages: readonly useExternalMessageConverter.Message[],\n): ThreadMessageLike => {\n const assistantMessage: Mutable<Omit<ThreadMessageLike, \"metadata\">> & {\n content: Exclude<ThreadMessageLike[\"content\"][0], string>[];\n metadata?: Mutable<ThreadMessageLike[\"metadata\"]>;\n } = {\n role: \"assistant\",\n content: [],\n };\n for (const output of messages) {\n if (output.role === \"tool\") {\n const toolCallIdx = assistantMessage.content.findIndex(\n (c) => c.type === \"tool-call\" && c.toolCallId === output.toolCallId,\n );\n // Ignore orphaned tool results so one bad tool message does not\n // prevent rendering the rest of the conversation.\n if (toolCallIdx !== -1) {\n const toolCall = assistantMessage.content[\n toolCallIdx\n ]! as ToolCallMessagePart;\n if (output.toolName !== undefined) {\n if (toolCall.toolName !== output.toolName)\n throw new Error(\n `Tool call name ${output.toolCallId} ${output.toolName} does not match existing tool call ${toolCall.toolName}`,\n );\n }\n assistantMessage.content[toolCallIdx] = {\n ...toolCall,\n ...{\n [symbolInnerMessage]: [\n ...((toolCall as any)[symbolInnerMessage] ?? []),\n output,\n ],\n },\n result: output.result,\n artifact: output.artifact,\n isError: output.isError,\n messages: output.messages,\n };\n }\n } else {\n const role = output.role;\n const content = (\n typeof output.content === \"string\"\n ? [{ type: \"text\" as const, text: output.content }]\n : output.content\n ).map((c) => ({\n ...c,\n ...{ [symbolInnerMessage]: [output] },\n }));\n switch (role) {\n case \"system\":\n case \"user\":\n return {\n ...output,\n content,\n };\n case \"assistant\":\n if (assistantMessage.content.length === 0) {\n assistantMessage.id = output.id;\n assistantMessage.createdAt ??= output.createdAt;\n assistantMessage.status ??= output.status;\n\n if (output.attachments) {\n assistantMessage.attachments = [\n ...(assistantMessage.attachments ?? []),\n ...output.attachments,\n ];\n }\n\n if (output.metadata) {\n assistantMessage.metadata ??= {};\n if (output.metadata.unstable_state) {\n assistantMessage.metadata.unstable_state =\n output.metadata.unstable_state;\n }\n if (output.metadata.unstable_annotations) {\n assistantMessage.metadata.unstable_annotations = [\n ...(assistantMessage.metadata.unstable_annotations ?? []),\n ...output.metadata.unstable_annotations,\n ];\n }\n if (output.metadata.unstable_data) {\n assistantMessage.metadata.unstable_data = [\n ...(assistantMessage.metadata.unstable_data ?? []),\n ...output.metadata.unstable_data,\n ];\n }\n if (output.metadata.steps) {\n assistantMessage.metadata.steps = [\n ...(assistantMessage.metadata.steps ?? []),\n ...output.metadata.steps,\n ];\n }\n if (output.metadata.custom) {\n assistantMessage.metadata.custom = {\n ...(assistantMessage.metadata.custom ?? {}),\n ...output.metadata.custom,\n };\n }\n\n if (output.metadata.timing) {\n assistantMessage.metadata.timing = output.metadata.timing;\n }\n\n if (output.metadata.submittedFeedback) {\n assistantMessage.metadata.submittedFeedback =\n output.metadata.submittedFeedback;\n }\n }\n // TODO keep this in sync\n }\n\n // Add content parts, merging reasoning parts with same parentId\n for (const part of content) {\n if (part.type === \"tool-call\") {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"tool-call\" && c.toolCallId === part.toolCallId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n ...part,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n\n if (\n part.type === \"reasoning\" &&\n \"parentId\" in part &&\n part.parentId\n ) {\n const existingIdx = assistantMessage.content.findIndex(\n (c) =>\n c.type === \"reasoning\" &&\n \"parentId\" in c &&\n c.parentId === part.parentId,\n );\n if (existingIdx !== -1) {\n const existing = assistantMessage.content[\n existingIdx\n ] as typeof part;\n assistantMessage.content[existingIdx] = {\n ...existing,\n text: `${existing.text}\\n\\n${part.text}`,\n ...mergeInnerMessages(existing, part),\n };\n continue;\n }\n }\n assistantMessage.content.push(part);\n }\n break;\n default: {\n const unsupportedRole: never = role;\n throw new Error(`Unknown message role: ${unsupportedRole}`);\n }\n }\n }\n }\n return assistantMessage;\n};\n\nconst chunkExternalMessages = <T>(\n callbackResults: CallbackResult<T>[],\n joinStrategy?: \"concat-content\" | \"none\",\n) => {\n const results: ChunkResult<T>[] = [];\n let isAssistant = false;\n let pendingNone = false; // true if the previous assistant message had joinStrategy \"none\"\n let inputs: T[] = [];\n let outputs: useExternalMessageConverter.Message[] = [];\n\n const flush = () => {\n if (outputs.length) {\n results.push({\n inputs,\n outputs,\n });\n }\n inputs = [];\n outputs = [];\n isAssistant = false;\n pendingNone = false;\n };\n\n for (const callbackResult of callbackResults) {\n for (const output of callbackResult.outputs) {\n if (\n (pendingNone && output.role !== \"tool\") ||\n !isAssistant ||\n output.role === \"user\" ||\n output.role === \"system\"\n ) {\n flush();\n }\n isAssistant = output.role === \"assistant\" || output.role === \"tool\";\n\n if (inputs.at(-1) !== callbackResult.input) {\n inputs.push(callbackResult.input);\n }\n outputs.push(output);\n\n if (\n output.role === \"assistant\" &&\n (output.convertConfig?.joinStrategy === \"none\" ||\n joinStrategy === \"none\")\n ) {\n pendingNone = true;\n }\n }\n }\n flush();\n return results;\n};\n\nfunction createErrorAssistantMessage(\n error: ReadonlyJSONValue,\n): ThreadAssistantMessage {\n const msg: ThreadAssistantMessage = {\n id: generateErrorMessageId(),\n role: \"assistant\",\n content: [],\n status: { type: \"incomplete\", reason: \"error\", error },\n createdAt: new Date(),\n metadata: {\n unstable_state: null,\n unstable_annotations: [],\n unstable_data: [],\n custom: {},\n steps: [],\n },\n };\n bindExternalStoreMessage(msg, []);\n return msg;\n}\n\nexport const convertExternalMessages = <T extends WeakKey>(\n messages: T[],\n callback: useExternalMessageConverter.Callback<T>,\n isRunning: boolean,\n metadata: useExternalMessageConverter.Metadata,\n) => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n const output = callback(message, metadata);\n const outputs = Array.isArray(output) ? output : [output];\n const result = { input: message, outputs };\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults);\n\n const result = chunks.map((message, idx) => {\n const isLast = idx === chunks.length - 1;\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? metadata.error : undefined,\n );\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n });\n\n if (metadata.error) {\n const lastMessage = result.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n result.push(createErrorAssistantMessage(metadata.error));\n }\n }\n\n return result;\n};\n\nexport const useExternalMessageConverter = <T extends WeakKey>({\n callback,\n messages,\n isRunning,\n joinStrategy,\n metadata,\n}: {\n callback: useExternalMessageConverter.Callback<T>;\n messages: T[];\n isRunning: boolean;\n joinStrategy?: \"concat-content\" | \"none\" | undefined;\n metadata?: useExternalMessageConverter.Metadata | undefined;\n}) => {\n const state = useMemo(\n () => ({\n metadata: metadata ?? {},\n callback,\n callbackCache: new WeakMap<T, CallbackResult<T>>(),\n chunkCache: new WeakMap<\n useExternalMessageConverter.Message,\n ChunkResult<T>\n >(),\n converterCache: new ThreadMessageConverter(),\n }),\n [callback, metadata],\n );\n\n return useMemo(() => {\n const callbackResults: CallbackResult<T>[] = [];\n for (const message of messages) {\n let result = state.callbackCache.get(message);\n if (!result) {\n const output = state.callback(message, state.metadata);\n const outputs = Array.isArray(output) ? output : [output];\n result = { input: message, outputs };\n state.callbackCache.set(message, result);\n }\n callbackResults.push(result);\n }\n\n const chunks = chunkExternalMessages(callbackResults, joinStrategy).map(\n (m) => {\n const key = m.outputs[0];\n if (!key) return m;\n\n const cached = state.chunkCache.get(key);\n if (cached && shallowArrayEqual(cached.outputs, m.outputs))\n return cached;\n state.chunkCache.set(key, m);\n return m;\n },\n );\n\n const threadMessages = state.converterCache.convertMessages(\n chunks,\n (cache, message, idx) => {\n const isLast = idx === chunks.length - 1;\n\n const joined = joinExternalMessages(message.outputs);\n const hasInterruptedToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isInterruptedToolCall);\n const hasPendingToolCalls =\n typeof joined.content === \"object\" &&\n joined.content.some(isPendingToolCall);\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n hasInterruptedToolCalls,\n hasPendingToolCalls,\n isLast ? state.metadata.error : undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n ) {\n const inputs = getExternalStoreMessages<T>(cache);\n if (shallowArrayEqual(inputs, message.inputs)) {\n return cache;\n }\n }\n\n const newMessage = fromThreadMessageLike(\n joined,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, message.inputs);\n return newMessage;\n },\n );\n\n bindExternalStoreMessage(threadMessages, messages);\n\n if (state.metadata.error) {\n const lastMessage = threadMessages.at(-1);\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n threadMessages.push(createErrorAssistantMessage(state.metadata.error));\n }\n }\n\n return threadMessages;\n }, [state, messages, isRunning, joinStrategy]);\n};\n\nconst shallowArrayEqual = (a: unknown[], b: unknown[]) => {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n};\n"],"mappings":";;;;;;;;AA6BA,MAAM,qBAAqB,MACzB,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA;AAEzC,MAAM,yBAAyB,MAA6C;CAC1E,IAAI,EAAE,SAAS,eAAe,EAAE,WAAW,KAAA,GAAW,OAAO;CAC7D,OACE,EAAE,aAAa,QACd,EAAE,YAAY,QAAQ,EAAE,SAAS,aAAa,KAAA;AAEnD;AA6CA,MAAM,sBAAsB,UAAkB,cAAsB,GACjE,qBAAqB,CACpB,GAAK,SAAiB,uBAAuB,CAAC,GAC9C,GAAK,SAAiB,uBAAuB,CAAC,CAChD,EACF;AAEA,MAAM,wBACJ,aACsB;CACtB,MAAM,mBAGF;EACF,MAAM;EACN,SAAS,CAAC;CACZ;CACA,KAAK,MAAM,UAAU,UACnB,IAAI,OAAO,SAAS,QAAQ;EAC1B,MAAM,cAAc,iBAAiB,QAAQ,WAC1C,MAAM,EAAE,SAAS,eAAe,EAAE,eAAe,OAAO,UAC3D;EAGA,IAAI,gBAAgB,IAAI;GACtB,MAAM,WAAW,iBAAiB,QAChC;GAEF,IAAI,OAAO,aAAa,KAAA;QAClB,SAAS,aAAa,OAAO,UAC/B,MAAM,IAAI,MACR,kBAAkB,OAAO,WAAW,GAAG,OAAO,SAAS,qCAAqC,SAAS,UACvG;GAAA;GAEJ,iBAAiB,QAAQ,eAAe;IACtC,GAAG;KAEA,qBAAqB,CACpB,GAAK,SAAiB,uBAAuB,CAAC,GAC9C,MACF;IAEF,QAAQ,OAAO;IACf,UAAU,OAAO;IACjB,SAAS,OAAO;IAChB,UAAU,OAAO;GACnB;EACF;CACF,OAAO;EACL,MAAM,OAAO,OAAO;EAC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AA0C,yBAAyB;EAAA,IACnE,MAAM,CAAA;AAAA;AAAA,cAKN,4BAAA,SAAqC,qBAAqB;EAAA,IAC1D,MAAA,CAAA;EAIJ,MAAA,CAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"attachment-runtime.js","names":[],"sources":["../../../src/runtime/api/attachment-runtime.ts"],"sourcesContent":["import type { Attachment, CompleteAttachment } from \"../../types/attachment\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\n\nimport type { ComposerRuntimeCoreBinding } from \"./bindings\";\nimport type { AttachmentRuntimePath } from \"./paths\";\n\ntype MessageAttachmentState = CompleteAttachment & {\n readonly source: \"message\";\n};\n\ntype ThreadComposerAttachmentState = Attachment & {\n readonly source: \"thread-composer\";\n};\n\ntype EditComposerAttachmentState = Attachment & {\n readonly source: \"edit-composer\";\n};\n\nexport type AttachmentState =\n | ThreadComposerAttachmentState\n | EditComposerAttachmentState\n | MessageAttachmentState;\n\ntype AttachmentSnapshotBinding<Source extends AttachmentRuntimeSource> =\n SubscribableWithState<\n AttachmentState & { source: Source },\n AttachmentRuntimePath & { attachmentSource: Source }\n >;\n\ntype AttachmentRuntimeSource = AttachmentState[\"source\"];\n\nexport type AttachmentRuntime<\n TSource extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> = {\n readonly path: AttachmentRuntimePath & { attachmentSource: TSource };\n readonly source: TSource;\n getState(): AttachmentState & { source: TSource };\n remove(): Promise<void>;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport abstract class AttachmentRuntimeImpl<\n Source extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> implements AttachmentRuntime\n{\n public get path() {\n return this._core.path;\n }\n\n public abstract get source(): Source;\n\n constructor(private _core: AttachmentSnapshotBinding<Source>) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.getState = this.getState.bind(this);\n this.remove = this.remove.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n\n public getState(): AttachmentState & { source: Source } {\n return this._core.getState();\n }\n\n public abstract remove(): Promise<void>;\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n}\n\nabstract class ComposerAttachmentRuntime<\n Source extends \"thread-composer\" | \"edit-composer\",\n> extends AttachmentRuntimeImpl<Source> {\n constructor(\n core: AttachmentSnapshotBinding<Source>,\n private _composerApi: ComposerRuntimeCoreBinding,\n ) {\n super(core);\n }\n\n public remove() {\n const core = this._composerApi.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.removeAttachment(this.getState().id);\n }\n}\n\nexport class ThreadComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"thread-composer\"> {\n public get source(): \"thread-composer\" {\n return \"thread-composer\";\n }\n}\n\nexport class EditComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"edit-composer\"> {\n public get source(): \"edit-composer\" {\n return \"edit-composer\";\n }\n}\n\nexport class MessageAttachmentRuntimeImpl extends AttachmentRuntimeImpl<\"message\"> {\n public get source(): \"message\" {\n return \"message\";\n }\n\n public remove(): never {\n throw new Error(\"Message attachments cannot be removed\");\n }\n}\n"],"mappings":";AA0CA,IAAsB,wBAAtB,MAGA;CAOsB;CANpB,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM;CACpB;CAIA,YAAY,OAAkD;EAA1C,KAAA,QAAA;EAClB,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;EACvC,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;CAC3C;CAEA,WAAwD;EACtD,OAAO,KAAK,MAAM,SAAS;CAC7B;CAIA,UAAiB,UAAsB;EACrC,OAAO,KAAK,MAAM,UAAU,QAAQ;CACtC;AACF;AAEA,IAAe,4BAAf,cAEU,sBAA8B;CAG5B;CAFV,YACE,MACA,cACA;EACA,MAAM,IAAI;EAFF,KAAA,eAAA;CAGV;CAEA,SAAgB;EACd,MAAM,OAAO,KAAK,aAAa,SAAS;EACxC,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,2BAA2B;EACtD,OAAO,KAAK,iBAAiB,KAAK,SAAS,EAAE,EAAE;CACjD;AACF;AAEA,IAAa,sCAAb,cAAyD,0BAA6C;CACpG,IAAW,SAA4B;EACrC,OAAO;CACT;AACF;AAEA,IAAa,oCAAb,cAAuD,0BAA2C;CAChG,IAAW,SAA0B;EACnC,OAAO;CACT;AACF;AAEA,IAAa,+BAAb,cAAkD,sBAAiC;CACjF,IAAW,SAAoB;EAC7B,OAAO;CACT;CAEA,SAAuB;EACrB,MAAM,IAAI,MAAM,uCAAuC;CACzD;AACF"}
1
+ {"version":3,"file":"attachment-runtime.js","names":[],"sources":["../../../src/runtime/api/attachment-runtime.ts"],"sourcesContent":["import type { Attachment, CompleteAttachment } from \"../../types/attachment\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\n\nimport type { ComposerRuntimeCoreBinding } from \"./bindings\";\nimport type { AttachmentRuntimePath } from \"./paths\";\n\ntype MessageAttachmentState = CompleteAttachment & {\n readonly source: \"message\";\n};\n\ntype ThreadComposerAttachmentState = Attachment & {\n readonly source: \"thread-composer\";\n};\n\ntype EditComposerAttachmentState = Attachment & {\n readonly source: \"edit-composer\";\n};\n\nexport type AttachmentState =\n | ThreadComposerAttachmentState\n | EditComposerAttachmentState\n | MessageAttachmentState;\n\ntype AttachmentSnapshotBinding<Source extends AttachmentRuntimeSource> =\n SubscribableWithState<\n AttachmentState & { source: Source },\n AttachmentRuntimePath & { attachmentSource: Source }\n >;\n\ntype AttachmentRuntimeSource = AttachmentState[\"source\"];\n\nexport type AttachmentRuntime<\n TSource extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> = {\n readonly path: AttachmentRuntimePath & { attachmentSource: TSource };\n readonly source: TSource;\n getState(): AttachmentState & { source: TSource };\n remove(): Promise<void>;\n subscribe(callback: () => void): Unsubscribe;\n};\n\nexport abstract class AttachmentRuntimeImpl<\n Source extends AttachmentRuntimeSource = AttachmentRuntimeSource,\n> implements AttachmentRuntime {\n public get path() {\n return this._core.path;\n }\n\n public abstract get source(): Source;\n\n constructor(private _core: AttachmentSnapshotBinding<Source>) {\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.getState = this.getState.bind(this);\n this.remove = this.remove.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n\n public getState(): AttachmentState & { source: Source } {\n return this._core.getState();\n }\n\n public abstract remove(): Promise<void>;\n\n public subscribe(callback: () => void) {\n return this._core.subscribe(callback);\n }\n}\n\nabstract class ComposerAttachmentRuntime<\n Source extends \"thread-composer\" | \"edit-composer\",\n> extends AttachmentRuntimeImpl<Source> {\n constructor(\n core: AttachmentSnapshotBinding<Source>,\n private _composerApi: ComposerRuntimeCoreBinding,\n ) {\n super(core);\n }\n\n public remove() {\n const core = this._composerApi.getState();\n if (!core) throw new Error(\"Composer is not available\");\n return core.removeAttachment(this.getState().id);\n }\n}\n\nexport class ThreadComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"thread-composer\"> {\n public get source(): \"thread-composer\" {\n return \"thread-composer\";\n }\n}\n\nexport class EditComposerAttachmentRuntimeImpl extends ComposerAttachmentRuntime<\"edit-composer\"> {\n public get source(): \"edit-composer\" {\n return \"edit-composer\";\n }\n}\n\nexport class MessageAttachmentRuntimeImpl extends AttachmentRuntimeImpl<\"message\"> {\n public get source(): \"message\" {\n return \"message\";\n }\n\n public remove(): never {\n throw new Error(\"Message attachments cannot be removed\");\n }\n}\n"],"mappings":";AA0CA,IAAsB,wBAAtB,MAE+B;CAOT;CANpB,IAAW,OAAO;EAChB,OAAO,KAAK,MAAM;CACpB;CAIA,YAAY,OAAkD;EAA1C,KAAA,QAAA;EAClB,KAAK,uBAAuB;CAC9B;CAEA,yBAAmC;EACjC,KAAK,WAAW,KAAK,SAAS,KAAK,IAAI;EACvC,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,YAAY,KAAK,UAAU,KAAK,IAAI;CAC3C;CAEA,WAAwD;EACtD,OAAO,KAAK,MAAM,SAAS;CAC7B;CAIA,UAAiB,UAAsB;EACrC,OAAO,KAAK,MAAM,UAAU,QAAQ;CACtC;AACF;AAEA,IAAe,4BAAf,cAEU,sBAA8B;CAG5B;CAFV,YACE,MACA,cACA;EACA,MAAM,IAAI;EAFF,KAAA,eAAA;CAGV;CAEA,SAAgB;EACd,MAAM,OAAO,KAAK,aAAa,SAAS;EACxC,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,2BAA2B;EACtD,OAAO,KAAK,iBAAiB,KAAK,SAAS,EAAE,EAAE;CACjD;AACF;AAEA,IAAa,sCAAb,cAAyD,0BAA6C;CACpG,IAAW,SAA4B;EACrC,OAAO;CACT;AACF;AAEA,IAAa,oCAAb,cAAuD,0BAA2C;CAChG,IAAW,SAA0B;EACnC,OAAO;CACT;AACF;AAEA,IAAa,+BAAb,cAAkD,sBAAiC;CACjF,IAAW,SAAoB;EAC7B,OAAO;CACT;CAEA,SAAuB;EACrB,MAAM,IAAI,MAAM,uCAAuC;CACzD;AACF"}
@@ -7,6 +7,7 @@ import { ChatModelRunOptions, ChatModelRunResult } from "../utils/chat-model-ada
7
7
  import { ThreadMessageLike } from "../utils/thread-message-like.js";
8
8
  import { ExportedMessageRepository } from "../utils/message-repository.js";
9
9
  import { EditComposerRuntimeCore, ThreadComposerRuntimeCore } from "./composer-runtime-core.js";
10
+ import { ToolModelContentPart } from "assistant-stream";
10
11
  import { ReadonlyJSONValue } from "assistant-stream/utils";
11
12
 
12
13
  //#region src/runtime/interfaces/thread-runtime-core.d.ts
@@ -31,6 +32,13 @@ type AddToolResultOptions = {
31
32
  result: ReadonlyJSONValue;
32
33
  isError: boolean;
33
34
  artifact?: ReadonlyJSONValue | undefined;
35
+ /**
36
+ * Optional model-content payload produced by the tool. Populated when a
37
+ * client-side `execute()` or `streamCall` returns a `ToolResponse` with
38
+ * `modelContent`. Forwarded through `adapter.onAddToolResult` so the
39
+ * adapter can include it when sending the result back to its backend.
40
+ */
41
+ modelContent?: readonly ToolModelContentPart[] | undefined;
34
42
  };
35
43
  type ResumeToolCallOptions = {
36
44
  toolCallId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/interfaces/thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;KAkBY,mBAAA;EAAA,SACD,cAAA;EAAA,SACA,qBAAA;EAAA,SACA,IAAA;EAAA,SACA,MAAA;EAAA,SACA,MAAA;EAAA,SACA,aAAA;EAAA,SACA,MAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA;EAAA,SACA,WAAA;EAAA,SACA,QAAA;EAAA,SACA,KAAA;AAAA;AAAA,KAGC,oBAAA;EACV,SAAA;EACA,QAAA;EACA,UAAA;EACA,MAAA,EAAQ,iBAAA;EACR,OAAA;EACA,QAAA,GAAW,iBAAiB;AAAA;AAAA,KAGlB,qBAAA;EACV,UAAA;EACA,OAAO;AAAA;AAAA,KAGG,4BAAA;EACV,UAAA;EACA,QAAA;EACA,MAAA;AAAA;AAAA,KAGU,qBAAA;EACV,SAAA;EACA,IAAI;AAAA;AAAA,KAGM,gBAAA;EACV,MAAM;AAAA;AAAA,KAGI,WAAA;EAAA,SACD,SAAA;EAAA,SACA,MAAA,EAAQ,sBAAA,CAAuB,MAAM;AAAA;AAAA,KAGpC,iBAAA;EAAA,SACD,MAAA,EAAQ,oBAAA,CAAqB,MAAA;EAAA,SAC7B,OAAA;EAAA,SACA,IAAA,EAAM,oBAAA,CAAqB,IAAI;AAAA;AAAA,KAG9B,iBAAA;EAAA,SACD,IAAI;AAAA;AAAA,KAGH,yBAAA;EAtBN;AAGN;;;;AACQ;EAyBN,QAAA,EAAU,MAAA;EAtBW;;;;;;EA6BrB,MAAA,EAAQ,MAAA;EA3BsC;AAAA;A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WAAsB,gBAAA;EAEtB,MAAA;EAEA,SAAA,GAAY,QAAA,iBAAyB,WAAA;EAErC,cAAA;EACA,oBAAA,GAAuB,QAAA,iBAAyB,WAAA;EAEhD,MAAA,CAAO,UAAA,EAAY,yBAAA;EACnB,MAAA,IAAU,yBAAA;EAEV,mBAAA;EACA,mBAAA,CAAoB,KAAA;EAEpB,KAAA,CAAM,eAAA,YAA2B,iBAAA;EA7E/B;;;;AACoC;EAmFtC,WAAA,WAAsB,sBAAA,EACpB,KAAA,EAAO,CAAA,EACP,QAAA,EAAU,0BAAA,CAA2B,CAAA,IACpC,WAAA;AAAA"}
1
+ {"version":3,"file":"thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/interfaces/thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;KAmBY,mBAAA;EAAA,SACD,cAAA;EAAA,SACA,qBAAA;EAAA,SACA,IAAA;EAAA,SACA,MAAA;EAAA,SACA,MAAA;EAAA,SACA,aAAA;EAAA,SACA,MAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA;EAAA,SACA,WAAA;EAAA,SACA,QAAA;EAAA,SACA,KAAA;AAAA;AAAA,KAGC,oBAAA;EACV,SAAA;EACA,QAAA;EACA,UAAA;EACA,MAAA,EAAQ,iBAAA;EACR,OAAA;EACA,QAAA,GAAW,iBAAA;;;;;;;EAOX,YAAA,YAAwB,oBAAA;AAAA;AAAA,KAGd,qBAAA;EACV,UAAA;EACA,OAAO;AAAA;AAAA,KAGG,4BAAA;EACV,UAAA;EACA,QAAA;EACA,MAAA;AAAA;AAAA,KAGU,qBAAA;EACV,SAAA;EACA,IAAI;AAAA;AAAA,KAGM,gBAAA;EACV,MAAM;AAAA;AAAA,KAGI,WAAA;EAAA,SACD,SAAA;EAAA,SACA,MAAA,EAAQ,sBAAA,CAAuB,MAAM;AAAA;AAAA,KAGpC,iBAAA;EAAA,SACD,MAAA,EAAQ,oBAAA,CAAqB,MAAA;EAAA,SAC7B,OAAA;EAAA,SACA,I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AAA;EAEP,YAAA,EAAc,QAAA,CAAS,mBAAA;EACvB,UAAA;EAxDA;;AAAqC;AAGvC;;EA2DE,cAAA;EACA,SAAA;EA3DA;;;;;AAEoB;EAgEpB,SAAA;EACA,QAAA,WAAmB,aAAA;EACnB,KAAA,EAAO,iBAAA;EACP,WAAA,WAAsB,gBAAA;EAEtB,MAAA;EAEA,SAAA,GAAY,QAAA,iBAAyB,WAAA;EAErC,cAAA;EACA,oBAAA,GAAuB,QAAA,iBAAyB,WAAA;EAEhD,MAAA,CAAO,UAAA,EAAY,yBAAA;EACnB,MAAA,IAAU,yBAAA;EAEV,mBAAA;EACA,mBAAA,CAAoB,KAAA;EAEpB,KAAA,CAAM,eAAA,YAA2B,iBAAA;EA5E5B;;;AAAiC;AAGxC;EAgFE,WAAA,WAAsB,sBAAA,EACpB,KAAA,EAAO,CAAA,EACP,QAAA,EAAU,0BAAA,CAA2B,CAAA,IACpC,WAAA;AAAA"}
@@ -6,6 +6,7 @@ import { RealtimeVoiceAdapter } from "../../adapters/voice.js";
6
6
  import { ThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
7
7
  import { ExportedMessageRepository } from "../../runtime/utils/message-repository.js";
8
8
  import { AddToolResultOptions, RespondToToolApprovalOptions, ResumeRunConfig, StartRunConfig, ThreadSuggestion } from "../../runtime/interfaces/thread-runtime-core.js";
9
+ import { ToolExecutionStatus } from "../tool-invocations/ToolInvocationTracker.js";
9
10
  import { ReadonlyJSONValue } from "assistant-stream/utils";
10
11
 
11
12
  //#region src/runtimes/external-store/external-store-adapter.d.ts
@@ -103,6 +104,36 @@ type ExternalStoreAdapterBase<T> = {
103
104
  unstable_capabilities?: {
104
105
  copy?: boolean | undefined;
105
106
  } | undefined;
107
+ /**
108
+ * Opt in to the built-in client-side tool-invocations pipeline
109
+ * (`streamCall` / `execute` / tool-status tracking) for this thread.
110
+ *
111
+ * Defaults to `false` — the runtime does *not* drive client-side tool
112
+ * callbacks on its own. Set to `true` to have the runtime construct a
113
+ * `ToolInvocationTracker` and feed every snapshot through it, so tool
114
+ * callbacks fire automatically for tool-call parts in `messages`.
115
+ *
116
+ * Opt-in by default because most external-store runtimes either run
117
+ * tools entirely server-side, or already wire their own client-side
118
+ * dispatch path. Enabling the embedded tracker on top of an existing
119
+ * dispatch path would cause tool callbacks to run twice.
120
+ *
121
+ * When enabled, client-side tool results (from `execute()` returning,
122
+ * or from `streamCall` resolving) flow back through
123
+ * `adapter.onAddToolResult` like any other tool result, with
124
+ * `modelContent` populated when present.
125
+ */
126
+ unstable_enableToolInvocations?: boolean | undefined;
127
+ /**
128
+ * Receives the current per-tool-call execution status map whenever it
129
+ * changes. Only invoked when `unstable_enableToolInvocations` is `true`
130
+ * — the runtime maintains the map via the embedded tracker.
131
+ *
132
+ * Wire this into local React state and feed it into the converter's
133
+ * `metadata.toolStatuses` so the UI can render `executing` spinners
134
+ * and human-input prompts.
135
+ */
136
+ setToolStatuses?: ((statuses: Record<string, ToolExecutionStatus>) => void) | undefined;
106
137
  };
107
138
  type ExternalStoreAdapter<T = ThreadMessage> = ExternalStoreAdapterBase<T> & (T extends ThreadMessage ? object : ExternalStoreMessageConverterAdapter<T>);
108
139
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"external-store-adapter.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-adapter.ts"],"mappings":";;;;;;;;;;;KAmBY,uBAAA;EACV,MAAA,EAAQ,MAAM;EACd,EAAA;EACA,QAAA;EACA,UAAA;EACA,KAAA;AAAA;AAAA,KAGU,8BAAA;EAPF;;;EAWR,QAAA;EACA,SAAA;EACA,OAAA,YAAmB,uBAAA;EACnB,eAAA,YAA2B,uBAAA;EAPjB;;;EAWV,mBAAA,UAA6B,OAAA;EAJF;;;EAQ3B,gBAAA,KAAqB,QAAA,aAAqB,OAAA;EAC1C,QAAA,IACE,QAAA,UACA,QAAA,cACI,OAAA;EACN,SAAA,KAAc,QAAA,aAAqB,OAAA;EACnC,WAAA,KAAgB,QAAA,aA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,IACnC,wBAAA,CAAyB,CAAA,KACtB,CAAA,SAAU,aAAA,YAEP,oCAAA,CAAqC,CAAA"}
1
+ {"version":3,"file":"external-store-adapter.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-adapter.ts"],"mappings":";;;;;;;;;;;;KAoBY,uBAAA;EACV,MAAA,EAAQ,MAAM;EACd,EAAA;EACA,QAAA;EACA,UAAA;EACA,KAAA;AAAA;AAAA,KAGU,8BAAA;EAPF;;;EAWR,QAAA;EACA,SAAA;EACA,OAAA,YAAmB,uBAAA;EACnB,eAAA,YAA2B,uBAAA;EAPjB;;;EAWV,mBAAA,UAA6B,OAAA;EAJF;;;EAQ3B,gBAAA,KAAqB,QAAA,aAAqB,OAAA;EAC1C,QAAA,IACE,QAAA,UACA,QAAA,cACI,OAAA;EACN,SAAA,KAAc,QAAA,aAAqB,OAAA;EACnC,WAAA,KAAgB,QAAA,aAAqB,OAAA;EACrC,QAAA,KAAa,QAAA,aAAqB,OAAA;AAAA;AAAA,KAGxB,6BAAA,OACV,OAAA,EAAS,CAAA,EACT,GAAA,aACG,iBAAiB;AAAA,KAEjB,oCAAA;EACH,cAAA,EAAgB,6BAA6B,CAAC,CAAA;AAAA;AAAA,KAG3C,wBAAA;EA3BwB;;;;;;EAkC3B,UAAA;EAxBE;;;;;;;;EAiCF,cAAA;EA5BA;;;;AAAyC;AAG3C;;;EAkCE,SAAA;EACA,SAAA;EACA,QAAA,YAAoB,CAAA;EACpB,iBAAA,GAAoB,yBAAA;EACpB,WAAA,YAAuB,gBAAA;EACvB,KAAA,GAAQ,iBAAA;EACR,MAAA;EAEA,WAAA,KAAgB,QAAA,WAAmB,CAAA;EACnC,QAAA,KAAa,QAAA,WAAmB,aAAA;EAChC,qBAAA;EACA,mBAAA,KAAwB,KAAA;EACxB,KAAA,GAAQ,OAAA,EAAS,aAAA,KAAkB,OAAA;EACnC,MAAA,KAAW,OAAA,EAAS,aAAA,KAAkB,OAAA;EACtC,QAAA,KACM,QAAA,iBAAyB,MAAA,EAAQ,cAAA,KAAmB,OAAA;EAE1D,QAAA,KAAa,MAAA,EAAQ,eAAA,KAAoB,OAAA;EACzC,QAAA,UAAkB,OAAA;EAClB,eAAA,KACM,OAAA,EAAS,oBAAA,KAAyB,OAAA;EAExC,gBAAA,KACM,OAAA;IAAW,UAAA;IAAoB,OAAA;EAAA;EAErC,uBAAA,KACM,OAAA,EAAS,4BAAA,KAAiC,OAAA;EAEhD,cAAA,GAAiB,6BAAA,CAA8B,CAAA;EAC/C,QAAA;IAEM,WAAA,GAAc,iBAAA;IACd,MAAA,GAAS,sBAAA;IACT,SAAA,GAAY,gBAAA;IACZ,KAAA,GAAQ,oBAAA;IACR,QAAA,GAAW,eAAA;IAtBG;;;IA0Bd,UAAA,GAAa,8BAAA;EAAA;EAGnB,qBAAA;IAEM,IAAA;EAAA;EAxBkC;;;;;;;;;;;;;;;;;;;EA8CxC,8BAAA;EAhEA;;;;;;;;;EA0EA,eAAA,KACM,QAAA,EAAU,MAAA,SAAe,mBAAA;AAAA;AAAA,KAIrB,oBAAA,KAAyB,aAAA,IACnC,wBAAA,CAAyB,CAAA,KACtB,CAAA,SAAU,aAAA,YAEP,oCAAA,CAAqC,CAAA"}
@@ -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":";;;;;;KAQY,0BAAA,SAAmC,8BAA8B;AAAA,cAgBhE,kCAAA,YACA,qBAAA;EAAA,QAyCD,aAAA;EAAA,QAvCF,aAAA;EAAA,QACA,QAAA;EAAA,QACA,gBAAA;EAAA,QACA,WAAA;EAAA,QAEA,OAAA;EAAA,IAEG,SAAA,CAAA;EAAA,IAIA,WAAA,CAAA;EAAA,IAIA,SAAA,CAAA;EAAA,IAIA,iBAAA,CAAA;EAAA,IAIA,WAAA,CAAA,GAAW,QAAA,CAAA,MAAA,SAAA,uBAAA;EAIf,qBAAA,CAAA,GAAqB,OAAA;EAAA,QAIpB,WAAA;EAAA,IAEG,YAAA,CAAA;cAKT,OAAA,EAAS,8BAAA,cACD,aAAA,EAAe,0BAAA;EAKlB,wBAAA,CAAA,GAAwB,8BAAA;EAIxB,oBAAA,CAAA;EAIA,WAAA,CAAY,QAAA,WAAgB,uBAAA;EAI5B,qBAAA,CACL,OAAA,EAAS,8BAAA,EACT,WAAA;EAqFW,cAAA,CACX,QAAA,UACA,QAAA;IAAa,SAAA;EAAA,IACZ,OAAA;EAUU,iBAAA,CAAA,GAAqB,OAAA;EAUrB,MAAA,CAAO,QAAA,UAAkB,QAAA,WAAmB,OAAA;EAQ5C,MAAA,CAAA,GAAU,OAAA;EAIV,OAAA,CAAQ,QAAA,WAAmB,OAAA;EAQ3B,SAAA,CAAU,QAAA,WAAmB,OAAA;EAQ7B,MAAA,CAAO,QAAA,WAAmB,OAAA;EAQhC,UAAA,CACL,QAAA,WACC,OAAA;IAAU,QAAA;IAAkB,UAAA;EAAA;EAIxB,aAAA,CAAA;EAAA,QAIC,cAAA;EAED,SAAA,CAAU,QAAA,eAAuB,WAAA;EAAA,QAKhC,kBAAA;AAAA"}
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":";;;;;;KAQY,0BAAA,SAAmC,8BAA8B;AAAA,cAgBhE,kCAAA,YAA8C,qBAAA;EAAA,QAwC/C,aAAA;EAAA,QAvCF,aAAA;EAAA,QACA,QAAA;EAAA,QACA,gBAAA;EAAA,QACA,WAAA;EAAA,QAEA,OAAA;EAAA,IAEG,SAAA,CAAA;EAAA,IAIA,WAAA,CAAA;EAAA,IAIA,SAAA,CAAA;EAAA,IAIA,iBAAA,CAAA;EAAA,IAIA,WAAA,CAAA,GAAW,QAAA,CAAA,MAAA,SAAA,uBAAA;EAIf,qBAAA,CAAA,GAAqB,OAAA;EAAA,QAIpB,WAAA;EAAA,IAEG,YAAA,CAAA;cAKT,OAAA,EAAS,8BAAA,cACD,aAAA,EAAe,0BAAA;EAKlB,wBAAA,CAAA,GAAwB,8BAAA;EAIxB,oBAAA,CAAA;EAIA,WAAA,CAAY,QAAA,WAAgB,uBAAA;EAI5B,qBAAA,CACL,OAAA,EAAS,8BAAA,EACT,WAAA;EAqFW,cAAA,CACX,QAAA,UACA,QAAA;IAAa,SAAA;EAAA,IACZ,OAAA;EAUU,iBAAA,CAAA,GAAqB,OAAA;EAUrB,MAAA,CAAO,QAAA,UAAkB,QAAA,WAAmB,OAAA;EAQ5C,MAAA,CAAA,GAAU,OAAA;EAIV,OAAA,CAAQ,QAAA,WAAmB,OAAA;EAQ3B,SAAA,CAAU,QAAA,WAAmB,OAAA;EAQ7B,MAAA,CAAO,QAAA,WAAmB,OAAA;EAQhC,UAAA,CACL,QAAA,WACC,OAAA;IAAU,QAAA;IAAkB,UAAA;EAAA;EAIxB,aAAA,CAAA;EAAA,QAIC,cAAA;EAED,SAAA,CAAU,QAAA,eAAuB,WAAA;EAAA,QAKhC,kBAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"external-store-thread-list-runtime-core.js","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport 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\";\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 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 constructor(\n adapter: ExternalStoreThreadListAdapter = {},\n private threadFactory: ExternalStoreThreadFactory,\n ) {\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 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 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 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 private _subscriptions = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n"],"mappings":";AAUA,MAAM,cAAc,OAAO,OAAO,CAAC,CAAC;AACpC,MAAM,oBAAoB;AAC1B,MAAM,kBAAkB,OAAO,OAAO,CAAC,iBAAiB,CAAC;AACzD,MAAM,iBAAiB,OAAO,OAAO;CACnC,IAAI;CACJ,UAAU,KAAA;CACV,YAAY,KAAA;CACZ,QAAQ;AACV,CAAC;AACD,MAAM,mBAAmB,QAAQ,QAAQ;AACzC,MAAM,sBAAsB,OAAO,OAAO,GACvC,oBAAoB,eACvB,CAAC;AAED,IAAa,qCAAb,MAEA;CAwCY;CAvCV,gBAAgC;CAChC,WAAsC;CACtC,mBAA8C;CAC9C,cACE;CACF,UAAkD,CAAC;CAEnD,IAAW,YAAY;EACrB,OAAO,KAAK,QAAQ,aAAa;CACnC;C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,MAAM,WAAW,KAAK,QAAQ;EAC9B,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,kDAAkD;EAEpE,MAAM,SAAS,QAAQ;CACzB;CAEA,WACE,UAC+D;EAC/D,OAAO,QAAQ,QAAQ;GAAE,UAAU;GAAU,YAAY,KAAA;EAAU,CAAC;CACtE;CAEA,gBAA8B;EAC5B,MAAM,IAAI,MAAM,yBAAyB;CAC3C;CAEA,iCAAyB,IAAI,IAAgB;CAE7C,UAAiB,UAAmC;EAClD,KAAK,eAAe,IAAI,QAAQ;EAChC,aAAa,KAAK,eAAe,OAAO,QAAQ;CAClD;CAEA,qBAA6B;EAC3B,KAAK,MAAM,YAAY,KAAK,gBAAgB,SAAS;CACvD;AACF"}
1
+ {"version":3,"file":"external-store-thread-list-runtime-core.js","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport 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\";\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 implements ThreadListRuntimeCore {\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 constructor(\n adapter: ExternalStoreThreadListAdapter = {},\n private threadFactory: ExternalStoreThreadFactory,\n ) {\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 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 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 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 private _subscriptions = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n"],"mappings":";AAUA,MAAM,cAAc,OAAO,OAAO,CAAC,CAAC;AACpC,MAAM,oBAAoB;AAC1B,MAAM,kBAAkB,OAAO,OAAO,CAAC,iBAAiB,CAAC;AACzD,MAAM,iBAAiB,OAAO,OAAO;CACnC,IAAI;CACJ,UAAU,KAAA;CACV,YAAY,KAAA;CACZ,QAAQ;AACV,CAAC;AACD,MAAM,mBAAmB,QAAQ,QAAQ;AACzC,MAAM,sBAAsB,OAAO,OAAO,GACvC,oBAAoB,eACvB,CAAC;AAED,IAAa,qCAAb,MAAiF;CAwCrE;CAvCV,gBAAgC;CAChC,WAAsC;CACtC,mBAA8C;CAC9C,cACE;CACF,UAAkD,CAAC;CAEnD,IAAW,YAAY;EACrB,OAAO,KAAK,QAAQ,aAAa;CACnC;CAEA,IAAW,cAAc,CAEzB;CAEA,IAAW,YAAY;EACrB,OAAO,KAAK;CACd;CAEA,IAAW,oBAAoB;EAC7B,OAAO,KAAK;CACd;CAEA,IAAW,cAAc;EACvB,OAAO,KAAK;CACd;CAEA,wBAA+B;EAC7B,OAAO;CACT;CAEA;CAEA,IAAW,eAAe;EAC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