@assistant-ui/core 0.2.15 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ import { DictationAdapter, SpeechSynthesisAdapter, WebSpeechDictationAdapter, We
11
11
  import { RealtimeVoiceAdapter, VoiceSessionControls, VoiceSessionHelpers, createVoiceSession } from "./adapters/voice.js";
12
12
  import { AssistantContextConfig, AssistantInstructionsConfig, AssistantToolProps, LanguageModelConfig, LanguageModelV1CallSettings, ModelContext, ModelContextProvider, mergeModelContexts } from "./model-context/types.js";
13
13
  import { ChatModelAdapter, ChatModelRunOptions, ChatModelRunResult, ChatModelRunUpdate, CoreChatModelRunResult } from "./runtime/utils/chat-model-adapter.js";
14
- import { ThreadMessageLike } from "./runtime/utils/thread-message-like.js";
14
+ import { ThreadMessageLike, fromThreadMessageLike } from "./runtime/utils/thread-message-like.js";
15
15
  import { ExportedMessageRepository, ExportedMessageRepositoryItem } from "./runtime/utils/message-repository.js";
16
16
  import { QuoteInfo } from "./types/quote.js";
17
17
  import { AttachmentAddErrorEvent, AttachmentAddErrorReason, ComposerRuntimeCore, ComposerRuntimeEventCallback, ComposerRuntimeEventPayload, ComposerRuntimeEventType, DictationState, EditComposerRuntimeCore, SendOptions, ThreadComposerRuntimeCore } from "./runtime/interfaces/composer-runtime-core.js";
@@ -29,6 +29,7 @@ import { FRAME_MESSAGE_CHANNEL, FrameMessage, FrameMessageType, SerializedModelC
29
29
  import { AttachmentRuntimePath, ComposerRuntimePath, MessagePartRuntimePath, MessageRuntimePath, ThreadListItemRuntimePath, ThreadRuntimePath } from "./runtime/api/paths.js";
30
30
  import { ThreadListItemCoreState, ThreadListItemStatus, ThreadListRuntimeCore } from "./runtime/interfaces/thread-list-runtime-core.js";
31
31
  import { AssistantRuntimeCore } from "./runtime/interfaces/assistant-runtime-core.js";
32
+ import { generateId } from "./utils/id.js";
32
33
  import { ThreadListItemState } from "./runtime/api/bindings.js";
33
34
  import { ThreadListItemEventCallback, ThreadListItemEventPayload, ThreadListItemEventType, ThreadListItemRuntime } from "./runtime/api/thread-list-item-runtime.js";
34
35
  import { ThreadListRuntime, ThreadListState } from "./runtime/api/thread-list-runtime.js";
@@ -48,4 +49,4 @@ import { ExternalThreadBranchAdapter } from "./runtime/branch/external-thread-br
48
49
  import { MessageQueueController, MessageQueueDriver, createMessageQueue } from "./runtime/queue/message-queue.js";
49
50
  import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
50
51
  import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
51
- 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 ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, type ExternalThreadBranchAdapter, type ExternalThreadQueueAdapter, 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 MessageQueueController, type MessageQueueDriver, 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 ToolApprovalOption, type ToolApprovalOptionKind, type ToolApprovalResponse, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolCallTiming, 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, createMessageQueue, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
52
+ 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 ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, type ExternalThreadBranchAdapter, type ExternalThreadQueueAdapter, 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 MessageQueueController, type MessageQueueDriver, 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 ToolApprovalOption, type ToolApprovalOptionKind, type ToolApprovalResponse, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolCallTiming, 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, createMessageQueue, createRequestHeaders, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
package/dist/index.js CHANGED
@@ -6,10 +6,12 @@ import { ModelContextRegistry } from "./model-context/registry.js";
6
6
  import { FRAME_MESSAGE_CHANNEL } from "./model-context/frame/types.js";
7
7
  import { AssistantFrameHost } from "./model-context/frame/host.js";
8
8
  import { AssistantFrameProvider } from "./model-context/frame/provider.js";
9
+ import { generateId } from "./utils/id.js";
9
10
  import { CompositeAttachmentAdapter, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter } from "./adapters/attachment.js";
10
11
  import { WebSpeechDictationAdapter, WebSpeechSynthesisAdapter } from "./adapters/speech.js";
11
12
  import { createVoiceSession } from "./adapters/voice.js";
12
13
  import { unstable_defaultDirectiveFormatter } from "./adapters/directive-formatter.js";
14
+ import { fromThreadMessageLike } from "./runtime/utils/thread-message-like.js";
13
15
  import { bindExternalStoreMessage, getExternalStoreMessages } from "./runtime/utils/external-store-message.js";
14
16
  import { ExportedMessageRepository } from "./runtime/utils/message-repository.js";
15
17
  import { pickExternalStoreSharedOptions } from "./runtimes/external-store/external-store-shared-options.js";
@@ -19,6 +21,6 @@ import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
19
21
  //#region src/index.ts
20
22
  if (process.env.NODE_ENV !== "production") checkDuplicateCore();
21
23
  //#endregion
22
- export { AssistantFrameHost, AssistantFrameProvider, CompositeAttachmentAdapter, ExportedMessageRepository, FRAME_MESSAGE_CHANNEL, InMemoryThreadListAdapter, MCP_APP_URI_SCHEME, ModelContextRegistry, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createVoiceSession, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
24
+ export { AssistantFrameHost, AssistantFrameProvider, CompositeAttachmentAdapter, ExportedMessageRepository, FRAME_MESSAGE_CHANNEL, InMemoryThreadListAdapter, MCP_APP_URI_SCHEME, ModelContextRegistry, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, tool, unstable_defaultDirectiveFormatter };
23
25
 
24
26
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["checkDuplicateCore","process","env","NODE_ENV","TextMessagePart","ReasoningMessagePart","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","ToolExecutionStatus","ModelContextRegistry","ModelContextRegistryToolHandle","ModelContextRegistryInstructionHandle","ModelContextRegistryProviderHandle","AssistantFrameHost","AssistantFrameProvider","SerializedTool","SerializedModelContext","FrameMessageType","FrameMessage","FRAME_MESSAGE_CHANNEL","AttachmentAdapter","SimpleImageAttachmentAdapter","SimpleTextAttachmentAdapter","CompositeAttachmentAdapter","SpeechSynthesisAdapter","DictationAdapter","WebSpeechSynthesisAdapter","WebSpeechDictationAdapter","RealtimeVoiceAdapter","createVoiceSession","VoiceSessionControls","VoiceSessionHelpers","FeedbackAdapter","SuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","RuntimeCapabilities","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","SubmitFeedbackOptions","ThreadSuggestion","SpeechState","VoiceSessionState","SubmittedFeedback","ThreadRuntimeEventCallback","ThreadRuntimeEventPayload","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ThreadRuntimeCore","ThreadListItemStatus","ThreadListItemCoreState","ThreadListRuntimeCore","AssistantRuntimeCore","AssistantRuntime","CreateStartRunConfig","CreateResumeRunConfig","CreateAppendMessage","ThreadState","ThreadRuntime","ThreadListState","ThreadListRuntime","ThreadListItemEventCallback","ThreadListItemEventPayload","ThreadListItemEventType","ThreadListItemRuntime","ThreadListItemState","MessageState","MessageRuntime","MessagePartState","MessagePartRuntime","ThreadComposerState","EditComposerState","ComposerState","ComposerRuntime","ThreadComposerRuntime","EditComposerRuntime","AttachmentState","AttachmentRuntime","ChatModelRunUpdate","ChatModelRunResult","CoreChatModelRunResult","ChatModelRunOptions","ChatModelAdapter","ThreadMessageLike","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RemoteThreadListOptions","RemoteThreadInitializeResponse","RemoteThreadMetadata","RemoteThreadListResponse","RemoteThreadListPageOptions","InMemoryThreadListAdapter","createRequestHeaders"],"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 ToolApprovalOption,\n ToolApprovalOptionKind,\n ToolApprovalResponse,\n ToolCallMessagePart,\n ToolCallTiming,\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\";\nexport type { ExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\nexport { pickExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\n\n// Message queue\nexport type { ExternalThreadQueueAdapter } from \"./runtime/queue/external-thread-queue-adapter\";\nexport type { ExternalThreadBranchAdapter } from \"./runtime/branch/external-thread-branch-adapter\";\nexport {\n createMessageQueue,\n type MessageQueueDriver,\n type MessageQueueController,\n} from \"./runtime/queue/message-queue\";\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,IAAIC,QAAQC,IAAIC,aAAa,cAC3BH,mBAAmB"}
1
+ {"version":3,"file":"index.js","names":["checkDuplicateCore","process","env","NODE_ENV","TextMessagePart","ReasoningMessagePart","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","ToolExecutionStatus","ModelContextRegistry","ModelContextRegistryToolHandle","ModelContextRegistryInstructionHandle","ModelContextRegistryProviderHandle","AssistantFrameHost","AssistantFrameProvider","SerializedTool","SerializedModelContext","FrameMessageType","FrameMessage","FRAME_MESSAGE_CHANNEL","AttachmentAdapter","SimpleImageAttachmentAdapter","SimpleTextAttachmentAdapter","CompositeAttachmentAdapter","SpeechSynthesisAdapter","DictationAdapter","WebSpeechSynthesisAdapter","WebSpeechDictationAdapter","RealtimeVoiceAdapter","createVoiceSession","VoiceSessionControls","VoiceSessionHelpers","FeedbackAdapter","SuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","RuntimeCapabilities","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","SubmitFeedbackOptions","ThreadSuggestion","SpeechState","VoiceSessionState","SubmittedFeedback","ThreadRuntimeEventCallback","ThreadRuntimeEventPayload","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ThreadRuntimeCore","ThreadListItemStatus","ThreadListItemCoreState","ThreadListRuntimeCore","AssistantRuntimeCore","AssistantRuntime","CreateStartRunConfig","CreateResumeRunConfig","CreateAppendMessage","ThreadState","ThreadRuntime","ThreadListState","ThreadListRuntime","ThreadListItemEventCallback","ThreadListItemEventPayload","ThreadListItemEventType","ThreadListItemRuntime","ThreadListItemState","MessageState","MessageRuntime","MessagePartState","MessagePartRuntime","ThreadComposerState","EditComposerState","ComposerState","ComposerRuntime","ThreadComposerRuntime","EditComposerRuntime","AttachmentState","AttachmentRuntime","ChatModelRunUpdate","ChatModelRunResult","CoreChatModelRunResult","ChatModelRunOptions","ChatModelAdapter","ThreadMessageLike","fromThreadMessageLike","generateId","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RemoteThreadListOptions","RemoteThreadInitializeResponse","RemoteThreadMetadata","RemoteThreadListResponse","RemoteThreadListPageOptions","InMemoryThreadListAdapter","createRequestHeaders"],"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 ToolApprovalOption,\n ToolApprovalOptionKind,\n ToolApprovalResponse,\n ToolCallMessagePart,\n ToolCallTiming,\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\";\nexport { fromThreadMessageLike } from \"./runtime/utils/thread-message-like\";\n\n// ID generation\nexport { generateId } from \"./utils/id\";\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\";\nexport type { ExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\nexport { pickExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\n\n// Message queue\nexport type { ExternalThreadQueueAdapter } from \"./runtime/queue/external-thread-queue-adapter\";\nexport type { ExternalThreadBranchAdapter } from \"./runtime/branch/external-thread-branch-adapter\";\nexport {\n createMessageQueue,\n type MessageQueueDriver,\n type MessageQueueController,\n} from \"./runtime/queue/message-queue\";\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,IAAIC,QAAQC,IAAIC,aAAa,cAC3BH,mBAAmB"}
package/dist/internal.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { generateErrorMessageId, generateId, isErrorMessageId } from "./utils/id.js";
2
+ import { fromThreadMessageLike } from "./runtime/utils/thread-message-like.js";
2
3
  import { symbolInnerMessage } from "./runtime/utils/external-store-message.js";
3
4
  import { getAutoStatus, isAutoStatus } from "./runtime/utils/auto-status.js";
4
- import { fromThreadMessageLike } from "./runtime/utils/thread-message-like.js";
5
5
  import { ExportedMessageRepository, MessageRepository } from "./runtime/utils/message-repository.js";
6
6
  import { getThreadMessageText } from "./utils/text.js";
7
7
  import { BaseSubject, BaseSubscribable, EventSubscriptionSubject, LazyMemoizeSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "./subscribable/subscribable.js";
@@ -1,4 +1,4 @@
1
- import { ToolCallMessagePartComponent } from "../types/MessagePartComponentTypes.js";
1
+ import { ToolCallMessagePartComponent, ToolCallMessagePartProps } from "../types/MessagePartComponentTypes.js";
2
2
  import { Tool, ToolCallReader, ToolDeclaration, ToolModelOutputFunction } from "assistant-stream";
3
3
  import { ReactNode } from "react";
4
4
 
@@ -46,7 +46,7 @@ type ToolCallText<TArgs extends Record<string, unknown>, TResult> = {
46
46
  running?: ToolCallRunningText<TArgs> | undefined;
47
47
  complete: ToolCallCompleteText<TArgs, TResult>;
48
48
  };
49
- declare const makeToolCallTextComponent: <TArgs extends Record<string, unknown>, TResult>(text: ToolCallText<TArgs, TResult>) => ToolCallMessagePartComponent<TArgs, TResult>;
49
+ declare const makeToolCallTextComponent: <TArgs extends Record<string, unknown>, TResult>(text: ToolCallText<TArgs, TResult>) => ((part: ToolCallMessagePartProps<TArgs, TResult>) => ReactNode);
50
50
  /**
51
51
  * Tool definition accepted by the React tool registry.
52
52
  *
@@ -89,7 +89,7 @@ type OverrideToolDeclarationCallbacks<T extends {
89
89
  streamCall?: unknown;
90
90
  }, TArgs extends Record<string, unknown>, TResult> = Omit<T, "type" | "execute" | "toModelOutput" | "experimental_onSchemaValidationError" | "streamCall"> & {
91
91
  type?: never;
92
- } & ("execute" extends keyof T ? OverrideOptionalField<T, "execute", ToolExecute<NoInfer<TArgs>, TResult>> : {}) & ("toModelOutput" extends keyof T ? OverrideOptionalField<T, "toModelOutput", ToolModelOutputFunction<NoInfer<TArgs>, NoInfer<TResult>>> : {}) & ("experimental_onSchemaValidationError" extends keyof T ? OverrideOptionalField<T, "experimental_onSchemaValidationError", (args: unknown, context: ToolExecuteContext) => NoInfer<TResult> | Promise<NoInfer<TResult>>> : {}) & OverrideOptionalField<T, "streamCall", ToolStreamCall<TArgs, NoInfer<TResult>>>;
92
+ } & ("execute" extends keyof T ? OverrideOptionalField<T, "execute", ToolExecute<NoInfer<TArgs>, TResult>> : {}) & ("toModelOutput" extends keyof T ? OverrideOptionalField<T, "toModelOutput", ToolModelOutputFunction<NoInfer<TArgs>, NoInfer<TResult>>> : {}) & ("experimental_onSchemaValidationError" extends keyof T ? OverrideOptionalField<T, "experimental_onSchemaValidationError", (args: unknown, context: ToolExecuteContext) => NoInfer<TResult> | Promise<NoInfer<TResult>>> : {}) & OverrideOptionalField<T, "streamCall", ToolStreamCall<TArgs, unknown>>;
93
93
  type ToolkitDefinitionInput<TArgs extends Record<string, unknown>, TResult> = WithRender<ToolDeclaration<TArgs, TResult> extends infer T ? T extends {
94
94
  streamCall?: unknown;
95
95
  } ? OverrideToolDeclarationCallbacks<T, TArgs, TResult> : never : never, TArgs, TResult>;
@@ -1 +1 @@
1
- {"version":3,"file":"toolbox.d.ts","names":[],"sources":["../../../src/react/model-context/toolbox.ts"],"mappings":";;;;;;;AAqBA;;;;;;;cAAa,uBAAA,GACX,IAAA,EAAM,IAAI,CAAC,IAAA;AAAA,KAMR,UAAA,kBAA4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,0CAErC,CAAA,GAC3B,qBAAA,CACE,CAAA,mBAEA,uBAAA,CAAwB,OAAA,CAAQ,KAAA,GAAQ,OAAA,CAAQ,OAAA,kEAGA,CAAA,GAClD,qBAAA,CACE,CAAA,2CAGE,IAAA,WACA,OAAA,EAAS,kBAAA,KACN,OAAA,CAAQ,OAAA,IAAW,OAAA,CAAQ,OAAA,CAAQ,OAAA,YAG9C,qBAAA,CAAsB,CAAA,gBAAiB,cAAA,CAAe,KAAA;AAAA,KAInD,sBAAA,eACW,MAAA,8BAEZ,UAAA,CACF,eAAA,CAAgB,KAAA,EAAO,OAAA,oBACnB,CAAA;EAAY,UAAA;AAAA,IACV,gCAAA,CAAiC,CAAA,EAAG,KAAA,EAAO,OAAA,mBAGjD,KAAA,EACA,OAAA;;;;;;AAjK2B;AAAA;;;KA6KjB,sBAAA,eACI,MAAA,oBAA0B,MAAA,wCAEtC,sBAAA,CAAuB,KAAA,EAAO,OAAA,IAAW,cAAA;AAAA,KAEjC,oCAAA,eACI,MAAA,oBAA0B,MAAA,wCAEtC,sBAAA,CAAuB,KAAA,EAAO,OAAA;EAChC,UAAA,EAAY,WAAA,CAAY,cAAA,CAAe,KAAA;AAAA;;;;;;KAQ7B,iBAAA,mCAEI,WAAA,GAAc,MAAA,sBACxB,MAAA,mDACgC,WAAA,6BACtB,WAAA,0BAGF,WAAA,GAAc,sBAAA,CACxB,WAAA,CAAY,CAAA,GACZ,aAAA,CAAc,CAAA;;KAKN,WAAA;EArMP,kFAuMH,OAAA,EAAS,OAAO;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"toolbox.js","names":["Tool","ToolCallReader","ToolDeclaration","ToolModelOutputFunction","ReactNode","ToolCallMessagePartComponent","ToolCallMessagePartProps","isStandaloneToolDisplay","tool","Pick","display","undefined","type","WithRender","Record","T","render","TArgs","TResult","renderText","ToolCallText","ToolParameters","ToolExecuteContext","Parameters","NonNullable","ToolExecute","args","context","Promise","ToolStreamCall","reader","ToolCallRunningText","options","ToolCallCompleteText","result","running","complete","resolveToolCallText","text","part","isRunning","status","value","makeToolCallTextComponent","ToolCallTextComponent","ToolDefinition","Toolkit","OverrideOptionalField","TKey","Exclude","TValue","OverrideToolDeclarationCallbacks","streamCall","Omit","NoInfer","ToolkitDefinitionInput","ToolkitDefinitionEntry","ToolkitDefinitionEntryWithParameters","parameters","ToolkitDefinition","TArgsByName","K","TResultByName","ToolsConfig","toolkit"],"sources":["../../../src/react/model-context/toolbox.ts"],"sourcesContent":["import type {\n Tool,\n ToolCallReader,\n ToolDeclaration,\n ToolModelOutputFunction,\n} from \"assistant-stream\";\nimport type { ReactNode } from \"react\";\nimport type {\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n} from \"../types/MessagePartComponentTypes\";\n\n/**\n * Resolves whether a tool's UI should be presented standalone (outside the\n * chain-of-thought grouping), applying the type-based defaults.\n *\n * An explicit `display` wins. Otherwise `human` tools default to standalone\n * (they prompt the user), and every other tool defaults to inline (a trace of\n * what the model is doing). MCP-app tool calls are detected separately from\n * the part itself and are not resolved here.\n */\nexport const isStandaloneToolDisplay = (\n tool: Pick<Tool<any, any>, \"type\" | \"display\">,\n): boolean => {\n if (tool.display !== undefined) return tool.display === \"standalone\";\n return tool.type === \"human\";\n};\n\ntype WithRender<T, TArgs extends Record<string, unknown>, TResult> = T extends {\n type: \"frontend\" | \"human\";\n}\n ? T &\n (T extends { type: \"frontend\" }\n ?\n | { render: ToolCallMessagePartComponent<TArgs, TResult> }\n | {\n render?: ToolCallMessagePartComponent<TArgs, TResult>;\n renderText: ToolCallText<TArgs, TResult>;\n }\n : { render: ToolCallMessagePartComponent<TArgs, TResult> })\n : T & {\n render?: ToolCallMessagePartComponent<TArgs, TResult> | undefined;\n renderText?: ToolCallText<TArgs, TResult> | undefined;\n };\n\ntype ToolParameters<TArgs extends Record<string, unknown>> =\n ToolDeclaration<TArgs>[\"parameters\"];\n\n// ToolExecutionContext is not re-exported from assistant-stream's public entry.\ntype ToolExecuteContext = Parameters<\n NonNullable<ToolDeclaration[\"execute\"]>\n>[1];\n\ntype ToolExecute<TArgs extends Record<string, unknown>, TResult> = (\n args: TArgs,\n context: ToolExecuteContext,\n) => TResult | Promise<TResult>;\n\ntype ToolStreamCall<TArgs extends Record<string, unknown>, TResult> = (\n reader: ToolCallReader<TArgs, TResult>,\n context: ToolExecuteContext,\n) => void;\n\ntype ToolCallRunningText<TArgs extends Record<string, unknown>> =\n | ReactNode\n | ((options: { args: TArgs }) => ReactNode);\n\ntype ToolCallCompleteText<TArgs extends Record<string, unknown>, TResult> =\n | ReactNode\n | ((options: { args: TArgs; result: TResult | undefined }) => ReactNode);\n\nexport type ToolCallText<TArgs extends Record<string, unknown>, TResult> =\n | {\n running: ToolCallRunningText<TArgs>;\n complete?: ToolCallCompleteText<TArgs, TResult> | undefined;\n }\n | {\n running?: ToolCallRunningText<TArgs> | undefined;\n complete: ToolCallCompleteText<TArgs, TResult>;\n };\n\nconst resolveToolCallText = <TArgs extends Record<string, unknown>, TResult>(\n text: ToolCallText<TArgs, TResult>,\n part: ToolCallMessagePartProps<TArgs, TResult>,\n): ReactNode => {\n const isRunning =\n part.status?.type === \"running\" || part.status?.type === \"requires-action\";\n\n if (!isRunning) {\n const value = text.complete;\n if (typeof value !== \"function\") return value ?? null;\n return value({ args: part.args, result: part.result });\n }\n\n const value = text.running;\n if (typeof value !== \"function\") return value ?? null;\n return value({ args: part.args });\n};\n\nexport const makeToolCallTextComponent = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n text: ToolCallText<TArgs, TResult>,\n): ToolCallMessagePartComponent<TArgs, TResult> => {\n return function ToolCallTextComponent(part) {\n return resolveToolCallText(text, part);\n };\n};\n\n/**\n * Tool definition accepted by the React tool registry.\n *\n * Extends the core tool contract with tool-call display options. Human tools\n * rely on `render` to collect input from the user. Frontend tools execute in\n * the browser and require either `render` or `renderText` for their progress\n * and result. Backend tools execute server-side and may omit a renderer.\n */\nexport type ToolDefinition<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = WithRender<Tool<TArgs, TResult>, TArgs, TResult>;\n\n/**\n * Named collection of tools exposed to the assistant model.\n *\n * Keys are the tool names the model receives and uses in tool calls.\n *\n * @example\n * ```tsx\n * const toolkit = defineToolkit({\n * get_weather: {\n * type: \"frontend\",\n * description: \"Get the weather for a city.\",\n * parameters: weatherSchema,\n * execute: async ({ city }: { city: string }) => fetchWeather(city),\n * render: WeatherToolUI,\n * },\n * });\n * ```\n */\nexport type Toolkit = Record<string, ToolDefinition<any, any>>;\n\n/**\n * A tool as authored, before the build splits it: like {@link ToolDefinition}\n * but it may declare `description`, `parameters`, and a server-side `execute`\n * alongside its `render`. The `type` field is **not** authored — the\n * `\"use generative\"` compiler infers it (`execute: humanTool()` → human;\n * `execute: providerTool(...)` → provider; `execute` with a `\"use client\"`\n * directive → frontend; otherwise backend) and writes it back — so declaring it\n * here is a type error.\n */\ntype OverrideOptionalField<\n T,\n TKey extends keyof T,\n TValue,\n> = undefined extends T[TKey]\n ? // Preserve `?: undefined` fields (for variants that explicitly disallow a\n // callback) instead of widening them to accept the override value.\n Exclude<T[TKey], undefined> extends never\n ? { [K in TKey]?: undefined }\n : { [K in TKey]?: TValue | undefined }\n : { [K in TKey]: TValue };\n\ntype OverrideToolDeclarationCallbacks<\n T extends { streamCall?: unknown },\n TArgs extends Record<string, unknown>,\n TResult,\n> = Omit<\n T,\n | \"type\"\n | \"execute\"\n | \"toModelOutput\"\n | \"experimental_onSchemaValidationError\"\n | \"streamCall\"\n> & {\n type?: never;\n} & (\"execute\" extends keyof T\n ? OverrideOptionalField<T, \"execute\", ToolExecute<NoInfer<TArgs>, TResult>>\n : {}) &\n (\"toModelOutput\" extends keyof T\n ? OverrideOptionalField<\n T,\n \"toModelOutput\",\n ToolModelOutputFunction<NoInfer<TArgs>, NoInfer<TResult>>\n >\n : {}) &\n (\"experimental_onSchemaValidationError\" extends keyof T\n ? OverrideOptionalField<\n T,\n \"experimental_onSchemaValidationError\",\n (\n args: unknown,\n context: ToolExecuteContext,\n ) => NoInfer<TResult> | Promise<NoInfer<TResult>>\n >\n : {}) &\n OverrideOptionalField<\n T,\n \"streamCall\",\n ToolStreamCall<TArgs, NoInfer<TResult>>\n >;\n\n// Keep the authored shape tied to ToolDeclaration's union variants while\n// overriding callback fields to avoid inference pollution.\ntype ToolkitDefinitionInput<\n TArgs extends Record<string, unknown>,\n TResult,\n> = WithRender<\n ToolDeclaration<TArgs, TResult> extends infer T\n ? T extends { streamCall?: unknown }\n ? OverrideToolDeclarationCallbacks<T, TArgs, TResult>\n : never\n : never,\n TArgs,\n TResult\n>;\n\n/**\n * A single entry in a {@link ToolkitDefinition}.\n *\n * Either authored inline (whose `type` the compiler infers) or an already-formed\n * {@link ToolDefinition} produced by a factory whose own build splits it across\n * targets — e.g. `new JSONGenerativeUI({ library }).present()`. The factory case\n * carries a `type`, so it can only match the {@link ToolDefinition} arm of this\n * union.\n */\nexport type ToolkitDefinitionEntry<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = ToolkitDefinitionInput<TArgs, TResult> | ToolDefinition<any, any>;\n\nexport type ToolkitDefinitionEntryWithParameters<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = ToolkitDefinitionInput<TArgs, TResult> & {\n parameters: NonNullable<ToolParameters<TArgs>>;\n};\n\n/**\n * The permissive, authoring-time counterpart to {@link Toolkit} — the input to\n * {@link defineToolkit}. Backend entries may carry their server `execute` here;\n * the canonical {@link Toolkit} keeps those fields `undefined`.\n */\nexport type ToolkitDefinition<\n TArgsByName extends {\n [K in keyof TArgsByName]: Record<string, unknown>;\n } = Record<string, any>,\n TResultByName extends { [K in keyof TArgsByName]: unknown } = {\n [K in keyof TArgsByName]: any;\n },\n> = {\n [K in keyof TArgsByName]: ToolkitDefinitionEntry<\n TArgsByName[K],\n TResultByName[K]\n >;\n};\n\n/** Configuration for the {@link Tools} resource. */\nexport type ToolsConfig = {\n /** Tools to register with model context and, when provided, message renderers. */\n toolkit: Toolkit;\n};\n"],"mappings":";;;;;;;;;;AAqBA,MAAaO,2BACXC,SACY;CACZ,IAAIA,KAAKE,YAAYC,KAAAA,GAAW,OAAOH,KAAKE,YAAY;CACxD,OAAOF,KAAKI,SAAS;AACvB;AAuDA,MAAMyB,uBACJC,MACAC,SACc;CAId,IAAI,EAFFA,KAAKE,QAAQ7B,SAAS,aAAa2B,KAAKE,QAAQ7B,SAAS,oBAE3C;EACd,MAAM8B,QAAQJ,KAAKF;EACnB,IAAI,OAAOM,UAAU,YAAY,OAAOA,SAAS;EACjD,OAAOA,MAAM;GAAEhB,MAAMa,KAAKb;GAAMQ,QAAQK,KAAKL;EAAO,CAAC;CACvD;CAEA,MAAMQ,QAAQJ,KAAKH;CACnB,IAAI,OAAOO,UAAU,YAAY,OAAOA,SAAS;CACjD,OAAOA,MAAM,EAAEhB,MAAMa,KAAKb,KAAK,CAAC;AAClC;AAEA,MAAaiB,6BAIXL,SACiD;CACjD,OAAO,SAASM,sBAAsBL,MAAM;EAC1C,OAAOF,oBAAoBC,MAAMC,IAAI;CACvC;AACF"}
1
+ {"version":3,"file":"toolbox.js","names":["Tool","ToolCallReader","ToolDeclaration","ToolModelOutputFunction","ReactNode","ToolCallMessagePartComponent","ToolCallMessagePartProps","isStandaloneToolDisplay","tool","Pick","display","undefined","type","WithRender","Record","T","render","TArgs","TResult","renderText","ToolCallText","ToolParameters","ToolExecuteContext","Parameters","NonNullable","ToolExecute","args","context","Promise","ToolStreamCall","reader","ToolCallRunningText","options","ToolCallCompleteText","result","running","complete","resolveToolCallText","text","part","isRunning","status","value","makeToolCallTextComponent","ToolCallTextComponent","ToolDefinition","Toolkit","OverrideOptionalField","TKey","Exclude","TValue","OverrideToolDeclarationCallbacks","streamCall","Omit","NoInfer","ToolkitDefinitionInput","ToolkitDefinitionEntry","ToolkitDefinitionEntryWithParameters","parameters","ToolkitDefinition","TArgsByName","K","TResultByName","ToolsConfig","toolkit"],"sources":["../../../src/react/model-context/toolbox.ts"],"sourcesContent":["import type {\n Tool,\n ToolCallReader,\n ToolDeclaration,\n ToolModelOutputFunction,\n} from \"assistant-stream\";\nimport type { ReactNode } from \"react\";\nimport type {\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n} from \"../types/MessagePartComponentTypes\";\n\n/**\n * Resolves whether a tool's UI should be presented standalone (outside the\n * chain-of-thought grouping), applying the type-based defaults.\n *\n * An explicit `display` wins. Otherwise `human` tools default to standalone\n * (they prompt the user), and every other tool defaults to inline (a trace of\n * what the model is doing). MCP-app tool calls are detected separately from\n * the part itself and are not resolved here.\n */\nexport const isStandaloneToolDisplay = (\n tool: Pick<Tool<any, any>, \"type\" | \"display\">,\n): boolean => {\n if (tool.display !== undefined) return tool.display === \"standalone\";\n return tool.type === \"human\";\n};\n\ntype WithRender<T, TArgs extends Record<string, unknown>, TResult> = T extends {\n type: \"frontend\" | \"human\";\n}\n ? T &\n (T extends { type: \"frontend\" }\n ?\n | { render: ToolCallMessagePartComponent<TArgs, TResult> }\n | {\n render?: ToolCallMessagePartComponent<TArgs, TResult>;\n renderText: ToolCallText<TArgs, TResult>;\n }\n : { render: ToolCallMessagePartComponent<TArgs, TResult> })\n : T & {\n render?: ToolCallMessagePartComponent<TArgs, TResult> | undefined;\n renderText?: ToolCallText<TArgs, TResult> | undefined;\n };\n\ntype ToolParameters<TArgs extends Record<string, unknown>> =\n ToolDeclaration<TArgs>[\"parameters\"];\n\n// ToolExecutionContext is not re-exported from assistant-stream's public entry.\ntype ToolExecuteContext = Parameters<\n NonNullable<ToolDeclaration[\"execute\"]>\n>[1];\n\ntype ToolExecute<TArgs extends Record<string, unknown>, TResult> = (\n args: TArgs,\n context: ToolExecuteContext,\n) => TResult | Promise<TResult>;\n\ntype ToolStreamCall<TArgs extends Record<string, unknown>, TResult> = (\n reader: ToolCallReader<TArgs, TResult>,\n context: ToolExecuteContext,\n) => void;\n\ntype ToolCallRunningText<TArgs extends Record<string, unknown>> =\n | ReactNode\n | ((options: { args: TArgs }) => ReactNode);\n\ntype ToolCallCompleteText<TArgs extends Record<string, unknown>, TResult> =\n | ReactNode\n | ((options: { args: TArgs; result: TResult | undefined }) => ReactNode);\n\nexport type ToolCallText<TArgs extends Record<string, unknown>, TResult> =\n | {\n running: ToolCallRunningText<TArgs>;\n complete?: ToolCallCompleteText<TArgs, TResult> | undefined;\n }\n | {\n running?: ToolCallRunningText<TArgs> | undefined;\n complete: ToolCallCompleteText<TArgs, TResult>;\n };\n\nconst resolveToolCallText = <TArgs extends Record<string, unknown>, TResult>(\n text: ToolCallText<TArgs, TResult>,\n part: ToolCallMessagePartProps<TArgs, TResult>,\n): ReactNode => {\n const isRunning =\n part.status?.type === \"running\" || part.status?.type === \"requires-action\";\n\n if (!isRunning) {\n const value = text.complete;\n if (typeof value !== \"function\") return value ?? null;\n return value({ args: part.args, result: part.result });\n }\n\n const value = text.running;\n if (typeof value !== \"function\") return value ?? null;\n return value({ args: part.args });\n};\n\nexport const makeToolCallTextComponent = <\n TArgs extends Record<string, unknown>,\n TResult,\n>(\n text: ToolCallText<TArgs, TResult>,\n): ((part: ToolCallMessagePartProps<TArgs, TResult>) => ReactNode) => {\n return function ToolCallTextComponent(part) {\n return resolveToolCallText(text, part);\n };\n};\n\n/**\n * Tool definition accepted by the React tool registry.\n *\n * Extends the core tool contract with tool-call display options. Human tools\n * rely on `render` to collect input from the user. Frontend tools execute in\n * the browser and require either `render` or `renderText` for their progress\n * and result. Backend tools execute server-side and may omit a renderer.\n */\nexport type ToolDefinition<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = WithRender<Tool<TArgs, TResult>, TArgs, TResult>;\n\n/**\n * Named collection of tools exposed to the assistant model.\n *\n * Keys are the tool names the model receives and uses in tool calls.\n *\n * @example\n * ```tsx\n * const toolkit = defineToolkit({\n * get_weather: {\n * type: \"frontend\",\n * description: \"Get the weather for a city.\",\n * parameters: weatherSchema,\n * execute: async ({ city }: { city: string }) => fetchWeather(city),\n * render: WeatherToolUI,\n * },\n * });\n * ```\n */\nexport type Toolkit = Record<string, ToolDefinition<any, any>>;\n\n/**\n * A tool as authored, before the build splits it: like {@link ToolDefinition}\n * but it may declare `description`, `parameters`, and a server-side `execute`\n * alongside its `render`. The `type` field is **not** authored — the\n * `\"use generative\"` compiler infers it (`execute: humanTool()` → human;\n * `execute: providerTool(...)` → provider; `execute` with a `\"use client\"`\n * directive → frontend; otherwise backend) and writes it back — so declaring it\n * here is a type error.\n */\ntype OverrideOptionalField<\n T,\n TKey extends keyof T,\n TValue,\n> = undefined extends T[TKey]\n ? // Preserve `?: undefined` fields (for variants that explicitly disallow a\n // callback) instead of widening them to accept the override value.\n Exclude<T[TKey], undefined> extends never\n ? { [K in TKey]?: undefined }\n : { [K in TKey]?: TValue | undefined }\n : { [K in TKey]: TValue };\n\ntype OverrideToolDeclarationCallbacks<\n T extends { streamCall?: unknown },\n TArgs extends Record<string, unknown>,\n TResult,\n> = Omit<\n T,\n | \"type\"\n | \"execute\"\n | \"toModelOutput\"\n | \"experimental_onSchemaValidationError\"\n | \"streamCall\"\n> & {\n type?: never;\n} & (\"execute\" extends keyof T\n ? OverrideOptionalField<T, \"execute\", ToolExecute<NoInfer<TArgs>, TResult>>\n : {}) &\n (\"toModelOutput\" extends keyof T\n ? OverrideOptionalField<\n T,\n \"toModelOutput\",\n ToolModelOutputFunction<NoInfer<TArgs>, NoInfer<TResult>>\n >\n : {}) &\n (\"experimental_onSchemaValidationError\" extends keyof T\n ? OverrideOptionalField<\n T,\n \"experimental_onSchemaValidationError\",\n (\n args: unknown,\n context: ToolExecuteContext,\n ) => NoInfer<TResult> | Promise<NoInfer<TResult>>\n >\n : {}) &\n OverrideOptionalField<T, \"streamCall\", ToolStreamCall<TArgs, unknown>>;\n\n// Keep the authored shape tied to ToolDeclaration's union variants while\n// overriding callback fields to avoid inference pollution.\ntype ToolkitDefinitionInput<\n TArgs extends Record<string, unknown>,\n TResult,\n> = WithRender<\n ToolDeclaration<TArgs, TResult> extends infer T\n ? T extends { streamCall?: unknown }\n ? OverrideToolDeclarationCallbacks<T, TArgs, TResult>\n : never\n : never,\n TArgs,\n TResult\n>;\n\n/**\n * A single entry in a {@link ToolkitDefinition}.\n *\n * Either authored inline (whose `type` the compiler infers) or an already-formed\n * {@link ToolDefinition} produced by a factory whose own build splits it across\n * targets — e.g. `new JSONGenerativeUI({ library }).present()`. The factory case\n * carries a `type`, so it can only match the {@link ToolDefinition} arm of this\n * union.\n */\nexport type ToolkitDefinitionEntry<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = ToolkitDefinitionInput<TArgs, TResult> | ToolDefinition<any, any>;\n\nexport type ToolkitDefinitionEntryWithParameters<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = ToolkitDefinitionInput<TArgs, TResult> & {\n parameters: NonNullable<ToolParameters<TArgs>>;\n};\n\n/**\n * The permissive, authoring-time counterpart to {@link Toolkit} — the input to\n * {@link defineToolkit}. Backend entries may carry their server `execute` here;\n * the canonical {@link Toolkit} keeps those fields `undefined`.\n */\nexport type ToolkitDefinition<\n TArgsByName extends {\n [K in keyof TArgsByName]: Record<string, unknown>;\n } = Record<string, any>,\n TResultByName extends { [K in keyof TArgsByName]: unknown } = {\n [K in keyof TArgsByName]: any;\n },\n> = {\n [K in keyof TArgsByName]: ToolkitDefinitionEntry<\n TArgsByName[K],\n TResultByName[K]\n >;\n};\n\n/** Configuration for the {@link Tools} resource. */\nexport type ToolsConfig = {\n /** Tools to register with model context and, when provided, message renderers. */\n toolkit: Toolkit;\n};\n"],"mappings":";;;;;;;;;;AAqBA,MAAaO,2BACXC,SACY;CACZ,IAAIA,KAAKE,YAAYC,KAAAA,GAAW,OAAOH,KAAKE,YAAY;CACxD,OAAOF,KAAKI,SAAS;AACvB;AAuDA,MAAMyB,uBACJC,MACAC,SACc;CAId,IAAI,EAFFA,KAAKE,QAAQ7B,SAAS,aAAa2B,KAAKE,QAAQ7B,SAAS,oBAE3C;EACd,MAAM8B,QAAQJ,KAAKF;EACnB,IAAI,OAAOM,UAAU,YAAY,OAAOA,SAAS;EACjD,OAAOA,MAAM;GAAEhB,MAAMa,KAAKb;GAAMQ,QAAQK,KAAKL;EAAO,CAAC;CACvD;CAEA,MAAMQ,QAAQJ,KAAKH;CACnB,IAAI,OAAOO,UAAU,YAAY,OAAOA,SAAS;CACjD,OAAOA,MAAM,EAAEhB,MAAMa,KAAKb,KAAK,CAAC;AAClC;AAEA,MAAaiB,6BAIXL,SACoE;CACpE,OAAO,SAASM,sBAAsBL,MAAM;EAC1C,OAAOF,oBAAoBC,MAAMC,IAAI;CACvC;AACF"}
@@ -1,8 +1,8 @@
1
1
  "use client";
2
2
  import { generateErrorMessageId } from "../../utils/id.js";
3
+ import { fromThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
3
4
  import { bindExternalStoreMessage, getExternalStoreMessages, symbolInnerMessage } from "../../runtime/utils/external-store-message.js";
4
5
  import { getAutoStatus, isAutoStatus } from "../../runtime/utils/auto-status.js";
5
- import { fromThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
6
6
  import { ThreadMessageConverter } from "../../runtimes/external-store/thread-message-converter.js";
7
7
  import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
8
8
  //#region src/react/runtimes/external-message-converter.ts
@@ -1,6 +1,6 @@
1
+ import { fromThreadMessageLike } from "./utils/thread-message-like.js";
1
2
  import { symbolInnerMessage } from "./utils/external-store-message.js";
2
3
  import { getAutoStatus, isAutoStatus } from "./utils/auto-status.js";
3
- import { fromThreadMessageLike } from "./utils/thread-message-like.js";
4
4
  import { ExportedMessageRepository, MessageRepository } from "./utils/message-repository.js";
5
5
  import { BaseAssistantRuntimeCore } from "./base/base-assistant-runtime-core.js";
6
6
  import { BaseComposerRuntimeCore } from "./base/base-composer-runtime-core.js";
@@ -1,6 +1,6 @@
1
1
  import { generateId } from "../../utils/id.js";
2
- import { getAutoStatus } from "./auto-status.js";
3
2
  import { fromThreadMessageLike } from "./thread-message-like.js";
3
+ import { getAutoStatus } from "./auto-status.js";
4
4
  //#region src/runtime/utils/message-repository.ts
5
5
  const ExportedMessageRepository = {
6
6
  fromArray: (messages) => {
@@ -1 +1 @@
1
- {"version":3,"file":"external-store-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;cA+Ca,kBAAA,GACX,SAAA,WACA,QAAA,WAAmB,aAAa;AAAA,cAKrB,8BAAA,SACH,qBAAA,YACG,iBAAA;EAAA,QAEH,aAAA;EAAA,IAgBG,YAAA,IAAY,mBAAA;EAAA,QAIf,SAAA;EACD,UAAA;EACA,cAAA;EAAA,IACI,SAAA;EAAA,IAIA,SAAA;EAAA,UAIQ,gBAAA,aAA6B,aAAA;EAAA,IAI5B,KAAA,iEAAK,kBAAA,oCAAA,iBAAA;EAAA,IAId,QAAA;kBARkD,iBAAA;;;;;;;EAYtD,WAAA,WAAsB,gBAAA;EACtB,MAAA;EAAA,QAEC,UAAA;EAAA,QAEA,MAAA;;;;;UAMA,gBAAA;EAEQ,SAAA,CAAU,SAAA;cAQxB,eAAA,EAAiB,oBAAA,EACjB,KAAA,EAAO,oBAAA;EAMF,qBAAA,CAAsB,KAAA,EAAO,oBAAA;EAAA;;;;;;EAAA,QA8J5B,qBAAA;EA0LuB;;;;EAAA,QAvHvB,oBAAA;EAAA,QACA,yBAAA;EAuOqB;;;;;;EAAA,QA/NrB,yBAAA;EAmBQ,cAAA,CAAe,QAAA;EAalB,MAAA,CAAO,OAAA,EAAS,aAAA,GAAgB,OAAA;EA8BhC,aAAA,CAAc,SAAA,WAAoB,OAAA;EAoBxC,aAAA,aApB+C,cAAA;EA0B/C,cAAA,CAAe,WAAA;EAIf,eAAA,CAAgB,WAAA;EAIV,QAAA,CAAS,MAAA,EAAQ,cAAA,GAAiB,OAAA;EAclC,SAAA,CAAU,MAAA,EAAQ,eAAA,GAAkB,OAAA;EAO1C,mBAAA;EAOA,mBAAA,CAAoB,KAAA;EAmBpB,SAAA;EA0CA,aAAA,CAAc,OAAA,EAAS,oBAAA;EAMvB,cAAA,CAAe,OAAA,EAAS,qBAAA;EAoBxB,qBAAA,CAAsB,OAAA,EAAS,4BAAA;EAMtB,KAAA,CAAM,eAAA,YAA2B,iBAAA;EAMjC,MAAA,CAAO,IAAA,EAAM,yBAAA;EAAA,QAQrB,cAAA;AAAA"}
1
+ {"version":3,"file":"external-store-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;cA+Ca,kBAAA,GACX,SAAA,WACA,QAAA,WAAmB,aAAa;AAAA,cAKrB,8BAAA,SACH,qBAAA,YACG,iBAAA;EAAA,QAEH,aAAA;EAAA,IAgBG,YAAA,IAAY,mBAAA;EAAA,QAIf,SAAA;EACD,UAAA;EACA,cAAA;EAAA,IACI,SAAA;EAAA,IAIA,SAAA;EAAA,UAIQ,gBAAA,aAA6B,aAAA;EAAA,IAI5B,KAAA,iEAAK,kBAAA,oCAAA,iBAAA;EAAA,IAId,QAAA;kBARkD,iBAAA;;;;;;;EAYtD,WAAA,WAAsB,gBAAA;EACtB,MAAA;EAAA,QAEC,UAAA;EAAA,QAEA,MAAA;;;;;UAMA,gBAAA;EAEQ,SAAA,CAAU,SAAA;cAQxB,eAAA,EAAiB,oBAAA,EACjB,KAAA,EAAO,oBAAA;EAMF,qBAAA,CAAsB,KAAA,EAAO,oBAAA;EAAA;;;;;;EAAA,QA8K5B,qBAAA;EA0LuB;;;;EAAA,QAvHvB,oBAAA;EAAA,QACA,yBAAA;EAuOqB;;;;;;EAAA,QA/NrB,yBAAA;EAmBQ,cAAA,CAAe,QAAA;EAalB,MAAA,CAAO,OAAA,EAAS,aAAA,GAAgB,OAAA;EA8BhC,aAAA,CAAc,SAAA,WAAoB,OAAA;EAoBxC,aAAA,aApB+C,cAAA;EA0B/C,cAAA,CAAe,WAAA;EAIf,eAAA,CAAgB,WAAA;EAIV,QAAA,CAAS,MAAA,EAAQ,cAAA,GAAiB,OAAA;EAclC,SAAA,CAAU,MAAA,EAAQ,eAAA,GAAkB,OAAA;EAO1C,mBAAA;EAOA,mBAAA,CAAoB,KAAA;EAmBpB,SAAA;EA0CA,aAAA,CAAc,OAAA,EAAS,oBAAA;EAMvB,cAAA,CAAe,OAAA,EAAS,qBAAA;EAoBxB,qBAAA,CAAsB,OAAA,EAAS,4BAAA;EAMtB,KAAA,CAAM,eAAA,YAA2B,iBAAA;EAMjC,MAAA,CAAO,IAAA,EAAM,yBAAA;EAAA,QAQrB,cAAA;AAAA"}
@@ -1,7 +1,7 @@
1
1
  import { generateId } from "../../utils/id.js";
2
+ import { fromThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
2
3
  import { bindExternalStoreMessage, getExternalStoreMessages } from "../../runtime/utils/external-store-message.js";
3
4
  import { getAutoStatus, isAutoStatus } from "../../runtime/utils/auto-status.js";
4
- import { fromThreadMessageLike } from "../../runtime/utils/thread-message-like.js";
5
5
  import { ExportedMessageRepository, MessageRepository } from "../../runtime/utils/message-repository.js";
6
6
  import { EMPTY_QUEUE_ITEMS } from "../../store/scopes/queue-item.js";
7
7
  import { getThreadMessageText } from "../../utils/text.js";
@@ -105,9 +105,18 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
105
105
  this._notifySubscribers();
106
106
  return;
107
107
  }
108
- this.repository.clear();
109
- this.repository.import(store.messageRepository);
110
- messages = this.repository.getMessages();
108
+ const incoming = store.messageRepository.messages;
109
+ const headId = store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;
110
+ if (oldStore && oldStore.messageRepository === store.messageRepository) {
111
+ this.repository.resetHead(headId);
112
+ messages = this.repository.getMessages();
113
+ } else {
114
+ const incomingIds = new Set(incoming.map(({ message }) => message.id));
115
+ for (const { message, parentId } of incoming) this.repository.addOrUpdateMessage(parentId, message);
116
+ for (const { message } of this.repository.export().messages) if (!incomingIds.has(message.id)) this.repository.deleteMessage(message.id);
117
+ this.repository.resetHead(headId);
118
+ messages = this.repository.getMessages();
119
+ }
111
120
  } else if (store.messages) {
112
121
  if (oldStore) {
113
122
  if (oldStore.convertMessage !== store.convertMessage) this._converter = new ThreadMessageConverter();
@@ -1 +1 @@
1
- {"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","EMPTY_ARRAY","Object","freeze","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","suggestions","extras","undefined","_converter","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","repository","clear","import","getMessages","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","i","message","parent","addOrUpdateMessage","id","ensureInitialized","_notifyEventSubscribers","optimisticId","at","content","metadata","isOptimistic","type","resetHead","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","result","isError","artifact","modelContent","err","console","error","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","visit","Array","isArray","part","set","get","branchId","updateMessages","append","Promise","isEdit","parentId","enqueue","steer","startRun","abort","onNew","deleteMessage","messageIndex","findIndex","filter","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","cancelRun","head","previousMessage","composer","text","trim","setText","setTimeout","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type { ExternalStoreAdapter } from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n this.repository.clear();\n this.repository.import(store.messageRepository);\n\n messages = this.repository.getMessages();\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n });\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isEdit = message.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // Buffering does not start a run, so the tool-abort below must wait until\n // the queue flushes. By then the prior run (and its tools) has settled.\n if (!isEdit && this._store.queue) {\n this._store.queue.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n this._store.queue?.clear(\"edit\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string) {\n this._store?.queue?.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n this._store.queue?.clear(\"reload\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. We only clear adapter-side\n // tool statuses when the tracker is the source of truth — otherwise\n // we'd wipe statuses the adapter is managing on its own.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._store.setToolStatuses?.({});\n }\n\n this._store.onLoadExternalState(state);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.queue?.clear(\"cancel-run\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n this._store.onCancel();\n\n // Drop an empty optimistic head (placeholder or pre-stream message); a\n // partially-streamed one is kept and re-supplied by the store on resync.\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this._notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult?.(options);\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n this._store.onRespondToToolApproval(options);\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage[]);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAoCA,MAAM0B,cAA2CC,OAAOC,OAAO,CAAA,CAAE;AAEjE,MAAMC,gBAAgBC,GAAWC,MAAuB;CACtD,MAAMC,QAAQL,OAAOM,KAAKH,CAAC;CAC3B,IAAIE,MAAME,WAAWP,OAAOM,KAAKF,CAAC,CAAC,CAACG,QAAQ,OAAO;CACnD,KAAK,MAAMC,OAAOH,OAChB,IAAKF,EAAUK,SAAUJ,EAAUI,MAAM,OAAO;CAElD,OAAO;AACT;AAEA,MAAaC,sBACXC,WACAC,aACG;CACH,OAAOD,aAAaC,SAASA,SAASJ,SAAS,EAAE,EAAEK,SAAS;AAC9D;AAEA,IAAaC,iCAAb,cACUrB,sBAEV;CACE,gBAA6C;EAC3CuB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,IAAWC,eAAe;EACxB,OAAO,KAAKd;CACd;CAEA;CACA;CACA;CACA,IAAWkB,YAAY;EACrB,OAAO,KAAKC,OAAOD,aAAa;CAClC;CAEA,IAAWtB,YAAiC;EAC1C,OAAO,KAAKuB,OAAOvB;CACrB;CAEA,mBAAgE;EAC9D,OAAO,KAAKmB;CACd;CAEA,IAAoBM,QAAQ;EAC1B,OAAO,KAAKF,OAAOE,SAAS,MAAMA;CACpC;CAEA,IAAWC,WAAW;EACpB,OAAO,KAAKH,OAAOG;CACrB;CAEA,cAAkD,CAAA;CAClD,SAAyBG,KAAAA;CAEzB,aAAqB,IAAIvD,uBAAuB;CAEhD;;;;;CAMA,mBAAyD;CAEzD,UAA0B2D,WAAmB;EAC3C,IAAI,CAAC,KAAKV,OAAOW,QACf,MAAM,IAAIC,MAAM,mCAAmC;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AiC;EACtD,MAAM3G,OAAO2G,IAAI;EAEjB,IAAI,KAAKzI,OAAO0I,UACd,KAAK1I,OAAO0I,SAAS,KAAK9G,WAAWG,YAAY,CAAC;CAEtD;CAEA,kBAA0BrD,aAAuC;EAE/D,IADqB,KAAKsB,OAAOgC,mBAAmB1B,KAAAA,GAElD,KAAKN,OAAOoB,cAAc1C,SAASkK,QAAQ/L,wBAAwB,CAAC;OAGpE,KAAKmD,OAAOoB,cAAc1C,QAA2B;CAEzD;AACF"}
1
+ {"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","EMPTY_ARRAY","Object","freeze","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","suggestions","extras","undefined","_converter","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","incoming","headId","at","message","id","repository","resetHead","getMessages","incomingIds","Set","map","parentId","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","i","parent","ensureInitialized","_notifyEventSubscribers","optimisticId","content","metadata","isOptimistic","type","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","result","isError","artifact","modelContent","err","console","error","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","clear","visit","Array","isArray","part","set","get","branchId","updateMessages","append","Promise","isEdit","enqueue","steer","startRun","abort","onNew","messageIndex","findIndex","filter","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","cancelRun","head","previousMessage","composer","text","trim","setText","setTimeout","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type { ExternalStoreAdapter } from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n const incoming = store.messageRepository.messages;\n const headId =\n store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;\n\n if (oldStore && oldStore.messageRepository === store.messageRepository) {\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n } else {\n const incomingIds = new Set(incoming.map(({ message }) => message.id));\n for (const { message, parentId } of incoming) {\n this.repository.addOrUpdateMessage(parentId, message);\n }\n for (const { message } of this.repository.export().messages) {\n if (!incomingIds.has(message.id)) {\n this.repository.deleteMessage(message.id);\n }\n }\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n }\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n });\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isEdit = message.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // Buffering does not start a run, so the tool-abort below must wait until\n // the queue flushes. By then the prior run (and its tools) has settled.\n if (!isEdit && this._store.queue) {\n this._store.queue.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n this._store.queue?.clear(\"edit\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string) {\n this._store?.queue?.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n this._store.queue?.clear(\"reload\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. We only clear adapter-side\n // tool statuses when the tracker is the source of truth — otherwise\n // we'd wipe statuses the adapter is managing on its own.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._store.setToolStatuses?.({});\n }\n\n this._store.onLoadExternalState(state);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.queue?.clear(\"cancel-run\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n this._store.onCancel();\n\n // Drop an empty optimistic head (placeholder or pre-stream message); a\n // partially-streamed one is kept and re-supplied by the store on resync.\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this._notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult?.(options);\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n this._store.onRespondToToolApproval(options);\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage[]);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAoCA,MAAM0B,cAA2CC,OAAOC,OAAO,CAAA,CAAE;AAEjE,MAAMC,gBAAgBC,GAAWC,MAAuB;CACtD,MAAMC,QAAQL,OAAOM,KAAKH,CAAC;CAC3B,IAAIE,MAAME,WAAWP,OAAOM,KAAKF,CAAC,CAAC,CAACG,QAAQ,OAAO;CACnD,KAAK,MAAMC,OAAOH,OAChB,IAAKF,EAAUK,SAAUJ,EAAUI,MAAM,OAAO;CAElD,OAAO;AACT;AAEA,MAAaC,sBACXC,WACAC,aACG;CACH,OAAOD,aAAaC,SAASA,SAASJ,SAAS,EAAE,EAAEK,SAAS;AAC9D;AAEA,IAAaC,iCAAb,cACUrB,sBAEV;CACE,gBAA6C;EAC3CuB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,IAAWC,eAAe;EACxB,OAAO,KAAKd;CACd;CAEA;CACA;CACA;CACA,IAAWkB,YAAY;E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AAQtM,wBAAwB,CAAC;OAGpE,KAAKmD,OAAOoB,cAAc1C,QAA2B;CAEzD;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/core",
3
- "version": "0.2.15",
3
+ "version": "0.2.17",
4
4
  "description": "Framework-agnostic core runtime for assistant-ui",
5
5
  "keywords": [
6
6
  "assistant",
@@ -59,7 +59,7 @@
59
59
  ],
60
60
  "sideEffects": false,
61
61
  "dependencies": {
62
- "assistant-stream": "^0.3.22",
62
+ "assistant-stream": "^0.3.23",
63
63
  "nanoid": "^5.1.11"
64
64
  },
65
65
  "optionalDevDependencies": {
@@ -67,7 +67,7 @@
67
67
  },
68
68
  "peerDependencies": {
69
69
  "@assistant-ui/store": "^0.2.13",
70
- "@assistant-ui/tap": "^0.8.0",
70
+ "@assistant-ui/tap": "^0.9.0",
71
71
  "@types/react": "*",
72
72
  "react": "^18 || ^19",
73
73
  "assistant-cloud": "^0.1.31",
@@ -92,11 +92,11 @@
92
92
  "react": "^19.2.7",
93
93
  "vitest": "^4.1.8",
94
94
  "zustand": "^5.0.14",
95
- "@assistant-ui/store": "0.2.17",
96
- "@assistant-ui/tap": "0.8.1",
97
- "@assistant-ui/vite": "0.0.4",
98
- "@assistant-ui/x-buildutils": "0.0.13",
99
- "assistant-cloud": "0.1.32"
95
+ "@assistant-ui/store": "0.2.18",
96
+ "@assistant-ui/tap": "0.9.2",
97
+ "@assistant-ui/vite": "0.0.5",
98
+ "@assistant-ui/x-buildutils": "0.0.15",
99
+ "assistant-cloud": "0.1.33"
100
100
  },
101
101
  "publishConfig": {
102
102
  "access": "public",
package/src/index.ts CHANGED
@@ -265,6 +265,10 @@ export type {
265
265
 
266
266
  // ThreadMessageLike
267
267
  export type { ThreadMessageLike } from "./runtime/utils/thread-message-like";
268
+ export { fromThreadMessageLike } from "./runtime/utils/thread-message-like";
269
+
270
+ // ID generation
271
+ export { generateId } from "./utils/id";
268
272
 
269
273
  // External Store Message Utilities
270
274
  export {
@@ -1,4 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
+ import type { ToolCallMessagePartProps } from "../types/MessagePartComponentTypes";
2
3
  import { makeToolCallTextComponent } from "./toolbox";
3
4
 
4
5
  describe("makeToolCallTextComponent", () => {
@@ -94,7 +95,7 @@ describe("makeToolCallTextComponent", () => {
94
95
  addResult: () => {},
95
96
  resume: () => {},
96
97
  respondToApproval: () => {},
97
- }),
98
+ } as unknown as ToolCallMessagePartProps),
98
99
  ).toBe("Complete");
99
100
  });
100
101
 
@@ -102,7 +102,7 @@ export const makeToolCallTextComponent = <
102
102
  TResult,
103
103
  >(
104
104
  text: ToolCallText<TArgs, TResult>,
105
- ): ToolCallMessagePartComponent<TArgs, TResult> => {
105
+ ): ((part: ToolCallMessagePartProps<TArgs, TResult>) => ReactNode) => {
106
106
  return function ToolCallTextComponent(part) {
107
107
  return resolveToolCallText(text, part);
108
108
  };
@@ -195,11 +195,7 @@ type OverrideToolDeclarationCallbacks<
195
195
  ) => NoInfer<TResult> | Promise<NoInfer<TResult>>
196
196
  >
197
197
  : {}) &
198
- OverrideOptionalField<
199
- T,
200
- "streamCall",
201
- ToolStreamCall<TArgs, NoInfer<TResult>>
202
- >;
198
+ OverrideOptionalField<T, "streamCall", ToolStreamCall<TArgs, unknown>>;
203
199
 
204
200
  // Keep the authored shape tied to ToolDeclaration's union variants while
205
201
  // overriding callback fields to avoid inference pollution.
@@ -179,10 +179,26 @@ export class ExternalStoreThreadRuntimeCore
179
179
  return;
180
180
  }
181
181
 
182
- this.repository.clear();
183
- this.repository.import(store.messageRepository);
182
+ const incoming = store.messageRepository.messages;
183
+ const headId =
184
+ store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;
184
185
 
185
- messages = this.repository.getMessages();
186
+ if (oldStore && oldStore.messageRepository === store.messageRepository) {
187
+ this.repository.resetHead(headId);
188
+ messages = this.repository.getMessages();
189
+ } else {
190
+ const incomingIds = new Set(incoming.map(({ message }) => message.id));
191
+ for (const { message, parentId } of incoming) {
192
+ this.repository.addOrUpdateMessage(parentId, message);
193
+ }
194
+ for (const { message } of this.repository.export().messages) {
195
+ if (!incomingIds.has(message.id)) {
196
+ this.repository.deleteMessage(message.id);
197
+ }
198
+ }
199
+ this.repository.resetHead(headId);
200
+ messages = this.repository.getMessages();
201
+ }
186
202
  } else if (store.messages) {
187
203
  // Handle messages array
188
204