@assistant-ui/core 0.3.12 → 0.3.13
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 +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/react/client/interactable-model-context.d.ts.map +1 -1
- package/dist/react/client/interactable-model-context.js +5 -1
- package/dist/react/client/interactable-model-context.js.map +1 -1
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js +5 -1
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts +25 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +64 -11
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.d.ts +14 -0
- package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js +31 -0
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/base/default-edit-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/default-edit-composer-runtime-core.js +1 -6
- package/dist/runtime/base/default-edit-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.js +1 -4
- package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
- package/dist/runtime/queue/external-thread-queue-adapter.d.ts +15 -0
- package/dist/runtime/queue/external-thread-queue-adapter.d.ts.map +1 -1
- package/dist/runtime/queue/message-queue.js +23 -10
- package/dist/runtime/queue/message-queue.js.map +1 -1
- package/dist/runtimes/external-store/external-store-adapter.d.ts +7 -0
- package/dist/runtimes/external-store/external-store-adapter.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +3 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js +49 -13
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +2 -1
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/store/clients/external-thread.d.ts +7 -0
- package/dist/store/clients/external-thread.d.ts.map +1 -1
- package/dist/store/clients/external-thread.js +460 -369
- package/dist/store/clients/external-thread.js.map +1 -1
- package/dist/store/clients/runtime-adapter.d.ts.map +1 -1
- package/dist/store/clients/runtime-adapter.js +5 -2
- package/dist/store/clients/runtime-adapter.js.map +1 -1
- package/dist/store/clients/single-thread-list.d.ts.map +1 -1
- package/dist/store/clients/single-thread-list.js +31 -27
- package/dist/store/clients/single-thread-list.js.map +1 -1
- package/dist/store/clients/suggestions.d.ts +3 -1
- package/dist/store/clients/suggestions.d.ts.map +1 -1
- package/dist/store/clients/suggestions.js +65 -37
- package/dist/store/clients/suggestions.js.map +1 -1
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js +64 -50
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.js +98 -82
- package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
- package/dist/store/scope-registration.d.ts +2 -2
- package/dist/store/scopes/suggestions.d.ts +6 -1
- package/dist/store/scopes/suggestions.d.ts.map +1 -1
- package/dist/store/scopes/thread.d.ts +17 -0
- package/dist/store/scopes/thread.d.ts.map +1 -1
- package/dist/types/error.d.ts +15 -1
- package/dist/types/error.d.ts.map +1 -1
- package/dist/types/error.js +18 -1
- package/dist/types/error.js.map +1 -1
- package/dist/types/message.d.ts +2 -0
- package/dist/types/message.d.ts.map +1 -1
- package/dist/types/message.js.map +1 -1
- package/package.json +5 -5
- package/src/index.ts +1 -0
- package/src/react/client/interactable-model-context.ts +6 -1
- package/src/react/runtimes/useExternalStoreRuntime.suggestions.test.tsx +114 -0
- package/src/runtime/api/thread-runtime.ts +8 -1
- package/src/runtime/base/base-composer-runtime-core.ts +100 -8
- package/src/runtime/base/base-thread-runtime-core.ts +36 -0
- package/src/runtime/base/default-edit-composer-runtime-core.ts +1 -15
- package/src/runtime/base/default-thread-composer-runtime-core.ts +1 -11
- package/src/runtime/queue/external-thread-queue-adapter.ts +17 -0
- package/src/runtime/queue/message-queue.ts +26 -9
- package/src/runtimes/external-store/external-store-adapter.ts +7 -0
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +100 -26
- package/src/runtimes/local/local-thread-runtime-core.ts +4 -1
- package/src/store/clients/external-thread.ts +119 -16
- package/src/store/clients/runtime-adapter.ts +5 -2
- package/src/store/clients/single-thread-list.ts +2 -1
- package/src/store/clients/suggestions.ts +39 -13
- package/src/store/runtime-clients/thread-list-item-runtime-client.ts +13 -28
- package/src/store/runtime-clients/thread-runtime-client.ts +5 -0
- package/src/store/scopes/suggestions.ts +6 -0
- package/src/store/scopes/thread.ts +17 -0
- package/src/tests/append-interactable-snapshots.test.ts +350 -0
- package/src/tests/base-composer-runtime-core-send.test.ts +126 -0
- package/src/tests/base-composer-runtime-core.test.ts +108 -1
- package/src/tests/default-edit-composer-runtime-core.test.ts +0 -68
- package/src/tests/external-store-thread-runtime-core-adapter.test.ts +300 -0
- package/src/tests/external-thread-attachments.test.tsx +214 -0
- package/src/tests/external-thread-parity.test.tsx +54 -0
- package/src/tests/external-thread-refetch.test.tsx +117 -0
- package/src/tests/external-thread-suggestions.test.tsx +59 -0
- package/src/tests/message-queue.test.ts +26 -0
- package/src/tests/thread-message-like.test.ts +39 -0
- package/src/tests/thread-switch-events.test.tsx +136 -0
- package/src/types/error.ts +24 -0
- package/src/types/message.ts +2 -0
- package/src/tests/default-thread-composer-runtime-core.test.ts +0 -82
package/dist/index.d.ts
CHANGED
|
@@ -30,7 +30,7 @@ import { AssistantFrameHost } from "./model-context/frame/host.js";
|
|
|
30
30
|
import { AssistantFrameProvider } from "./model-context/frame/provider.js";
|
|
31
31
|
import { FRAME_MESSAGE_CHANNEL, FrameMessage, FrameMessageType, SerializedModelContext, SerializedTool } from "./model-context/frame/types.js";
|
|
32
32
|
import { AttachmentRuntimePath, ComposerRuntimePath, MessagePartRuntimePath, MessageRuntimePath, ThreadListItemRuntimePath, ThreadRuntimePath } from "./runtime/api/paths.js";
|
|
33
|
-
import { AssistantError, AssistantErrorCode, ErrorDisplay, ErrorSeverity, isAssistantError, toAssistantError } from "./types/error.js";
|
|
33
|
+
import { AssistantError, AssistantErrorCode, ErrorDisplay, ErrorSeverity, MessageNotSentError, isAssistantError, isMessageNotSentError, toAssistantError } from "./types/error.js";
|
|
34
34
|
import { ThreadListItemCoreState, ThreadListItemStatus, ThreadListRuntimeCore } from "./runtime/interfaces/thread-list-runtime-core.js";
|
|
35
35
|
import { AssistantRuntimeCore } from "./runtime/interfaces/assistant-runtime-core.js";
|
|
36
36
|
import { generateId } from "./utils/id.js";
|
|
@@ -53,4 +53,4 @@ import { ExternalStoreSharedOptions, pickExternalStoreSharedOptions } from "./ru
|
|
|
53
53
|
import { MessageQueueController, MessageQueueDriver, createMessageQueue } from "./runtime/queue/message-queue.js";
|
|
54
54
|
import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
|
|
55
55
|
import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
|
|
56
|
-
export { type AddToolResultOptions, type AppendMessage, type Assistant, type AssistantContextConfig, type AssistantError, type AssistantErrorCode, 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 CreateSuggestionAdapterOptions, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, type ErrorDisplay, type ErrorSeverity, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreBranchChange, 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 MessagePartStreamStatus, 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 PartProviderMetadata, type PendingAttachment, type PendingAttachmentStatus, type QueuePlacement, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListProviderComponent, 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 StreamingTimingAccessors, type StreamingTimingOptions, type StreamingTimingState, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type SuggestionAdapterGenerateOptions, 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_InteractableSnapshotEntry, type Unstable_InteractableVersion, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type UserCommands, type UserExternalState, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
|
|
56
|
+
export { type AddToolResultOptions, type AppendMessage, type Assistant, type AssistantContextConfig, type AssistantError, type AssistantErrorCode, 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 CreateSuggestionAdapterOptions, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, type ErrorDisplay, type ErrorSeverity, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreBranchChange, 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, MessageNotSentError, type MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, type MessagePartStreamStatus, 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 PartProviderMetadata, type PendingAttachment, type PendingAttachmentStatus, type QueuePlacement, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListProviderComponent, 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 StreamingTimingAccessors, type StreamingTimingOptions, type StreamingTimingState, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type SuggestionAdapterGenerateOptions, 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_InteractableSnapshotEntry, type Unstable_InteractableVersion, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type UserCommands, type UserExternalState, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, isMessageNotSentError, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
|
package/dist/index.js
CHANGED
|
@@ -13,7 +13,7 @@ import { WebSpeechDictationAdapter, WebSpeechSynthesisAdapter } from "./adapters
|
|
|
13
13
|
import { createVoiceSession } from "./adapters/voice.js";
|
|
14
14
|
import { createSuggestionAdapter } from "./adapters/suggestion.js";
|
|
15
15
|
import { unstable_defaultDirectiveFormatter } from "./adapters/directive-formatter.js";
|
|
16
|
-
import { isAssistantError, toAssistantError } from "./types/error.js";
|
|
16
|
+
import { MessageNotSentError, isAssistantError, isMessageNotSentError, toAssistantError } from "./types/error.js";
|
|
17
17
|
import { fromThreadMessageLike } from "./runtime/utils/thread-message-like.js";
|
|
18
18
|
import { stepStreamingTiming } from "./runtime/utils/streaming-timing.js";
|
|
19
19
|
import { bindExternalStoreMessage, getExternalStoreMessages } from "./runtime/utils/external-store-message.js";
|
|
@@ -25,6 +25,6 @@ import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
|
|
|
25
25
|
//#region src/index.ts
|
|
26
26
|
if (process.env.NODE_ENV !== "production") checkDuplicateCore();
|
|
27
27
|
//#endregion
|
|
28
|
-
export { AssistantFrameHost, AssistantFrameProvider, CompositeAttachmentAdapter, ExportedMessageRepository, FRAME_MESSAGE_CHANNEL, InMemoryThreadListAdapter, MCP_APP_URI_SCHEME, ModelContextRegistry, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
|
|
28
|
+
export { AssistantFrameHost, AssistantFrameProvider, CompositeAttachmentAdapter, ExportedMessageRepository, FRAME_MESSAGE_CHANNEL, InMemoryThreadListAdapter, MCP_APP_URI_SCHEME, MessageNotSentError, ModelContextRegistry, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, isMessageNotSentError, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
|
|
29
29
|
|
|
30
30
|
//# 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","PartProviderMetadata","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","MessagePartStreamStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","Assistant","UserCommands","UserExternalState","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","unstable_getInteractableSnapshots","unstable_formatInteractableSnapshot","unstable_getInteractableVersions","Unstable_InteractableSnapshotEntry","Unstable_InteractableVersion","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","SuggestionAdapterGenerateOptions","CreateSuggestionAdapterOptions","createSuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","ErrorSeverity","ErrorDisplay","AssistantErrorCode","AssistantError","toAssistantError","isAssistantError","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","StreamingTimingAccessors","StreamingTimingOptions","StreamingTimingState","stepStreamingTiming","generateId","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreBranchChange","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","QueuePlacement","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RemoteThreadListOptions","RemoteThreadListProviderComponent","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 PartProviderMetadata,\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 MessagePartStreamStatus,\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 {\n Assistant,\n UserCommands,\n UserExternalState,\n} from \"./types/augmentations\";\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 {\n unstable_getInteractableSnapshots,\n unstable_formatInteractableSnapshot,\n unstable_getInteractableVersions,\n type Unstable_InteractableSnapshotEntry,\n type Unstable_InteractableVersion,\n} from \"./model-context/interactable-composer-metadata\";\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 {\n SuggestionAdapter,\n SuggestionAdapterGenerateOptions,\n CreateSuggestionAdapterOptions,\n} from \"./adapters/suggestion\";\nexport { createSuggestionAdapter } 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 ErrorSeverity,\n ErrorDisplay,\n AssistantErrorCode,\n AssistantError,\n} from \"./types/error\";\nexport { toAssistantError, isAssistantError } from \"./types/error\";\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// Streaming timing (client-side)\nexport type {\n StreamingTimingAccessors,\n StreamingTimingOptions,\n StreamingTimingState,\n} from \"./runtime/utils/streaming-timing\";\nexport { stepStreamingTiming } from \"./runtime/utils/streaming-timing\";\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 ExternalStoreBranchChange,\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 {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} 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 RemoteThreadListProviderComponent,\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","PartProviderMetadata","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","MessagePartStreamStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","Assistant","UserCommands","UserExternalState","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","unstable_getInteractableSnapshots","unstable_formatInteractableSnapshot","unstable_getInteractableVersions","Unstable_InteractableSnapshotEntry","Unstable_InteractableVersion","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","SuggestionAdapterGenerateOptions","CreateSuggestionAdapterOptions","createSuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","ErrorSeverity","ErrorDisplay","AssistantErrorCode","AssistantError","toAssistantError","isAssistantError","MessageNotSentError","isMessageNotSentError","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","StreamingTimingAccessors","StreamingTimingOptions","StreamingTimingState","stepStreamingTiming","generateId","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreBranchChange","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","QueuePlacement","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RemoteThreadListOptions","RemoteThreadListProviderComponent","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 PartProviderMetadata,\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 MessagePartStreamStatus,\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 {\n Assistant,\n UserCommands,\n UserExternalState,\n} from \"./types/augmentations\";\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 {\n unstable_getInteractableSnapshots,\n unstable_formatInteractableSnapshot,\n unstable_getInteractableVersions,\n type Unstable_InteractableSnapshotEntry,\n type Unstable_InteractableVersion,\n} from \"./model-context/interactable-composer-metadata\";\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 {\n SuggestionAdapter,\n SuggestionAdapterGenerateOptions,\n CreateSuggestionAdapterOptions,\n} from \"./adapters/suggestion\";\nexport { createSuggestionAdapter } 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 ErrorSeverity,\n ErrorDisplay,\n AssistantErrorCode,\n AssistantError,\n} from \"./types/error\";\nexport { toAssistantError, isAssistantError } from \"./types/error\";\nexport { MessageNotSentError, isMessageNotSentError } from \"./types/error\";\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// Streaming timing (client-side)\nexport type {\n StreamingTimingAccessors,\n StreamingTimingOptions,\n StreamingTimingState,\n} from \"./runtime/utils/streaming-timing\";\nexport { stepStreamingTiming } from \"./runtime/utils/streaming-timing\";\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 ExternalStoreBranchChange,\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 {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} 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 RemoteThreadListProviderComponent,\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactable-model-context.d.ts","names":[],"sources":["../../../src/react/client/interactable-model-context.ts"],"mappings":";;;KAWY,oBAAoB,kBAAkB;
|
|
1
|
+
{"version":3,"file":"interactable-model-context.d.ts","names":[],"sources":["../../../src/react/client/interactable-model-context.ts"],"mappings":";;;KAWY,oBAAoB,kBAAkB;iBAgIlC,8BACd,aAAa,eAAe,kCAC5B,oBAAoB,YAAY,oBAChC,cAAc,YAAY,UAAU,oCACpC,kBAAe;EAA+B;EAAe;;EAGzD,OAAO,eAAe;EACtB,4BAA4B"}
|
|
@@ -7,6 +7,10 @@ const ID_PROPERTY = {
|
|
|
7
7
|
type: "string",
|
|
8
8
|
description: "The id of the instance to update, as shown in its state snapshot in the conversation."
|
|
9
9
|
};
|
|
10
|
+
const ITEM_ID_PROPERTY = {
|
|
11
|
+
type: "string",
|
|
12
|
+
description: "The id of an item currently in this list."
|
|
13
|
+
};
|
|
10
14
|
const hasIdProperty = (schema) => {
|
|
11
15
|
const properties = schema.properties;
|
|
12
16
|
return isRecord(properties) && properties.id !== void 0;
|
|
@@ -36,7 +40,7 @@ const toArrayUpdateSchema = (schema, field) => {
|
|
|
36
40
|
},
|
|
37
41
|
remove: {
|
|
38
42
|
type: "array",
|
|
39
|
-
items: idKeyed ?
|
|
43
|
+
items: idKeyed ? ITEM_ID_PROPERTY : itemSchema
|
|
40
44
|
},
|
|
41
45
|
clear: { type: "boolean" }
|
|
42
46
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interactable-model-context.js","names":["Tool","toJSONSchema","Unstable_InteractableDefinition","interactableToolName","shallowMergeInteractableState","Unstable_InteractableSnapshotEntry","generateId","isRecord","PartialJSONSchema","ReturnType","ID_PROPERTY","type","const","description","hasIdProperty","schema","Record","properties","id","undefined","withRequiredItemId","required","withoutItemId","_omitted","Array","isArray","filter","key","toArrayUpdateSchema","field","itemSchema","items","idKeyed","add","remove","clear","update","additionalProperties","idKeyedArrayFieldNames","Set","names","value","Object","entries","withArrayUpdateSchemas","fromEntries","map","withRequiredId","partial","process","env","NODE_ENV","console","warn","_reserved","buildInteractableModelContext","definitions","partialSchemaCache","Map","setDefState","updater","prev","streamBaselines","targetId","state","tools","unstable_composerMetadata","values","length","byName","def","list","get","name","push","set","instances","toolName","first","partialSchema","idKeyedFields","resolveTarget","parameters","streamCall","reader","toolCallId","partialArgs","args","streamValues","keys","idIndex","indexOf","target","baseline","arrayBaseline","execute","validIds","d","success","error","JSON","stringify","join","delete","addedItemIds","idFactory","itemId","result","interactables"],"sources":["../../../src/react/client/interactable-model-context.ts"],"sourcesContent":["import type { Tool } from \"assistant-stream\";\nimport { toJSONSchema } from \"assistant-stream\";\nimport type { Unstable_InteractableDefinition } from \"../types/scopes/interactables\";\nimport {\n interactableToolName,\n shallowMergeInteractableState,\n type Unstable_InteractableSnapshotEntry,\n} from \"../../model-context/interactable-composer-metadata\";\nimport { generateId } from \"../../utils/id\";\nimport { isRecord } from \"../../utils/json/is-json\";\n\nexport type PartialJSONSchema = ReturnType<typeof toJSONSchema>;\n\nconst ID_PROPERTY = {\n type: \"string\" as const,\n description:\n \"The id of the instance to update, as shown in its state snapshot in the conversation.\",\n};\n\nconst hasIdProperty = (schema: Record<string, unknown>) => {\n const properties = schema.properties;\n return isRecord(properties) && properties.id !== undefined;\n};\n\nconst withRequiredItemId = (schema: Record<string, unknown>) => ({\n ...schema,\n required: [\"id\"],\n});\n\n// The framework assigns ids to new items, so the model never sees the `id`\n// field when adding (it can't address an item that doesn't exist yet).\nconst withoutItemId = (schema: Record<string, unknown>) => {\n const { id: _omitted, ...properties } = isRecord(schema.properties)\n ? schema.properties\n : {};\n const required = Array.isArray(schema.required)\n ? schema.required.filter((key) => key !== \"id\")\n : schema.required;\n return { ...schema, properties, required };\n};\n\nconst toArrayUpdateSchema = (schema: unknown, field: string) => {\n if (!isRecord(schema) || schema.type !== \"array\") return schema;\n const itemSchema = schema.items;\n if (Array.isArray(itemSchema) || !isRecord(itemSchema)) return schema;\n\n const idKeyed = hasIdProperty(itemSchema);\n const properties: Record<string, unknown> = {\n add: {\n type: \"array\",\n items: idKeyed ? withoutItemId(itemSchema) : itemSchema,\n },\n remove: {\n type: \"array\",\n items: idKeyed ? ID_PROPERTY : itemSchema,\n },\n clear: { type: \"boolean\" },\n };\n\n if (idKeyed) {\n properties.update = {\n type: \"array\",\n items: withRequiredItemId(itemSchema),\n };\n }\n\n return {\n type: \"object\" as const,\n description:\n `Operations for array field \"${field}\". To change one item use update ` +\n `with its id; add new items (their ids are assigned for you), remove items ` +\n `by id, or clear to empty. Change only the items you mean to — never resend ` +\n `the whole array to edit one item.`,\n properties,\n additionalProperties: false,\n };\n};\n\n// Top-level array fields whose items carry an `id` — the fields the framework\n// mints ids for on add.\nconst idKeyedArrayFieldNames = (\n properties: Record<string, unknown>,\n): Set<string> => {\n const names = new Set<string>();\n for (const [key, value] of Object.entries(properties)) {\n if (\n isRecord(value) &&\n value.type === \"array\" &&\n isRecord(value.items) &&\n hasIdProperty(value.items)\n ) {\n names.add(key);\n }\n }\n return names;\n};\n\nconst withArrayUpdateSchemas = (properties: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(properties).map(([key, value]) => [\n key,\n toArrayUpdateSchema(value, key),\n ]),\n );\n\n/**\n * Wraps an interactable's partial state schema with the required `id`\n * parameter. Falls back to a permissive schema when the partial conversion\n * failed at registration time.\n */\nfunction withRequiredId(partial: PartialJSONSchema | undefined) {\n if (!partial || typeof partial !== \"object\" || partial.type !== \"object\") {\n return {\n type: \"object\" as const,\n properties: { id: ID_PROPERTY },\n required: [\"id\"],\n additionalProperties: true,\n };\n }\n if (process.env.NODE_ENV !== \"production\" && partial.properties?.id) {\n console.warn(\n `[Interactables] a top-level \"id\" field in an interactable's stateSchema is ` +\n `reserved for instance addressing by the update tool and cannot be updated ` +\n `by the model. Rename the field to make it model-writable.`,\n );\n }\n const { id: _reserved, ...properties } = partial.properties ?? {};\n return {\n ...partial,\n properties: { id: ID_PROPERTY, ...withArrayUpdateSchemas(properties) },\n required: [\"id\"],\n };\n}\n\nexport function buildInteractableModelContext(\n definitions: Record<string, Unstable_InteractableDefinition>,\n partialSchemaCache: Map<string, PartialJSONSchema>,\n setDefState: (id: string, updater: (prev: unknown) => unknown) => void,\n streamBaselines = new Map<string, { targetId: string; state: unknown }>(),\n):\n | {\n tools: Record<string, Tool<any, any>>;\n unstable_composerMetadata?: Record<string, unknown>;\n }\n | undefined {\n const entries = Object.values(definitions);\n if (entries.length === 0) return undefined;\n\n const byName = new Map<string, Unstable_InteractableDefinition[]>();\n for (const def of entries) {\n const list = byName.get(def.name) ?? [];\n list.push(def);\n byName.set(def.name, list);\n }\n\n const tools: Record<string, Tool<any, any>> = {};\n\n for (const [name, instances] of byName) {\n const toolName = interactableToolName(name);\n if (tools[toolName]) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Interactables] interactable names \"${name}\" and another registered name ` +\n `both sanitize to the tool name \"${toolName}\". Rename one of them.`,\n );\n }\n continue;\n }\n\n const first = instances[0]!;\n const partialSchema = partialSchemaCache.get(first.id);\n const idKeyedFields =\n partialSchema && isRecord(partialSchema.properties)\n ? idKeyedArrayFieldNames(partialSchema.properties)\n : new Set<string>();\n\n // `id` resolves to a definition of this name; an id-less call is accepted\n // only while exactly one instance exists.\n const resolveTarget = (\n id: unknown,\n ): Unstable_InteractableDefinition | undefined => {\n if (typeof id === \"string\") {\n const def = definitions[id];\n return def?.name === name ? def : undefined;\n }\n return instances.length === 1 ? first : undefined;\n };\n\n tools[toolName] = {\n type: \"frontend\",\n description:\n `Update the state of interactable component \"${name}\". ${first.description} ` +\n `Pass the id of the instance to update — instance ids and current state ` +\n `appear in the conversation as state snapshots. Only include the fields ` +\n `you want to change; omitted fields keep their current values.`,\n parameters: withRequiredId(partialSchema),\n streamCall: async (reader, { toolCallId }) => {\n try {\n for await (const partialArgs of reader.args.streamValues()) {\n if (!partialArgs || typeof partialArgs !== \"object\") continue;\n const args = partialArgs as Record<string, unknown>;\n const keys = Object.keys(args);\n const idIndex = keys.indexOf(\"id\");\n if (idIndex === keys.length - 1) continue;\n\n const { id, ...partial } = args;\n if (Object.keys(partial).length === 0) continue;\n const target = resolveTarget(id);\n if (!target) continue;\n\n const baseline = streamBaselines.get(toolCallId);\n const arrayBaseline =\n baseline?.targetId === target.id ? baseline.state : target.state;\n if (!baseline || baseline.targetId !== target.id) {\n streamBaselines.set(toolCallId, {\n targetId: target.id,\n state: target.state,\n });\n }\n\n setDefState(target.id, (prev) =>\n shallowMergeInteractableState(prev, partial, { arrayBaseline }),\n );\n }\n } catch {\n // Non-fatal: execute handles the final state\n }\n },\n execute: async (args: unknown, { toolCallId }) => {\n const { id, ...partial } = (args ?? {}) as Record<string, unknown>;\n const target = resolveTarget(id);\n if (!target) {\n const validIds = instances.map((d) => d.id);\n return {\n success: false,\n error: `Unknown id ${JSON.stringify(id)} for interactable \"${name}\". Valid ids: ${validIds.join(\", \")}`,\n };\n }\n const baseline = streamBaselines.get(toolCallId);\n streamBaselines.delete(toolCallId);\n const addedItemIds: Record<string, string[]> = {};\n setDefState(target.id, (prev) =>\n shallowMergeInteractableState(prev, partial, {\n arrayBaseline:\n baseline?.targetId === target.id ? baseline.state : undefined,\n idFactory: (field) => {\n const itemId = generateId();\n (addedItemIds[field] ??= []).push(itemId);\n return itemId;\n },\n idKeyedFields,\n }),\n );\n // The resolved id lets an id-less call's UI (and the model) address\n // the instance that was actually updated.\n const result: {\n success: true;\n id: string;\n addedItemIds?: Record<string, string[]>;\n } = { success: true, id: target.id };\n if (Object.keys(addedItemIds).length > 0) {\n result.addedItemIds = addedItemIds;\n }\n return result;\n },\n };\n }\n\n const interactables: Unstable_InteractableSnapshotEntry[] = entries.map(\n (def) => ({\n id: def.id,\n name: def.name,\n state: def.state,\n }),\n );\n return { tools, unstable_composerMetadata: { interactables } };\n}\n"],"mappings":";;;;;AAaA,MAAMU,cAAc;CAClBC,MAAM;CACNE,aACE;AACJ;AAEA,MAAMC,iBAAiBC,WAAoC;CACzD,MAAME,aAAaF,OAAOE;CAC1B,OAAOV,SAASU,UAAU,KAAKA,WAAWC,OAAOC,KAAAA;AACnD;AAEA,MAAMC,sBAAsBL,YAAqC;CAC/D,GAAGA;CACHM,UAAU,CAAC,IAAI;AACjB;AAIA,MAAMC,iBAAiBP,WAAoC;CACzD,MAAM,EAAEG,IAAIK,UAAU,GAAGN,eAAeV,SAASQ,OAAOE,UAAU,IAC9DF,OAAOE,aACP,CAAC;CACL,MAAMI,WAAWG,MAAMC,QAAQV,OAAOM,QAAQ,IAC1CN,OAAOM,SAASK,QAAQC,QAAQA,QAAQ,IAAI,IAC5CZ,OAAOM;CACX,OAAO;EAAE,GAAGN;EAAQE;EAAYI;CAAS;AAC3C;AAEA,MAAMO,uBAAuBb,QAAiBc,UAAkB;CAC9D,IAAI,CAACtB,SAASQ,MAAM,KAAKA,OAAOJ,SAAS,SAAS,OAAOI;CACzD,MAAMe,aAAaf,OAAOgB;CAC1B,IAAIP,MAAMC,QAAQK,UAAU,KAAK,CAACvB,SAASuB,UAAU,GAAG,OAAOf;CAE/D,MAAMiB,UAAUlB,cAAcgB,UAAU;CACxC,MAAMb,aAAsC;EAC1CgB,KAAK;GACHtB,MAAM;GACNoB,OAAOC,UAAUV,cAAcQ,UAAU,IAAIA;EAC/C;EACAI,QAAQ;GACNvB,MAAM;GACNoB,OAAOC,UAAUtB,cAAcoB;EACjC;EACAK,OAAO,EAAExB,MAAM,UAAU;CAC3B;CAEA,IAAIqB,SACFf,WAAWmB,SAAS;EAClBzB,MAAM;EACNoB,OAAOX,mBAAmBU,UAAU;CACtC;CAGF,OAAO;EACLnB,MAAM;EACNE,aACE,+BAA+BgB,MA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AAC,CACH;IAGA,MAAM2B,SAIF;KAAET,SAAS;KAAMhF,IAAI0E,OAAO1E;IAAG;IACnC,IAAIwB,OAAO+C,KAAKe,YAAY,CAAC,CAACpC,SAAS,GACrCuC,OAAOH,eAAeA;IAExB,OAAOG;GACT;EACF;CACF;CASA,OAAO;EAAE1C;EAAOC,2BAA2B,EAAE0C,eAPejE,QAAQG,KACjEwB,SAAS;GACRpD,IAAIoD,IAAIpD;GACRuD,MAAMH,IAAIG;GACVT,OAAOM,IAAIN;EACb,EAE2C4C,EAAc;CAAE;AAC/D"}
|
|
1
|
+
{"version":3,"file":"interactable-model-context.js","names":["Tool","toJSONSchema","Unstable_InteractableDefinition","interactableToolName","shallowMergeInteractableState","Unstable_InteractableSnapshotEntry","generateId","isRecord","PartialJSONSchema","ReturnType","ID_PROPERTY","type","const","description","ITEM_ID_PROPERTY","hasIdProperty","schema","Record","properties","id","undefined","withRequiredItemId","required","withoutItemId","_omitted","Array","isArray","filter","key","toArrayUpdateSchema","field","itemSchema","items","idKeyed","add","remove","clear","update","additionalProperties","idKeyedArrayFieldNames","Set","names","value","Object","entries","withArrayUpdateSchemas","fromEntries","map","withRequiredId","partial","process","env","NODE_ENV","console","warn","_reserved","buildInteractableModelContext","definitions","partialSchemaCache","Map","setDefState","updater","prev","streamBaselines","targetId","state","tools","unstable_composerMetadata","values","length","byName","def","list","get","name","push","set","instances","toolName","first","partialSchema","idKeyedFields","resolveTarget","parameters","streamCall","reader","toolCallId","partialArgs","args","streamValues","keys","idIndex","indexOf","target","baseline","arrayBaseline","execute","validIds","d","success","error","JSON","stringify","join","delete","addedItemIds","idFactory","itemId","result","interactables"],"sources":["../../../src/react/client/interactable-model-context.ts"],"sourcesContent":["import type { Tool } from \"assistant-stream\";\nimport { toJSONSchema } from \"assistant-stream\";\nimport type { Unstable_InteractableDefinition } from \"../types/scopes/interactables\";\nimport {\n interactableToolName,\n shallowMergeInteractableState,\n type Unstable_InteractableSnapshotEntry,\n} from \"../../model-context/interactable-composer-metadata\";\nimport { generateId } from \"../../utils/id\";\nimport { isRecord } from \"../../utils/json/is-json\";\n\nexport type PartialJSONSchema = ReturnType<typeof toJSONSchema>;\n\nconst ID_PROPERTY = {\n type: \"string\" as const,\n description:\n \"The id of the instance to update, as shown in its state snapshot in the conversation.\",\n};\n\nconst ITEM_ID_PROPERTY = {\n type: \"string\" as const,\n description: \"The id of an item currently in this list.\",\n};\n\nconst hasIdProperty = (schema: Record<string, unknown>) => {\n const properties = schema.properties;\n return isRecord(properties) && properties.id !== undefined;\n};\n\nconst withRequiredItemId = (schema: Record<string, unknown>) => ({\n ...schema,\n required: [\"id\"],\n});\n\n// The framework assigns ids to new items, so the model never sees the `id`\n// field when adding (it can't address an item that doesn't exist yet).\nconst withoutItemId = (schema: Record<string, unknown>) => {\n const { id: _omitted, ...properties } = isRecord(schema.properties)\n ? schema.properties\n : {};\n const required = Array.isArray(schema.required)\n ? schema.required.filter((key) => key !== \"id\")\n : schema.required;\n return { ...schema, properties, required };\n};\n\nconst toArrayUpdateSchema = (schema: unknown, field: string) => {\n if (!isRecord(schema) || schema.type !== \"array\") return schema;\n const itemSchema = schema.items;\n if (Array.isArray(itemSchema) || !isRecord(itemSchema)) return schema;\n\n const idKeyed = hasIdProperty(itemSchema);\n const properties: Record<string, unknown> = {\n add: {\n type: \"array\",\n items: idKeyed ? withoutItemId(itemSchema) : itemSchema,\n },\n remove: {\n type: \"array\",\n items: idKeyed ? ITEM_ID_PROPERTY : itemSchema,\n },\n clear: { type: \"boolean\" },\n };\n\n if (idKeyed) {\n properties.update = {\n type: \"array\",\n items: withRequiredItemId(itemSchema),\n };\n }\n\n return {\n type: \"object\" as const,\n description:\n `Operations for array field \"${field}\". To change one item use update ` +\n `with its id; add new items (their ids are assigned for you), remove items ` +\n `by id, or clear to empty. Change only the items you mean to — never resend ` +\n `the whole array to edit one item.`,\n properties,\n additionalProperties: false,\n };\n};\n\n// Top-level array fields whose items carry an `id` — the fields the framework\n// mints ids for on add.\nconst idKeyedArrayFieldNames = (\n properties: Record<string, unknown>,\n): Set<string> => {\n const names = new Set<string>();\n for (const [key, value] of Object.entries(properties)) {\n if (\n isRecord(value) &&\n value.type === \"array\" &&\n isRecord(value.items) &&\n hasIdProperty(value.items)\n ) {\n names.add(key);\n }\n }\n return names;\n};\n\nconst withArrayUpdateSchemas = (properties: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(properties).map(([key, value]) => [\n key,\n toArrayUpdateSchema(value, key),\n ]),\n );\n\n/**\n * Wraps an interactable's partial state schema with the required `id`\n * parameter. Falls back to a permissive schema when the partial conversion\n * failed at registration time.\n */\nfunction withRequiredId(partial: PartialJSONSchema | undefined) {\n if (!partial || typeof partial !== \"object\" || partial.type !== \"object\") {\n return {\n type: \"object\" as const,\n properties: { id: ID_PROPERTY },\n required: [\"id\"],\n additionalProperties: true,\n };\n }\n if (process.env.NODE_ENV !== \"production\" && partial.properties?.id) {\n console.warn(\n `[Interactables] a top-level \"id\" field in an interactable's stateSchema is ` +\n `reserved for instance addressing by the update tool and cannot be updated ` +\n `by the model. Rename the field to make it model-writable.`,\n );\n }\n const { id: _reserved, ...properties } = partial.properties ?? {};\n return {\n ...partial,\n properties: { id: ID_PROPERTY, ...withArrayUpdateSchemas(properties) },\n required: [\"id\"],\n };\n}\n\nexport function buildInteractableModelContext(\n definitions: Record<string, Unstable_InteractableDefinition>,\n partialSchemaCache: Map<string, PartialJSONSchema>,\n setDefState: (id: string, updater: (prev: unknown) => unknown) => void,\n streamBaselines = new Map<string, { targetId: string; state: unknown }>(),\n):\n | {\n tools: Record<string, Tool<any, any>>;\n unstable_composerMetadata?: Record<string, unknown>;\n }\n | undefined {\n const entries = Object.values(definitions);\n if (entries.length === 0) return undefined;\n\n const byName = new Map<string, Unstable_InteractableDefinition[]>();\n for (const def of entries) {\n const list = byName.get(def.name) ?? [];\n list.push(def);\n byName.set(def.name, list);\n }\n\n const tools: Record<string, Tool<any, any>> = {};\n\n for (const [name, instances] of byName) {\n const toolName = interactableToolName(name);\n if (tools[toolName]) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Interactables] interactable names \"${name}\" and another registered name ` +\n `both sanitize to the tool name \"${toolName}\". Rename one of them.`,\n );\n }\n continue;\n }\n\n const first = instances[0]!;\n const partialSchema = partialSchemaCache.get(first.id);\n const idKeyedFields =\n partialSchema && isRecord(partialSchema.properties)\n ? idKeyedArrayFieldNames(partialSchema.properties)\n : new Set<string>();\n\n // `id` resolves to a definition of this name; an id-less call is accepted\n // only while exactly one instance exists.\n const resolveTarget = (\n id: unknown,\n ): Unstable_InteractableDefinition | undefined => {\n if (typeof id === \"string\") {\n const def = definitions[id];\n return def?.name === name ? def : undefined;\n }\n return instances.length === 1 ? first : undefined;\n };\n\n tools[toolName] = {\n type: \"frontend\",\n description:\n `Update the state of interactable component \"${name}\". ${first.description} ` +\n `Pass the id of the instance to update — instance ids and current state ` +\n `appear in the conversation as state snapshots. Only include the fields ` +\n `you want to change; omitted fields keep their current values.`,\n parameters: withRequiredId(partialSchema),\n streamCall: async (reader, { toolCallId }) => {\n try {\n for await (const partialArgs of reader.args.streamValues()) {\n if (!partialArgs || typeof partialArgs !== \"object\") continue;\n const args = partialArgs as Record<string, unknown>;\n const keys = Object.keys(args);\n const idIndex = keys.indexOf(\"id\");\n if (idIndex === keys.length - 1) continue;\n\n const { id, ...partial } = args;\n if (Object.keys(partial).length === 0) continue;\n const target = resolveTarget(id);\n if (!target) continue;\n\n const baseline = streamBaselines.get(toolCallId);\n const arrayBaseline =\n baseline?.targetId === target.id ? baseline.state : target.state;\n if (!baseline || baseline.targetId !== target.id) {\n streamBaselines.set(toolCallId, {\n targetId: target.id,\n state: target.state,\n });\n }\n\n setDefState(target.id, (prev) =>\n shallowMergeInteractableState(prev, partial, { arrayBaseline }),\n );\n }\n } catch {\n // Non-fatal: execute handles the final state\n }\n },\n execute: async (args: unknown, { toolCallId }) => {\n const { id, ...partial } = (args ?? {}) as Record<string, unknown>;\n const target = resolveTarget(id);\n if (!target) {\n const validIds = instances.map((d) => d.id);\n return {\n success: false,\n error: `Unknown id ${JSON.stringify(id)} for interactable \"${name}\". Valid ids: ${validIds.join(\", \")}`,\n };\n }\n const baseline = streamBaselines.get(toolCallId);\n streamBaselines.delete(toolCallId);\n const addedItemIds: Record<string, string[]> = {};\n setDefState(target.id, (prev) =>\n shallowMergeInteractableState(prev, partial, {\n arrayBaseline:\n baseline?.targetId === target.id ? baseline.state : undefined,\n idFactory: (field) => {\n const itemId = generateId();\n (addedItemIds[field] ??= []).push(itemId);\n return itemId;\n },\n idKeyedFields,\n }),\n );\n // The resolved id lets an id-less call's UI (and the model) address\n // the instance that was actually updated.\n const result: {\n success: true;\n id: string;\n addedItemIds?: Record<string, string[]>;\n } = { success: true, id: target.id };\n if (Object.keys(addedItemIds).length > 0) {\n result.addedItemIds = addedItemIds;\n }\n return result;\n },\n };\n }\n\n const interactables: Unstable_InteractableSnapshotEntry[] = entries.map(\n (def) => ({\n id: def.id,\n name: def.name,\n state: def.state,\n }),\n );\n return { tools, unstable_composerMetadata: { interactables } };\n}\n"],"mappings":";;;;;AAaA,MAAMU,cAAc;CAClBC,MAAM;CACNE,aACE;AACJ;AAEA,MAAMC,mBAAmB;CACvBH,MAAM;CACNE,aAAa;AACf;AAEA,MAAME,iBAAiBC,WAAoC;CACzD,MAAME,aAAaF,OAAOE;CAC1B,OAAOX,SAASW,UAAU,KAAKA,WAAWC,OAAOC,KAAAA;AACnD;AAEA,MAAMC,sBAAsBL,YAAqC;CAC/D,GAAGA;CACHM,UAAU,CAAC,IAAI;AACjB;AAIA,MAAMC,iBAAiBP,WAAoC;CACzD,MAAM,EAAEG,IAAIK,UAAU,GAAGN,eAAeX,SAASS,OAAOE,UAAU,IAC9DF,OAAOE,aACP,CAAC;CACL,MAAMI,WAAWG,MAAMC,QAAQV,OAAOM,QAAQ,IAC1CN,OAAOM,SAASK,QAAQC,QAAQA,QAAQ,IAAI,IAC5CZ,OAAOM;CACX,OAAO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,SAASX,cAAc/D,EAAE;IAC/B,IAAI,CAAC0E,QAAQ;KACX,MAAMI,WAAWpB,UAAU9B,KAAKmD,MAAMA,EAAE/E,EAAE;KAC1C,OAAO;MACLgF,SAAS;MACTC,OAAO,cAAcC,KAAKC,UAAUnF,EAAE,EAAC,qBAAsBuD,KAAI,gBAAiBuB,SAASM,KAAK,IAAI;KACtG;IACF;IACA,MAAMT,WAAW/B,gBAAgBU,IAAIa,UAAU;IAC/CvB,gBAAgByC,OAAOlB,UAAU;IACjC,MAAMmB,eAAyC,CAAC;IAChD7C,YAAYiC,OAAO1E,KAAK2C,SACtB1D,8BAA8B0D,MAAMb,SAAS;KAC3C8C,eACED,UAAU9B,aAAa6B,OAAO1E,KAAK2E,SAAS7B,QAAQ7C,KAAAA;KACtDsF,YAAY5E,UAAU;MACpB,MAAM6E,SAASrG,WAAW;MAC1B,CAACmG,aAAa3E,WAAW,CAAA,EAAA,CAAI6C,KAAKgC,MAAM;MACxC,OAAOA;KACT;KACA1B;IACF,CAAC,CACH;IAGA,MAAM2B,SAIF;KAAET,SAAS;KAAMhF,IAAI0E,OAAO1E;IAAG;IACnC,IAAIwB,OAAO+C,KAAKe,YAAY,CAAC,CAACpC,SAAS,GACrCuC,OAAOH,eAAeA;IAExB,OAAOG;GACT;EACF;CACF;CASA,OAAO;EAAE1C;EAAOC,2BAA2B,EAAE0C,eAPejE,QAAQG,KACjEwB,SAAS;GACRpD,IAAIoD,IAAIpD;GACRuD,MAAMH,IAAIG;GACVT,OAAOM,IAAIN;EACb,EAE2C4C,EAAc;CAAE;AAC/D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;KA+CY;EAC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cAAc,2BAAiB;EAI/B,UAAU,uBAAoB;EAI9B,mBAAe;EAIf,SAAS,QAAQ;EAIjB,UAAU,QAAQ;EAIlB;EAIA,oBAAoB;EAIpB;EAIA;EAIA;EAIA;EAIA;EAIA,qBAAqB,uBAAoB;EAIzC;EAIA;EAIA,UAAM;EAIN,OAAO,MAAM;EAIb,MAAM,2BAA2B;EAIjC,kBAAkB,cAAW;EAsB7B,eAAe,oBAAiB;UAW/B;UA2CA;EAKD,YAAY,UAAU,wBAC3B,OAAO,GACP,UAAU,2BAA2B,KACpC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isMessageNotSentError } from "../../types/error.js";
|
|
1
2
|
import { symbolInnerMessage } from "../utils/external-store-message.js";
|
|
2
3
|
import { EventSubscriptionSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "../../subscribable/subscribable.js";
|
|
3
4
|
import { ThreadComposerRuntimeImpl } from "./composer-runtime.js";
|
|
@@ -138,7 +139,10 @@ var ThreadRuntimeImpl = class {
|
|
|
138
139
|
return this._threadBinding.getStateState();
|
|
139
140
|
}
|
|
140
141
|
append(message) {
|
|
141
|
-
this._threadBinding.getState().append(toAppendMessage(this._threadBinding.getState().messages, message));
|
|
142
|
+
const task = this._threadBinding.getState().append(toAppendMessage(this._threadBinding.getState().messages, message));
|
|
143
|
+
Promise.resolve(task).catch((error) => {
|
|
144
|
+
if (!isMessageNotSentError(error)) throw error;
|
|
145
|
+
});
|
|
142
146
|
}
|
|
143
147
|
deleteMessage(messageId) {
|
|
144
148
|
return this._threadBinding.getState().deleteMessage(messageId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.js","names":["ThreadSuggestion","RuntimeCapabilities","ThreadRuntimeCore","SpeechState","VoiceSessionState","ThreadRuntimeEventCallback","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ExportedMessageRepository","ThreadMessageLike","MessageRuntime","MessageRuntimeImpl","MessageState","NestedSubscriptionSubject","ShallowMemoizeSubject","SKIP_UPDATE","SubscribableWithState","ThreadComposerRuntime","ThreadComposerRuntimeImpl","MessageRuntimePath","ThreadListItemRuntimePath","ThreadRuntimePath","ThreadListItemState","AppendMessage","ThreadMessage","Unsubscribe","RunConfig","EventSubscriptionSubject","symbolInnerMessage","ModelContext","ChatModelRunOptions","ChatModelRunResult","ReadonlyJSONValue","CreateStartRunConfig","parentId","sourceId","runConfig","CreateResumeRunConfig","stream","options","AsyncGenerator","toResumeRunConfig","message","toStartRunConfig","CreateAppendMessage","role","content","attachments","metadata","createdAt","Date","startRun","toAppendMessage","messages","at","id","type","text","custom","ThreadRuntimeCoreBinding","outerSubscribe","callback","ThreadListItemRuntimeBinding","ThreadState","threadId","isDisabled","isLoading","isRunning","capabilities","state","suggestions","extras","speech","voice","getThreadRuntimeCoreIsRunning","runtime","undefined","lastMessage","status","getThreadState","threadListItemState","Object","freeze","ThreadRuntime","path","composer","getState","append","deleteMessage","messageId","Promise","config","resumeRun","exportExternalState","importExternalState","subscribe","cancelRun","getModelContext","export","import","repository","reset","initialMessages","getMessageByIndex","idx","getMessageById","stopSpeaking","connectVoice","disconnectVoice","getVoiceVolume","subscribeVoiceVolume","muteVoice","unmuteVoice","unstable_on","event","E","ThreadRuntimeImpl","_threadBinding","__internal_threadBinding","getStateState","constructor","threadBinding","threadListItemBinding","stateBinding","sub1","sub2","ref","composerSource","__internal_bindMethods","bind","data","Error","_getMessageRuntime","messageSelector","index","JSON","stringify","speechState","thread","branches","getBranches","isLast","branchNumber","indexOf","branchCount","length","_eventSubscriptionSubjects","Map","subject","get","binding","set","payload"],"sources":["../../../src/runtime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\n/**\n * The canonical `isRunning` derivation. A runtime that tracks run state itself\n * reports it directly; the rest fall back to the trailing assistant message.\n */\nexport const getThreadRuntimeCoreIsRunning = (\n runtime: ThreadRuntimeCore,\n): boolean => {\n if (runtime.isRunning !== undefined) return runtime.isRunning;\n const lastMessage = runtime.messages.at(-1);\n return (\n lastMessage?.role === \"assistant\" && lastMessage.status.type === \"running\"\n );\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning: getThreadRuntimeCoreIsRunning(runtime),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n deleteMessage(messageId: string): void | Promise<void>;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n\n connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => {\n sub1();\n sub2();\n };\n },\n });\n\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.deleteMessage = this.deleteMessage.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\n }\n\n public readonly composer;\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n }\n\n public deleteMessage(messageId: string) {\n return this._threadBinding.getState().deleteMessage(messageId);\n }\n\n public subscribe(callback: () => void) {\n return this._threadBinding.subscribe(callback);\n }\n\n public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n}\n"],"mappings":";;;;;AA0DA,MAAM0C,qBAAqBC,YAAoD;CAC7E,OAAO;EACLR,UAAUQ,QA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AM,EAAE5C,SAASR,UAAUoG,UAAUzE,SAAS,KAAK,CAAC;IAEpD,MAAM,EAAER,UAAUmB,QAAQiE,gBACxB,KAAKpB,eAAe/B,SAAS;IAE/B,IAAI,CAAC5C,WAAWR,aAAa0C,KAAAA,KAAa0D,UAAU1D,KAAAA,GAClD,OAAO7D;IAIT,MAAM4H,WAFS,KAAKtB,eAAe/B,SAElBoD,CAAM,CAACE,YAAYlG,QAAQa,EAAE;IAE9C,OAAO;KACL,GAAGb;MACGd,qBAAsBc,QAAgBd;KAE5C0G;KACAO,QAAQxF,SAASC,GAAG,EAAE,CAAC,EAAEC,OAAOb,QAAQa;KACxCrB;KAEA4G,cAAcH,SAASI,QAAQrG,QAAQa,EAAE,IAAI;KAC7CyF,aAAaL,SAASM;KAEtBzE,QACEiE,aAAahD,cAAc/C,QAAQa,KAAKkF,cAAc7D,KAAAA;IAC1D;GACF;GACAmB,YAAYlC,aAAa,KAAKwD,eAAetB,UAAUlC,QAAQ;EACjE,CAAC,GACD,KAAKwD,cACP;CACF;CAEA,6CAAqC,IAAI8B,IAGvC;CAEF,YACEjC,OACArD,UACa;EACb,IAAIuF,UAAU,KAAKF,2BAA2BG,IAAInC,KAAK;EACvD,IAAI,CAACkC,SAAS;GACZA,UAAU,IAAIzH,yBAAiD;IAC7DuF;IACAoC,SAAS,KAAKjC;GAChB,CAAC;GACD,KAAK6B,2BAA2BK,IAAIrC,OAAOkC,OAAO;EACpD;EACA,OAAOA,QAAQrD,UAAUlC,QAAuC;CAClE;AACF"}
|
|
1
|
+
{"version":3,"file":"thread-runtime.js","names":["ThreadSuggestion","RuntimeCapabilities","ThreadRuntimeCore","SpeechState","VoiceSessionState","ThreadRuntimeEventCallback","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ExportedMessageRepository","ThreadMessageLike","MessageRuntime","MessageRuntimeImpl","MessageState","NestedSubscriptionSubject","ShallowMemoizeSubject","SKIP_UPDATE","SubscribableWithState","ThreadComposerRuntime","ThreadComposerRuntimeImpl","MessageRuntimePath","ThreadListItemRuntimePath","ThreadRuntimePath","ThreadListItemState","AppendMessage","ThreadMessage","Unsubscribe","isMessageNotSentError","RunConfig","EventSubscriptionSubject","symbolInnerMessage","ModelContext","ChatModelRunOptions","ChatModelRunResult","ReadonlyJSONValue","CreateStartRunConfig","parentId","sourceId","runConfig","CreateResumeRunConfig","stream","options","AsyncGenerator","toResumeRunConfig","message","toStartRunConfig","CreateAppendMessage","role","content","attachments","metadata","createdAt","Date","startRun","toAppendMessage","messages","at","id","type","text","custom","ThreadRuntimeCoreBinding","outerSubscribe","callback","ThreadListItemRuntimeBinding","ThreadState","threadId","isDisabled","isLoading","isRunning","capabilities","state","suggestions","extras","speech","voice","getThreadRuntimeCoreIsRunning","runtime","undefined","lastMessage","status","getThreadState","threadListItemState","Object","freeze","ThreadRuntime","path","composer","getState","append","deleteMessage","messageId","Promise","config","resumeRun","exportExternalState","importExternalState","subscribe","cancelRun","getModelContext","export","import","repository","reset","initialMessages","getMessageByIndex","idx","getMessageById","stopSpeaking","connectVoice","disconnectVoice","getVoiceVolume","subscribeVoiceVolume","muteVoice","unmuteVoice","unstable_on","event","E","ThreadRuntimeImpl","_threadBinding","__internal_threadBinding","getStateState","constructor","threadBinding","threadListItemBinding","stateBinding","sub1","sub2","ref","composerSource","__internal_bindMethods","bind","task","resolve","catch","error","data","Error","_getMessageRuntime","messageSelector","index","JSON","stringify","speechState","thread","branches","getBranches","isLast","branchNumber","indexOf","branchCount","length","_eventSubscriptionSubjects","Map","subject","get","binding","set","payload"],"sources":["../../../src/runtime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { isMessageNotSentError } from \"../../types/error\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId: message.parentId ?? messages.at(-1)?.id ?? null,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\n/**\n * The canonical `isRunning` derivation. A runtime that tracks run state itself\n * reports it directly; the rest fall back to the trailing assistant message.\n */\nexport const getThreadRuntimeCoreIsRunning = (\n runtime: ThreadRuntimeCore,\n): boolean => {\n if (runtime.isRunning !== undefined) return runtime.isRunning;\n const lastMessage = runtime.messages.at(-1);\n return (\n lastMessage?.role === \"assistant\" && lastMessage.status.type === \"running\"\n );\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning: getThreadRuntimeCoreIsRunning(runtime),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n deleteMessage(messageId: string): void | Promise<void>;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n\n connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => {\n sub1();\n sub2();\n };\n },\n });\n\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.deleteMessage = this.deleteMessage.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\n }\n\n public readonly composer;\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n const task = this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n // An undispatched send is reported to the composer, so it is a control\n // signal rather than a failure to surface; every other rejection keeps\n // reaching the host untouched.\n void Promise.resolve(task).catch((error) => {\n if (!isMessageNotSentError(error)) throw error;\n });\n }\n\n public deleteMessage(messageId: string) {\n return this._threadBinding.getState().deleteMessage(messageId);\n }\n\n public subscribe(callback: () => void) {\n return this._threadBinding.subscribe(callback);\n }\n\n public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe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BaseSubscribable implemen
|
|
|
34
34
|
get quote(): QuoteInfo | undefined;
|
|
35
35
|
setQuote(quote: QuoteInfo | undefined): void;
|
|
36
36
|
setText(value: string): void;
|
|
37
|
+
private _rebaseDictation;
|
|
37
38
|
setRole(role: MessageRole): void;
|
|
38
39
|
setRunConfig(runConfig: RunConfig): void;
|
|
39
40
|
protected _isSending: boolean;
|
|
@@ -47,6 +48,30 @@ declare abstract class BaseComposerRuntimeCore extends BaseSubscribable implemen
|
|
|
47
48
|
reset(): Promise<void>;
|
|
48
49
|
clearAttachments(): Promise<void>;
|
|
49
50
|
send(options?: SendOptions): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Take a message back into the composer when it has nowhere else to live:
|
|
53
|
+
* a send the runtime never dispatched, or a message a cancelled run is
|
|
54
|
+
* removing from the thread. Reports whether the composer accepted it, so a
|
|
55
|
+
* caller that is also removing the message can keep it instead of dropping
|
|
56
|
+
* it. Refused, and left untouched, while the composer holds anything of its
|
|
57
|
+
* own.
|
|
58
|
+
*/
|
|
59
|
+
restoreDraft(draft: {
|
|
60
|
+
text: string;
|
|
61
|
+
quote?: QuoteInfo | undefined;
|
|
62
|
+
attachments?: readonly Attachment[] | undefined;
|
|
63
|
+
}): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Inverse of `restoreDraft`: clears the composer while it still holds
|
|
66
|
+
* exactly the given draft. A draft the user has edited since is left
|
|
67
|
+
* untouched.
|
|
68
|
+
*/
|
|
69
|
+
retractDraft(draft: {
|
|
70
|
+
text: string;
|
|
71
|
+
quote?: QuoteInfo | undefined;
|
|
72
|
+
attachments?: readonly Attachment[] | undefined;
|
|
73
|
+
}): void;
|
|
74
|
+
private _restoreUnsentDraft;
|
|
50
75
|
cancel(): void;
|
|
51
76
|
get queue(): readonly QueueItemState[];
|
|
52
77
|
moveQueueItem(_queueItemId: string, _placement: QueuePlacement): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":";;;;;;;;;;uBA2CsB,gCACZ,4BACG;WAEK;qBAEG,wBAAwB;qBACxB,uBAAuB;YAEhC,2BACR;IAAY;MAAa,SAAS;;KAClC,SAAS,GAAG,kBAAkB,sCAAsC;MAW3D;UAIH;MACG,wBAAW;YAIZ,eAAe,gBAAgB;eAKrB;eACA;MAET;UAIH;MAEJ;UAII;MAEJ;UAII;MAEJ,aAAS;UAIL;MAEJ,SAAK;EAIF,SAAS,OAAO;EAOhB,QAAQ;UAWP;EASD,QAAQ,MAAM;EAOd,aAAa,WAAW;YAOrB;UACF;UACA;UACA;UAEA;UAQA;UAOA;UAMM;EAQD,SAAK;EA8BL,oBAAgB;EAQhB,KAAK,UAAU,cAAW;;;;;;;;;EAoGhC,aAAa;IAClB;IACA,QAAQ;IACR,uBAAuB;;;;;;;EAsBlB,aAAa;IAClB;IACA,QAAQ;IACR,uBAAuB;;UAuBjB;EAcD;MAII,kBAAkB;EAItB,cACL,sBACA,YAAY;EAEP,gBAAgB;qBAEJ,WACjB,SAAS,KAAK,yCACd,UAAU,qBACF;qBACS;EAEb,cAAc,kBAAkB,OAAO,mBAAgB;UAuIrD;EAqBF,iBAAiB,uBAAoB;UAmCnC;UACA;UACA;UACA;UACA;UACA;UACA;UACA;MAEG,aAAa;UAIhB;EAUD;EA6FA;UAUC;UAuBA;YAKE,wBAAwB,UAAU,0BAC1C,OAAO,GACP,SAAS,4BAA4B;EAQhC,YAAY,UAAU,0BAC3B,OAAO,GACP,UAAU,6BAA6B"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { generateId } from "../../utils/id.js";
|
|
2
2
|
import { fileMatchesAccept } from "../../adapters/attachment.js";
|
|
3
|
+
import { isMessageNotSentError } from "../../types/error.js";
|
|
3
4
|
import { EMPTY_QUEUE_ITEMS } from "../../store/scopes/queue-item.js";
|
|
4
5
|
import { notifyEventListeners } from "../../utils/notify-event-listeners.js";
|
|
5
6
|
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
@@ -59,17 +60,19 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
59
60
|
setText(value) {
|
|
60
61
|
if (this._text === value) return;
|
|
61
62
|
this._text = value;
|
|
62
|
-
|
|
63
|
-
this._dictationBaseText = value;
|
|
64
|
-
this._currentInterimText = "";
|
|
65
|
-
const { status, inputDisabled } = this._dictation;
|
|
66
|
-
this._dictation = inputDisabled ? {
|
|
67
|
-
status,
|
|
68
|
-
inputDisabled
|
|
69
|
-
} : { status };
|
|
70
|
-
}
|
|
63
|
+
this._rebaseDictation(value);
|
|
71
64
|
this._notifySubscribers();
|
|
72
65
|
}
|
|
66
|
+
_rebaseDictation(value) {
|
|
67
|
+
if (!this._dictation) return;
|
|
68
|
+
this._dictationBaseText = value;
|
|
69
|
+
this._currentInterimText = "";
|
|
70
|
+
const { status, inputDisabled } = this._dictation;
|
|
71
|
+
this._dictation = inputDisabled ? {
|
|
72
|
+
status,
|
|
73
|
+
inputDisabled
|
|
74
|
+
} : { status };
|
|
75
|
+
}
|
|
73
76
|
setRole(role) {
|
|
74
77
|
if (this._role === role) return;
|
|
75
78
|
this._role = role;
|
|
@@ -153,6 +156,7 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
153
156
|
if (generation === this._sendGeneration) {
|
|
154
157
|
if (!this.text.trim() && this._quote === void 0) {
|
|
155
158
|
this._text = text;
|
|
159
|
+
this._rebaseDictation(text);
|
|
156
160
|
this._quote = quote;
|
|
157
161
|
this._notifySubscribers();
|
|
158
162
|
}
|
|
@@ -183,10 +187,59 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
183
187
|
runConfig: this.runConfig,
|
|
184
188
|
metadata: { custom: { ...quote ? { quote } : {} } }
|
|
185
189
|
};
|
|
186
|
-
const
|
|
187
|
-
|
|
190
|
+
const draft = {
|
|
191
|
+
text,
|
|
192
|
+
quote,
|
|
193
|
+
attachments: finalAttachments
|
|
194
|
+
};
|
|
195
|
+
let sendTask;
|
|
196
|
+
try {
|
|
197
|
+
sendTask = this.handleSend(message, options);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
this._restoreUnsentDraft(error, generation, draft);
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
if (sendTask) sendTask.catch((error) => {
|
|
203
|
+
this._restoreUnsentDraft(error, generation, draft);
|
|
204
|
+
});
|
|
188
205
|
this._notifyEventSubscribers("send", {});
|
|
189
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* Take a message back into the composer when it has nowhere else to live:
|
|
209
|
+
* a send the runtime never dispatched, or a message a cancelled run is
|
|
210
|
+
* removing from the thread. Reports whether the composer accepted it, so a
|
|
211
|
+
* caller that is also removing the message can keep it instead of dropping
|
|
212
|
+
* it. Refused, and left untouched, while the composer holds anything of its
|
|
213
|
+
* own.
|
|
214
|
+
*/
|
|
215
|
+
restoreDraft(draft) {
|
|
216
|
+
if (this._text.trim() || this._quote !== void 0 || this._attachments.length > 0) return false;
|
|
217
|
+
this._text = draft.text;
|
|
218
|
+
this._rebaseDictation(draft.text);
|
|
219
|
+
this._quote = draft.quote;
|
|
220
|
+
this._attachments = draft.attachments ?? [];
|
|
221
|
+
this._notifySubscribers();
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Inverse of `restoreDraft`: clears the composer while it still holds
|
|
226
|
+
* exactly the given draft. A draft the user has edited since is left
|
|
227
|
+
* untouched.
|
|
228
|
+
*/
|
|
229
|
+
retractDraft(draft) {
|
|
230
|
+
const attachmentsUntouched = draft.attachments !== void 0 ? this._attachments === draft.attachments : this._attachments.length === 0;
|
|
231
|
+
if (this._text !== draft.text || this._quote !== draft.quote || !attachmentsUntouched) return;
|
|
232
|
+
this._text = "";
|
|
233
|
+
this._rebaseDictation("");
|
|
234
|
+
this._quote = void 0;
|
|
235
|
+
this._attachments = [];
|
|
236
|
+
this._notifySubscribers();
|
|
237
|
+
}
|
|
238
|
+
_restoreUnsentDraft(error, generation, draft) {
|
|
239
|
+
if (!isMessageNotSentError(error)) return;
|
|
240
|
+
if (generation !== this._sendGeneration) return;
|
|
241
|
+
this.restoreDraft(draft);
|
|
242
|
+
}
|
|
190
243
|
cancel() {
|
|
191
244
|
this.handleCancel();
|
|
192
245
|
}
|