@assistant-ui/core 0.2.18 → 0.2.20
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 +4 -2
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +2 -1
- package/dist/internal.js +2 -1
- package/dist/model-context/interactable-composer-metadata.d.ts +105 -0
- package/dist/model-context/interactable-composer-metadata.d.ts.map +1 -0
- package/dist/model-context/interactable-composer-metadata.js +259 -0
- package/dist/model-context/interactable-composer-metadata.js.map +1 -0
- package/dist/model-context/registry.d.ts.map +1 -1
- package/dist/model-context/registry.js +1 -0
- package/dist/model-context/registry.js.map +1 -1
- package/dist/model-context/types.d.ts +6 -0
- package/dist/model-context/types.d.ts.map +1 -1
- package/dist/model-context/types.js +4 -0
- package/dist/model-context/types.js.map +1 -1
- package/dist/react/AssistantProvider.d.ts +1 -1
- package/dist/react/AssistantProvider.js +1 -1
- package/dist/react/AssistantRuntimeProvider.d.ts +1 -1
- package/dist/react/RuntimeAdapter.js +1 -1
- package/dist/react/client/Interactables.d.ts +8 -2
- package/dist/react/client/Interactables.d.ts.map +1 -1
- package/dist/react/client/Interactables.js +190 -94
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/Tools.js +1 -1
- package/dist/react/client/interactable-model-context.d.ts +9 -6
- package/dist/react/client/interactable-model-context.d.ts.map +1 -1
- package/dist/react/client/interactable-model-context.js +154 -32
- package/dist/react/client/interactable-model-context.js.map +1 -1
- package/dist/react/index.d.ts +15 -6
- package/dist/react/index.js +12 -5
- package/dist/react/interactables-legacy/Interactables.d.ts +12 -0
- package/dist/react/interactables-legacy/Interactables.d.ts.map +1 -0
- package/dist/react/interactables-legacy/Interactables.js +264 -0
- package/dist/react/interactables-legacy/Interactables.js.map +1 -0
- package/dist/react/interactables-legacy/interactable-model-context.d.ts +12 -0
- package/dist/react/interactables-legacy/interactable-model-context.d.ts.map +1 -0
- package/dist/react/interactables-legacy/interactable-model-context.js +54 -0
- package/dist/react/interactables-legacy/interactable-model-context.js.map +1 -0
- package/dist/react/interactables-legacy/scopes.d.ts +58 -0
- package/dist/react/interactables-legacy/scopes.d.ts.map +1 -0
- package/dist/react/interactables-legacy/scopes.js +0 -0
- package/dist/react/interactables-legacy/useAssistantInteractable.d.ts +31 -0
- package/dist/react/interactables-legacy/useAssistantInteractable.d.ts.map +1 -0
- package/dist/react/{model-context → interactables-legacy}/useAssistantInteractable.js +6 -2
- package/dist/react/interactables-legacy/useAssistantInteractable.js.map +1 -0
- package/dist/react/interactables-legacy/useInteractableState.d.ts +21 -0
- package/dist/react/interactables-legacy/useInteractableState.d.ts.map +1 -0
- package/dist/react/interactables-legacy/useInteractableState.js +84 -0
- package/dist/react/interactables-legacy/useInteractableState.js.map +1 -0
- package/dist/react/model-context/interactableTool.d.ts +53 -0
- package/dist/react/model-context/interactableTool.d.ts.map +1 -0
- package/dist/react/model-context/interactableTool.js +188 -0
- package/dist/react/model-context/interactableTool.js.map +1 -0
- package/dist/react/model-context/useAssistantContext.js +1 -1
- package/dist/react/model-context/useAssistantDataUI.js +1 -1
- package/dist/react/model-context/useAssistantInstructions.js +1 -1
- package/dist/react/model-context/useAssistantTool.js +1 -1
- package/dist/react/model-context/useAssistantToolUI.js +1 -1
- package/dist/react/model-context/useAuiToolOverrides.js +1 -1
- package/dist/react/model-context/useInteractable.d.ts +73 -0
- package/dist/react/model-context/useInteractable.d.ts.map +1 -0
- package/dist/react/model-context/useInteractable.js +100 -0
- package/dist/react/model-context/useInteractable.js.map +1 -0
- package/dist/react/model-context/useInteractableState.d.ts +8 -5
- package/dist/react/model-context/useInteractableState.d.ts.map +1 -1
- package/dist/react/model-context/useInteractableState.js +48 -48
- package/dist/react/model-context/useInteractableState.js.map +1 -1
- package/dist/react/model-context/useInteractableVersions.d.ts +19 -0
- package/dist/react/model-context/useInteractableVersions.d.ts.map +1 -0
- package/dist/react/model-context/useInteractableVersions.js +51 -0
- package/dist/react/model-context/useInteractableVersions.js.map +1 -0
- package/dist/react/primitive-hooks/useThreadMessageIds.d.ts +15 -0
- package/dist/react/primitive-hooks/useThreadMessageIds.d.ts.map +1 -0
- package/dist/react/primitive-hooks/useThreadMessageIds.js +26 -0
- package/dist/react/primitive-hooks/useThreadMessageIds.js.map +1 -0
- package/dist/react/primitive-hooks/useVoice.js +1 -1
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js +1 -1
- package/dist/react/primitives/composer/ComposerAttachments.js +1 -1
- package/dist/react/primitives/composer/ComposerQueue.js +1 -1
- package/dist/react/primitives/generativeUI/GenerativeUI.d.ts.map +1 -1
- package/dist/react/primitives/generativeUI/GenerativeUI.js +2 -2
- package/dist/react/primitives/generativeUI/GenerativeUI.js.map +1 -1
- package/dist/react/primitives/message/MessageAttachments.js +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.js +1 -1
- package/dist/react/primitives/message/MessageParts.js +1 -1
- package/dist/react/primitives/message/MessageQuote.js +1 -1
- package/dist/react/primitives/part/PartMessages.d.ts +5 -2
- package/dist/react/primitives/part/PartMessages.d.ts.map +1 -1
- package/dist/react/primitives/part/PartMessages.js +8 -8
- package/dist/react/primitives/part/PartMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.d.ts +31 -1
- package/dist/react/primitives/thread/ThreadMessages.d.ts.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.js +64 -2
- package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadSuggestions.js +1 -1
- package/dist/react/primitives/threadList/ThreadListItems.js +1 -1
- package/dist/react/providers/MessageByIdProvider.d.ts +9 -0
- package/dist/react/providers/MessageByIdProvider.d.ts.map +1 -0
- package/dist/react/providers/MessageByIdProvider.js +57 -0
- package/dist/react/providers/MessageByIdProvider.js.map +1 -0
- package/dist/react/providers/ReadonlyThreadProvider.js +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +3 -0
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +16 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +1 -1
- package/dist/react/runtimes/cloud/auiV0.js +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +1 -1
- package/dist/react/runtimes/createRuntimeExtras.d.ts +20 -0
- package/dist/react/runtimes/createRuntimeExtras.d.ts.map +1 -0
- package/dist/react/runtimes/createRuntimeExtras.js +43 -0
- package/dist/react/runtimes/createRuntimeExtras.js.map +1 -0
- package/dist/react/runtimes/useLocalRuntime.js +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.d.ts.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js +6 -2
- package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
- package/dist/react/runtimes/useStreamingTiming.d.ts +26 -0
- package/dist/react/runtimes/useStreamingTiming.d.ts.map +1 -0
- package/dist/react/runtimes/useStreamingTiming.js +43 -0
- package/dist/react/runtimes/useStreamingTiming.js.map +1 -0
- package/dist/react/types/scopes/interactables.d.ts +40 -24
- package/dist/react/types/scopes/interactables.d.ts.map +1 -1
- package/dist/react/types/store-augmentation.d.ts +3 -1
- package/dist/react/types/store-augmentation.d.ts.map +1 -1
- package/dist/react/utils/useJSONEqual.d.ts +11 -0
- package/dist/react/utils/useJSONEqual.d.ts.map +1 -0
- package/dist/react/utils/useJSONEqual.js +30 -0
- package/dist/react/utils/useJSONEqual.js.map +1 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts +5 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +13 -0
- package/dist/runtime/base/base-composer-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 +6 -1
- 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 +4 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
- package/dist/runtime/utils/message-repository.d.ts +1 -0
- package/dist/runtime/utils/message-repository.d.ts.map +1 -1
- package/dist/runtime/utils/message-repository.js +6 -3
- package/dist/runtime/utils/message-repository.js.map +1 -1
- package/dist/runtime/utils/streaming-timing.d.ts +59 -0
- package/dist/runtime/utils/streaming-timing.d.ts.map +1 -0
- package/dist/runtime/utils/streaming-timing.js +76 -0
- package/dist/runtime/utils/streaming-timing.js.map +1 -0
- package/dist/runtime/utils/thread-message-like.js +2 -1
- package/dist/runtime/utils/thread-message-like.js.map +1 -1
- package/dist/runtimes/external-store/external-store-adapter.d.ts +26 -1
- 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 +9 -0
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js +19 -0
- 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 +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/remote-thread-list/types.d.ts +12 -0
- package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
- package/dist/store/clients/suggestions.js +1 -1
- package/dist/store/clients/thread-message-client.js +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.js +1 -1
- package/dist/store/runtime-clients/message-runtime-client.js +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.js +1 -1
- package/dist/tests/remote-thread-list-test-helpers.d.ts +1 -1
- package/dist/tests/remote-thread-list-test-helpers.d.ts.map +1 -1
- package/dist/tests/remote-thread-list-test-helpers.js +3 -2
- package/dist/tests/remote-thread-list-test-helpers.js.map +1 -1
- package/package.json +9 -9
- package/src/index.ts +17 -0
- package/src/internal.ts +7 -0
- package/src/model-context/interactable-composer-metadata.test.ts +550 -0
- package/src/model-context/interactable-composer-metadata.ts +395 -0
- package/src/model-context/registry.ts +5 -0
- package/src/model-context/types.ts +12 -0
- package/src/react/client/Interactables.test.ts +358 -0
- package/src/react/client/Interactables.ts +339 -86
- package/src/react/client/interactable-model-context.test.ts +418 -0
- package/src/react/client/interactable-model-context.ts +252 -58
- package/src/react/index.ts +72 -3
- package/src/react/interactables-legacy/Interactables.ts +332 -0
- package/src/react/interactables-legacy/interactable-model-context.test.ts +54 -0
- package/src/react/interactables-legacy/interactable-model-context.ts +80 -0
- package/src/react/interactables-legacy/scopes.ts +66 -0
- package/src/react/{model-context → interactables-legacy}/useAssistantInteractable.ts +10 -1
- package/src/react/interactables-legacy/useInteractableState.ts +67 -0
- package/src/react/model-context/interactableTool.tsx +175 -0
- package/src/react/model-context/useInteractable.ts +233 -0
- package/src/react/model-context/useInteractableState.ts +31 -23
- package/src/react/model-context/useInteractableVersions.ts +48 -0
- package/src/react/primitive-hooks/useThreadMessageIds.ts +27 -0
- package/src/react/primitives/generativeUI/GenerativeUI.tsx +5 -1
- package/src/react/primitives/part/PartMessages.test.tsx +17 -0
- package/src/react/primitives/part/PartMessages.tsx +13 -8
- package/src/react/primitives/thread/ThreadMessages.tsx +67 -0
- package/src/react/providers/MessageByIdProvider.tsx +23 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +21 -1
- package/src/react/runtimes/createRuntimeExtras.test.ts +58 -0
- package/src/react/runtimes/createRuntimeExtras.ts +68 -0
- package/src/react/runtimes/createRuntimeExtras.use.test.ts +50 -0
- package/src/react/runtimes/useRemoteThreadListRuntime.ts +13 -1
- package/src/react/runtimes/useStreamingTiming.ts +68 -0
- package/src/react/types/scopes/interactables.ts +45 -23
- package/src/react/types/store-augmentation.ts +4 -2
- package/src/react/utils/useJSONEqual.ts +20 -0
- package/src/runtime/base/base-composer-runtime-core.ts +13 -0
- package/src/runtime/base/default-edit-composer-runtime-core.ts +18 -1
- package/src/runtime/base/default-thread-composer-runtime-core.ts +11 -1
- package/src/runtime/utils/message-repository.ts +11 -7
- package/src/runtime/utils/streaming-timing.test.ts +301 -0
- package/src/runtime/utils/streaming-timing.ts +161 -0
- package/src/runtime/utils/thread-message-like.ts +2 -1
- package/src/runtimes/external-store/external-store-adapter.ts +28 -0
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +33 -1
- package/src/runtimes/local/local-thread-runtime-core.ts +4 -1
- package/src/runtimes/remote-thread-list/types.ts +13 -0
- package/src/tests/MessageRepository.test.ts +2 -0
- package/src/tests/composer-can-send.test.ts +1 -0
- package/src/tests/default-edit-composer-runtime-core.test.ts +78 -1
- package/src/tests/default-thread-composer-runtime-core.test.ts +82 -0
- package/src/tests/external-store-thread-runtime-core.test.ts +337 -0
- package/src/tests/groupParts.test.ts +32 -0
- package/src/tests/remote-thread-list-reactive-threadId.test.ts +90 -0
- package/src/tests/remote-thread-list-test-helpers.ts +2 -1
- package/src/tests/thread-message-like.test.ts +50 -0
- package/dist/react/model-context/useAssistantInteractable.d.ts +0 -22
- package/dist/react/model-context/useAssistantInteractable.d.ts.map +0 -1
- package/dist/react/model-context/useAssistantInteractable.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","EMPTY_ARRAY","Object","freeze","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","suggestions","extras","undefined","_converter","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","incoming","headId","at","message","id","repository","resetHead","getMessages","incomingIds","Set","map","parentId","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","i","parent","ensureInitialized","_notifyEventSubscribers","optimisticId","content","metadata","isOptimistic","type","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","result","isError","artifact","modelContent","err","console","error","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","clear","visit","Array","isArray","part","set","get","branchId","updateMessages","append","Promise","isEdit","enqueue","steer","startRun","abort","onNew","messageIndex","findIndex","filter","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","cancelRun","head","previousMessage","composer","text","trim","setText","setTimeout","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type { ExternalStoreAdapter } from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n const incoming = store.messageRepository.messages;\n const headId =\n store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;\n\n if (oldStore && oldStore.messageRepository === store.messageRepository) {\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n } else {\n const incomingIds = new Set(incoming.map(({ message }) => message.id));\n for (const { message, parentId } of incoming) {\n this.repository.addOrUpdateMessage(parentId, message);\n }\n for (const { message } of this.repository.export().messages) {\n if (!incomingIds.has(message.id)) {\n this.repository.deleteMessage(message.id);\n }\n }\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n }\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n });\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isEdit = message.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // Buffering does not start a run, so the tool-abort below must wait until\n // the queue flushes. By then the prior run (and its tools) has settled.\n if (!isEdit && this._store.queue) {\n this._store.queue.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n this._store.queue?.clear(\"edit\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string) {\n this._store?.queue?.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n this._store.queue?.clear(\"reload\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. We only clear adapter-side\n // tool statuses when the tracker is the source of truth — otherwise\n // we'd wipe statuses the adapter is managing on its own.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._store.setToolStatuses?.({});\n }\n\n this._store.onLoadExternalState(state);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.queue?.clear(\"cancel-run\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n this._store.onCancel();\n\n // Drop an empty optimistic head (placeholder or pre-stream message); a\n // partially-streamed one is kept and re-supplied by the store on resync.\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this._notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult?.(options);\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n this._store.onRespondToToolApproval(options);\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage[]);\n }\n };\n}\n"],"mappings":";;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xI,OAAOyI,kBAAkB;GAChC,KAAKzI,OAAOyI,iBAAiBL,OAAO;GACpC;EACF;EAEA,MAAM,IAAIxH,MACR,aAAawH,QAAQ3D,WAAU,4BACjC;CACF;CAEA,sBAA6B2D,SAAuC;EAClE,IAAI,CAAC,KAAKpI,OAAO2I,yBACf,MAAM,IAAI/H,MAAM,0CAA0C;EAC5D,KAAKZ,OAAO2I,wBAAwBP,OAAO;CAC7C;CAEA,MAAsBQ,iBAAgD;EACpE,MAAMC,OAAO,IAAInL,kBAAkB;EACnCmL,KAAKC,OAAOrL,0BAA0BsL,UAAUH,mBAAmB,CAAA,CAAE,CAAC;EACtE,KAAK1C,eAAe2C,KAAK1G,YAAY,CAAC;CACxC;CAEA,OAAuB6G,MAAiC;EACtD,MAAMF,OAAOE,IAAI;EAEjB,IAAI,KAAKhJ,OAAOiJ,UACd,KAAKjJ,OAAOiJ,SAAS,KAAKhH,WAAWE,YAAY,CAAC;CAEtD;CAEA,kBAA0BzD,aAAuC;EAE/D,IADqB,KAAKsB,OAAO4C,mBAAmBtC,KAAAA,GAElD,KAAKN,OAAOoB,cAAc1C,SAASyK,QAAQtM,wBAAwB,CAAC;OAGpE,KAAKmD,OAAOoB,cAAc1C,QAA2B;CAEzD;AACF"}
|
|
1
|
+
{"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","ExternalStoreBranchChange","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","EMPTY_ARRAY","Object","freeze","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","suggestions","extras","undefined","_converter","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","incoming","headId","at","message","id","repository","resetHead","getMessages","incomingIds","Set","map","parentId","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","i","parent","ensureInitialized","_notifyEventSubscribers","optimisticId","content","metadata","isOptimistic","type","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","result","isError","artifact","modelContent","err","console","error","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","clear","visit","Array","isArray","part","set","get","branchId","onBranchChange","unstable_onBranchChange","previousHeadId","canonicalHeadId","updateMessages","_notifyBranchChange","event","visibleMessageIds","append","Promise","isEdit","enqueue","steer","startRun","abort","onNew","messageIndex","findIndex","filter","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","cancelRun","head","previousMessage","composer","text","trim","setText","setTimeout","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type {\n ExternalStoreAdapter,\n ExternalStoreBranchChange,\n} from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n const incoming = store.messageRepository.messages;\n const headId =\n store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;\n\n if (oldStore && oldStore.messageRepository === store.messageRepository) {\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n } else {\n const incomingIds = new Set(incoming.map(({ message }) => message.id));\n for (const { message, parentId } of incoming) {\n this.repository.addOrUpdateMessage(parentId, message);\n }\n for (const { message } of this.repository.export().messages) {\n if (!incomingIds.has(message.id)) {\n this.repository.deleteMessage(message.id);\n }\n }\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n }\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n });\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n const onBranchChange = this._store.unstable_onBranchChange;\n const previousHeadId = onBranchChange\n ? this.repository.canonicalHeadId\n : null;\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n if (onBranchChange) {\n this._notifyBranchChange(previousHeadId, onBranchChange);\n }\n }\n\n /**\n * Emit `unstable_onBranchChange` for an explicit branch switch. Reads the\n * canonical head from the repository (which skips optimistic/transient\n * messages) and de-dupes switches that leave the canonical head unchanged.\n * Comparing against the head observed just before the switch — rather than the\n * last emitted head — keeps a switch firing after an adapter resync moved the\n * head elsewhere in the meantime.\n */\n private _notifyBranchChange(\n previousHeadId: string | null,\n onBranchChange: (event: ExternalStoreBranchChange) => void,\n ): void {\n const headId = this.repository.canonicalHeadId;\n if (headId === previousHeadId) return;\n\n onBranchChange({\n headId,\n visibleMessageIds: this.repository.getMessages().map((m) => m.id),\n });\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isEdit = message.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // Buffering does not start a run, so the tool-abort below must wait until\n // the queue flushes. By then the prior run (and its tools) has settled.\n if (!isEdit && this._store.queue) {\n this._store.queue.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n this._store.queue?.clear(\"edit\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string) {\n this._store?.queue?.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n this._store.queue?.clear(\"reload\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. We only clear adapter-side\n // tool statuses when the tracker is the source of truth — otherwise\n // we'd wipe statuses the adapter is managing on its own.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._store.setToolStatuses?.({});\n }\n\n this._store.onLoadExternalState(state);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.queue?.clear(\"cancel-run\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n this._store.onCancel();\n\n // Drop an empty optimistic head (placeholder or pre-stream message); a\n // partially-streamed one is kept and re-supplied by the store on resync.\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this._notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult?.(options);\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n this._store.onRespondToToolApproval(options);\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage[]);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAuCA,MAAM2B,cAA2CC,OAAOC,OAAO,CAAA,CAAE;AAEjE,MAAMC,gBAAgBC,GAAWC,MAAuB;CACtD,MAAMC,QAAQL,OAAOM,KAAKH,CAAC;CAC3B,IAAIE,MAAME,WAAWP,OAAOM,KAAKF,CAAC,CAAC,CAACG,QAAQ,OAAO;CACnD,KAAK,MAAMC,OAAOH,OAChB,IAAKF,EAAUK,SAAUJ,EAAUI,MAAM,OAAO;CAElD,OAAO;AACT;AAEA,MAAaC,sBACXC,WACAC,aACG;CACH,OAAOD,aAAaC,SAASA,SAASJ,SAAS,EAAE,EAAEK,SAAS;AAC9D;AAEA,IAAaC,iCAAb,cACUrB,sBAEV;CACE,gBAA6C;EAC3CuB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,IAAWC,eAAe;EACxB,OAAO,KAAKd;CACd;CAEA;CACA;CACA;CACA,IAAWkB,YAAY;EACrB,OAAO,KAAKC,OAAOD,aAAa;CAClC;CAEA,IAAWtB,YAAiC;EAC1C,OAAO,KAAKuB,OAAOvB;CACrB;CAEA,mBAAgE;EAC9D,OAAO,KAAKmB;CACd;CAEA,IAAoBM,QAAQ;EA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;EAAA,QAuBW,QAAA;EAAA,QA2DA,gBAAA;EAmLP,MAAA;EAOA,SAAA;EAOA,aAAA;IACL,SAAA;IACA,UAAA;IACA,MAAA;IACA,OAAA;IACA;EAAA,GACC,oBAAA;EA2CI,cAAA,CAAe,QAAA,EAAU,qBAAA;EAMzB,qBAAA;IACL,UAAA;IACA,QAAA;IACA,QAAA;IACA;EAAA,GACC,4BAAA;AAAA"}
|
|
@@ -307,7 +307,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
307
307
|
}
|
|
308
308
|
try {
|
|
309
309
|
this._lastRunConfig = runConfig ?? {};
|
|
310
|
-
const context = this.getModelContext();
|
|
310
|
+
const { unstable_composerMetadata: _, ...context } = this.getModelContext();
|
|
311
311
|
runCallback = runCallback ?? this.adapters.chatModel.run.bind(this.adapters.chatModel);
|
|
312
312
|
const abortSignal = this.abortController.signal;
|
|
313
313
|
const threadId = this._getThreadId?.();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","ModelContextProvider","createMessageQueue","MessageQueueController","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","adapters","_options","contextProvider","options","__internal_setOptions","_lastRunConfig","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","Promise","__internal_setGetInitializePromise","getPromise","extras","undefined","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","history","canQueue","unstable_enableMessageQueue","run","_runAppend","finally","notifyIdle","catch","subscribe","_notifySubscribers","adapter","clear","_loadPromise","__internal_load","promise","load","resolve","then","repo","repository","import","messages","length","ensureInitialized","resume","bind","unstable_resume","startRun","parentId","headId","sourceId","runConfig","append","isTail","at","id","willRun","role","enqueue","steer","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","initPromise","newMessage","type","reason","addOrUpdateMessage","resetHead","deleteMessage","messageId","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","runCallback","status","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","signal","suggestion","promiseOrGenerator","generate","Symbol","asyncIterator","r","aborted","result","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","data","timing","maxSteps","context","getModelContext","chatModel","abortSignal","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","e","error","String","toString","cancelRun","addToolResult","toolCallId","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig } from \"../../types/message\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n void this._runAppend(message)\n .finally(() => {\n this._queueRunInFlight = false;\n this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue.adapter.clear(\"cancel-run\");\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n this._queue.adapter.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n if (this._queue && !isTail) this._queue.adapter.clear(\"edit\");\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string): void {\n this._queue?.adapter.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private async _runAppend(message: AppendMessage): Promise<void> {\n this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // queue-driven runs release from the driver settle handler; a direct\n // run (regenerate, resume) releases here\n if (!this._queueRunInFlight) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n const promiseOrGenerator = this.adapters.suggestion?.generate({\n messages: this.messages,\n });\n\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (signal.aborted) break;\n this._suggestions = r;\n this._notifySubscribers();\n }\n } else {\n const result = await promiseOrGenerator;\n if (signal.aborted) return;\n this._suggestions = result;\n this._notifySubscribers();\n }\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n }\n\n try {\n this._lastRunConfig = runConfig ?? {};\n const context = this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = this.abortController.signal;\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n // TODO this should be handled by the run result stream\n if (e instanceof AbortError) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"error\",\n error:\n e instanceof Error\n ? e.message\n : `[${typeof e}] ${new String(e).toString()}`,\n },\n });\n\n throw e;\n }\n } finally {\n this.abortController = null;\n\n if (\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\"\n ) {\n await this._options.adapters.history?.append({\n parentId,\n message: message,\n runConfig: this._lastRunConfig,\n });\n }\n }\n return message;\n }\n\n public detach() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n }\n\n public cancelRun() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (!c.result) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n}\n"],"mappings":";;;;;;;AAiCA,IAAMsB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUf,sBAEV;CACE,eAA+B;EAC7BiB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,Q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WyG,WAAW7K,QAAQoF,EAAE;EAC1D,KAAKhB,WAAW+B,mBAAmBtB,UAAU7E,OAAO;EACpD,KAAK0D,mBAAmB;EAExB,IACE,KAAKU,WAAWU,WAAW9E,QAAQoF,MACnC3G,eAAeuB,SAAS,KAAK4B,SAASqG,uBAAuB,GAE7D,KAAKL,SAAS/C,UAAU7E,SAAS,KAAKgC,cAAc,CAAC,CAACwB,YAAY,CAAC,CAAC;CAExE;AACF"}
|
|
1
|
+
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","ModelContextProvider","createMessageQueue","MessageQueueController","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","adapters","_options","contextProvider","options","__internal_setOptions","_lastRunConfig","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","Promise","__internal_setGetInitializePromise","getPromise","extras","undefined","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","history","canQueue","unstable_enableMessageQueue","run","_runAppend","finally","notifyIdle","catch","subscribe","_notifySubscribers","adapter","clear","_loadPromise","__internal_load","promise","load","resolve","then","repo","repository","import","messages","length","ensureInitialized","resume","bind","unstable_resume","startRun","parentId","headId","sourceId","runConfig","append","isTail","at","id","willRun","role","enqueue","steer","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","initPromise","newMessage","type","reason","addOrUpdateMessage","resetHead","deleteMessage","messageId","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","runCallback","status","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","signal","suggestion","promiseOrGenerator","generate","Symbol","asyncIterator","r","aborted","result","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","data","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","e","error","String","toString","cancelRun","addToolResult","toolCallId","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig } from \"../../types/message\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n void this._runAppend(message)\n .finally(() => {\n this._queueRunInFlight = false;\n this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue.adapter.clear(\"cancel-run\");\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n this._queue.adapter.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n if (this._queue && !isTail) this._queue.adapter.clear(\"edit\");\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string): void {\n this._queue?.adapter.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private async _runAppend(message: AppendMessage): Promise<void> {\n this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // queue-driven runs release from the driver settle handler; a direct\n // run (regenerate, resume) releases here\n if (!this._queueRunInFlight) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n const promiseOrGenerator = this.adapters.suggestion?.generate({\n messages: this.messages,\n });\n\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (signal.aborted) break;\n this._suggestions = r;\n this._notifySubscribers();\n }\n } else {\n const result = await promiseOrGenerator;\n if (signal.aborted) return;\n this._suggestions = result;\n this._notifySubscribers();\n }\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n }\n\n try {\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = this.abortController.signal;\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n // TODO this should be handled by the run result stream\n if (e instanceof AbortError) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"error\",\n error:\n e instanceof Error\n ? e.message\n : `[${typeof e}] ${new String(e).toString()}`,\n },\n });\n\n throw e;\n }\n } finally {\n this.abortController = null;\n\n if (\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\"\n ) {\n await this._options.adapters.history?.append({\n parentId,\n message: message,\n runConfig: this._lastRunConfig,\n });\n }\n }\n return message;\n }\n\n public detach() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n }\n\n public cancelRun() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (!c.result) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n}\n"],"mappings":";;;;;;;AAiCA,IAAMsB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUf,sBAEV;CACE,eAA+B;EAC7BiB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAE5B,aAA6B;CAC7B,iBAAiC;CAEjC,aAAqB;CACrB,IAAWQ,YAAY;EACrB,OAAO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AAS/C,UAAU7E,SAAS,KAAKgC,cAAc,CAAC,CAACwB,YAAY,CAAC,CAAC;CAExE;AACF"}
|
|
@@ -62,6 +62,18 @@ type RemoteThreadListOptions = {
|
|
|
62
62
|
* switch to a new thread.
|
|
63
63
|
*/
|
|
64
64
|
threadId?: string | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Called whenever the active thread's canonical (remote) ID changes, so the
|
|
67
|
+
* value can be treated as a managed/controlled variable (e.g. synced to a
|
|
68
|
+
* URL query param). Together with `threadId` this forms the controlled
|
|
69
|
+
* pattern: `threadId` in, `onThreadIdChange` out.
|
|
70
|
+
*
|
|
71
|
+
* Only the settled remote ID is emitted: while a freshly created thread is
|
|
72
|
+
* still optimistic (no remote ID yet) the value is `undefined`, and the real
|
|
73
|
+
* ID is emitted once the thread is initialized. The transient local ID is
|
|
74
|
+
* never surfaced.
|
|
75
|
+
*/
|
|
76
|
+
onThreadIdChange?: ((threadId: string | undefined) => void) | undefined;
|
|
65
77
|
/**
|
|
66
78
|
* When true, if this runtime is used inside another RemoteThreadListRuntime,
|
|
67
79
|
* it becomes a no-op and simply calls the runtimeHook directly.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/types.ts"],"mappings":";;;;;;KAKY,8BAAA;EACV,QAAA;EACA,UAAU;AAAA;AAAA,KAGA,oBAAA;EAAA,SACD,MAAA;EAAA,SACA,QAAA;EAAA,SACA,UAAA;EAAA,SACA,KAAA;EAAA,SACA,aAAA,GAAgB,IAAA;EAAA,SAChB,MAAA,GAAS,MAAM;AAAA;AAAA,KAGd,wBAAA;EACV,OAAA,EAAS,oBAAoB;EAC7B,UAAA;AAAA;AAAA,KAGU,2BAAA;EACV,KAAK;AAAA;AAAA,KAGK,uBAAA;EACV,IAAA,CAAK,MAAA,GAAS,2BAAA,GAA8B,OAAA,CAAQ,wBAAA;EAEpD,MAAA,CAAO,QAAA,UAAkB,QAAA,WA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AA;EAC7B,MAAA,CAAO,QAAA,WAAmB,OAAA;EAC1B,UAAA,CAAW,QAAA,WAAmB,OAAA,CAAQ,8BAAA;EACtC,aAAA,CACE,QAAA,UACA,iBAAA,WAA4B,aAAA,KAC3B,OAAA,CAAQ,eAAA;EACX,KAAA,CAAM,QAAA,WAAmB,OAAA,CAAQ,oBAAA;EAvBvB;AAGZ;;;;AACO;AAGP;;;;EA4BE,iBAAA,GAAoB,aAAA,CAAc,iBAAA;AAAA;AAAA,KAGxB,uBAAA;EACV,WAAA,QAAmB,gBAAA;EACnB,OAAA,EAAS,uBAAuB;EAzBL;;;;;;;EAkC3B,eAAA;EA1BiC;;;;;EAiCjC,QAAA;EAhDA;;;;;;;;;;;EA6DA,gBAAA,KAAqB,QAAA;EAxDnB;;;;;EA+DF,YAAA;AAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { useState } from "@assistant-ui/tap/react-shim";
|
|
2
1
|
import { useClientLookup } from "@assistant-ui/store";
|
|
2
|
+
import { useState } from "@assistant-ui/tap/react-shim";
|
|
3
3
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
4
4
|
import { resource, withKey } from "@assistant-ui/tap";
|
|
5
5
|
//#region src/store/clients/suggestions.ts
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getThreadMessageText } from "../../utils/text.js";
|
|
2
2
|
import { NoOpComposerClient } from "./no-op-composer-client.js";
|
|
3
|
-
import { useState } from "@assistant-ui/tap/react-shim";
|
|
4
3
|
import { useClientLookup } from "@assistant-ui/store";
|
|
4
|
+
import { useState } from "@assistant-ui/tap/react-shim";
|
|
5
5
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
6
6
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
7
7
|
//#region src/store/clients/thread-message-client.ts
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useSubscribable } from "./useSubscribable.js";
|
|
2
2
|
import { AttachmentRuntimeClient } from "./attachment-runtime-client.js";
|
|
3
|
-
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
4
3
|
import { useAssistantEmit, useClientLookup } from "@assistant-ui/store";
|
|
4
|
+
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
5
5
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
6
6
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
7
7
|
//#region src/store/runtime-clients/composer-runtime-client.ts
|
|
@@ -3,8 +3,8 @@ import { AttachmentRuntimeClient } from "./attachment-runtime-client.js";
|
|
|
3
3
|
import { MessagePartClient } from "./message-part-runtime-client.js";
|
|
4
4
|
import { ComposerClient } from "./composer-runtime-client.js";
|
|
5
5
|
import { liveRef } from "./liveRef.js";
|
|
6
|
-
import { useState } from "@assistant-ui/tap/react-shim";
|
|
7
6
|
import { useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
7
|
+
import { useState } from "@assistant-ui/tap/react-shim";
|
|
8
8
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
9
9
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
10
10
|
//#region src/store/runtime-clients/message-runtime-client.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useSubscribable } from "./useSubscribable.js";
|
|
2
|
-
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
3
2
|
import { useAssistantEmit } from "@assistant-ui/store";
|
|
3
|
+
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
4
4
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
5
5
|
import { resource } from "@assistant-ui/tap";
|
|
6
6
|
//#region src/store/runtime-clients/thread-list-item-runtime-client.ts
|
|
@@ -2,8 +2,8 @@ import { useSubscribable } from "./useSubscribable.js";
|
|
|
2
2
|
import { ComposerClient } from "./composer-runtime-client.js";
|
|
3
3
|
import { liveRef } from "./liveRef.js";
|
|
4
4
|
import { MessageClient } from "./message-runtime-client.js";
|
|
5
|
-
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
6
5
|
import { useAssistantEmit, useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
6
|
+
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
7
7
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
8
8
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
9
9
|
//#region src/store/runtime-clients/thread-runtime-client.ts
|
|
@@ -10,7 +10,7 @@ declare function deferred<T>(): {
|
|
|
10
10
|
};
|
|
11
11
|
declare const contextProvider: ModelContextProvider;
|
|
12
12
|
declare function makeAdapter(overrides?: Partial<RemoteThreadListAdapter>): RemoteThreadListAdapter;
|
|
13
|
-
declare function createCore(adapter: RemoteThreadListAdapter, threadId?: string): RemoteThreadListThreadListRuntimeCore;
|
|
13
|
+
declare function createCore(adapter: RemoteThreadListAdapter, threadId?: string, onThreadIdChange?: (threadId: string | undefined) => void): RemoteThreadListThreadListRuntimeCore;
|
|
14
14
|
//#endregion
|
|
15
15
|
export { contextProvider, createCore, deferred, makeAdapter };
|
|
16
16
|
//# sourceMappingURL=remote-thread-list-test-helpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-thread-list-test-helpers.d.ts","names":[],"sources":["../../src/tests/remote-thread-list-test-helpers.ts"],"mappings":";;;;;iBAKgB,QAAA;;mBACQ,CAAA;;;cASX,eAAA,EAAiB,oBAG7B;AAAA,iBAEe,WAAA,CACd,SAAA,GAAW,OAAA,CAAQ,uBAAA,IAClB,uBAAA;AAAA,iBA6Ba,UAAA,CACd,OAAA,EAAS,uBAAA,EACT,QAAA,
|
|
1
|
+
{"version":3,"file":"remote-thread-list-test-helpers.d.ts","names":[],"sources":["../../src/tests/remote-thread-list-test-helpers.ts"],"mappings":";;;;;iBAKgB,QAAA;;mBACQ,CAAA;;;cASX,eAAA,EAAiB,oBAG7B;AAAA,iBAEe,WAAA,CACd,SAAA,GAAW,OAAA,CAAQ,uBAAA,IAClB,uBAAA;AAAA,iBA6Ba,UAAA,CACd,OAAA,EAAS,uBAAA,EACT,QAAA,WACA,gBAAA,IAAoB,QAAA,gCACnB,qCAAqC"}
|
|
@@ -40,11 +40,12 @@ function makeAdapter(overrides = {}) {
|
|
|
40
40
|
...overrides
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
-
function createCore(adapter, threadId) {
|
|
43
|
+
function createCore(adapter, threadId, onThreadIdChange) {
|
|
44
44
|
const core = new RemoteThreadListThreadListRuntimeCore({
|
|
45
45
|
adapter,
|
|
46
46
|
runtimeHook: () => ({}),
|
|
47
|
-
threadId
|
|
47
|
+
threadId,
|
|
48
|
+
onThreadIdChange
|
|
48
49
|
}, contextProvider);
|
|
49
50
|
core._hookManager.startThreadRuntime = async () => ({});
|
|
50
51
|
return core;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-thread-list-test-helpers.js","names":["vi","RemoteThreadListThreadListRuntimeCore","RemoteThreadListAdapter","ModelContextProvider","deferred","resolve","value","T","reject","reason","promise","Promise","res","rej","contextProvider","getModelContext","subscribe","makeAdapter","overrides","Partial","list","fn","threads","initialize","threadId","remoteId","externalId","rename","archive","unarchive","delete","generateTitle","ReadableStream","start","c","close","fetch","id","status","const","title","createCore","adapter","core","runtimeHook","_hookManager","startThreadRuntime"],"sources":["../../src/tests/remote-thread-list-test-helpers.ts"],"sourcesContent":["import { vi } from \"vitest\";\nimport { RemoteThreadListThreadListRuntimeCore } from \"../react/runtimes/RemoteThreadListThreadListRuntimeCore\";\nimport type { RemoteThreadListAdapter } from \"../runtimes/remote-thread-list/types\";\nimport type { ModelContextProvider } from \"../model-context/types\";\n\nexport function deferred<T>() {\n let resolve!: (value: T) => void;\n let reject!: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\nexport const contextProvider: ModelContextProvider = {\n getModelContext: () => ({}),\n subscribe: () => () => {},\n};\n\nexport function makeAdapter(\n overrides: Partial<RemoteThreadListAdapter> = {},\n): RemoteThreadListAdapter {\n return {\n list: vi.fn(async () => ({ threads: [] })),\n initialize: vi.fn(async (threadId: string) => ({\n remoteId: threadId,\n externalId: threadId,\n })),\n rename: vi.fn(async () => {}),\n archive: vi.fn(async () => {}),\n unarchive: vi.fn(async () => {}),\n delete: vi.fn(async () => {}),\n generateTitle: vi.fn(\n async () =>\n new ReadableStream({\n start(c) {\n c.close();\n },\n }) as never,\n ),\n fetch: vi.fn(async (id: string) => ({\n status: \"regular\" as const,\n remoteId: id,\n externalId: id,\n title: \"Test\",\n })),\n ...overrides,\n };\n}\n\nexport function createCore(\n adapter: RemoteThreadListAdapter,\n threadId?: string,\n): RemoteThreadListThreadListRuntimeCore {\n const core = new RemoteThreadListThreadListRuntimeCore(\n { adapter, runtimeHook: () => ({}) as never, threadId },\n contextProvider,\n );\n // `startThreadRuntime` blocks until a React component attaches a runtime;\n // stub it so non-React unit tests don't hang.\n (\n core as unknown as {\n _hookManager: {\n startThreadRuntime: (id: string) => Promise<unknown>;\n };\n }\n )._hookManager.startThreadRuntime = async () => ({});\n return core;\n}\n"],"mappings":";;;AAKA,SAAgBI,WAAc;CAC5B,IAAIC;CACJ,IAAIG;CAKJ,OAAO;EAAEE,SAAAA,IAJWC,SAAYC,KAAKC,QAAQ;GAC3CR,UAAUO;GACVJ,SAASK;EACX,CACSH;EAASL;EAASG;CAAO;AACpC;AAEA,MAAaM,kBAAwC;CACnDC,wBAAwB,CAAC;CACzBC,uBAAuB,CAAC;AAC1B;AAEA,SAAgBC,YACdC,YAA8C,CAAC,GACtB;CACzB,OAAO;EACLE,MAAMpB,GAAGqB,GAAG,aAAa,EAAEC,SAAS,CAAA,EAAG,EAAE;EACzCC,YAAYvB,GAAGqB,GAAG,OAAOG,cAAsB;GAC7CC,UAAUD;GACVE,YAAYF;EACd,EAAE;EACFG,QAAQ3B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC5BO,SAAS5B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC7BQ,WAAW7B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC/BS,QAAQ9B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC5BU,eAAe/B,GAAGqB,GAChB,YACE,IAAIW,eAAe,EACjBC,MAAMC,GAAG;GACPA,EAAEC,MAAM;EACV,EACF,CAAC,CACL;EACAC,OAAOpC,GAAGqB,GAAG,OAAOgB,QAAgB;GAClCC,QAAQ;GACRb,UAAUY;GACVX,YAAYW;GACZG,OAAO;EACT,EAAE;EACF,GAAGtB;CACL;AACF;AAEA,SAAgBuB,WACdC,SACAlB,
|
|
1
|
+
{"version":3,"file":"remote-thread-list-test-helpers.js","names":["vi","RemoteThreadListThreadListRuntimeCore","RemoteThreadListAdapter","ModelContextProvider","deferred","resolve","value","T","reject","reason","promise","Promise","res","rej","contextProvider","getModelContext","subscribe","makeAdapter","overrides","Partial","list","fn","threads","initialize","threadId","remoteId","externalId","rename","archive","unarchive","delete","generateTitle","ReadableStream","start","c","close","fetch","id","status","const","title","createCore","adapter","onThreadIdChange","core","runtimeHook","_hookManager","startThreadRuntime"],"sources":["../../src/tests/remote-thread-list-test-helpers.ts"],"sourcesContent":["import { vi } from \"vitest\";\nimport { RemoteThreadListThreadListRuntimeCore } from \"../react/runtimes/RemoteThreadListThreadListRuntimeCore\";\nimport type { RemoteThreadListAdapter } from \"../runtimes/remote-thread-list/types\";\nimport type { ModelContextProvider } from \"../model-context/types\";\n\nexport function deferred<T>() {\n let resolve!: (value: T) => void;\n let reject!: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\nexport const contextProvider: ModelContextProvider = {\n getModelContext: () => ({}),\n subscribe: () => () => {},\n};\n\nexport function makeAdapter(\n overrides: Partial<RemoteThreadListAdapter> = {},\n): RemoteThreadListAdapter {\n return {\n list: vi.fn(async () => ({ threads: [] })),\n initialize: vi.fn(async (threadId: string) => ({\n remoteId: threadId,\n externalId: threadId,\n })),\n rename: vi.fn(async () => {}),\n archive: vi.fn(async () => {}),\n unarchive: vi.fn(async () => {}),\n delete: vi.fn(async () => {}),\n generateTitle: vi.fn(\n async () =>\n new ReadableStream({\n start(c) {\n c.close();\n },\n }) as never,\n ),\n fetch: vi.fn(async (id: string) => ({\n status: \"regular\" as const,\n remoteId: id,\n externalId: id,\n title: \"Test\",\n })),\n ...overrides,\n };\n}\n\nexport function createCore(\n adapter: RemoteThreadListAdapter,\n threadId?: string,\n onThreadIdChange?: (threadId: string | undefined) => void,\n): RemoteThreadListThreadListRuntimeCore {\n const core = new RemoteThreadListThreadListRuntimeCore(\n { adapter, runtimeHook: () => ({}) as never, threadId, onThreadIdChange },\n contextProvider,\n );\n // `startThreadRuntime` blocks until a React component attaches a runtime;\n // stub it so non-React unit tests don't hang.\n (\n core as unknown as {\n _hookManager: {\n startThreadRuntime: (id: string) => Promise<unknown>;\n };\n }\n )._hookManager.startThreadRuntime = async () => ({});\n return core;\n}\n"],"mappings":";;;AAKA,SAAgBI,WAAc;CAC5B,IAAIC;CACJ,IAAIG;CAKJ,OAAO;EAAEE,SAAAA,IAJWC,SAAYC,KAAKC,QAAQ;GAC3CR,UAAUO;GACVJ,SAASK;EACX,CACSH;EAASL;EAASG;CAAO;AACpC;AAEA,MAAaM,kBAAwC;CACnDC,wBAAwB,CAAC;CACzBC,uBAAuB,CAAC;AAC1B;AAEA,SAAgBC,YACdC,YAA8C,CAAC,GACtB;CACzB,OAAO;EACLE,MAAMpB,GAAGqB,GAAG,aAAa,EAAEC,SAAS,CAAA,EAAG,EAAE;EACzCC,YAAYvB,GAAGqB,GAAG,OAAOG,cAAsB;GAC7CC,UAAUD;GACVE,YAAYF;EACd,EAAE;EACFG,QAAQ3B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC5BO,SAAS5B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC7BQ,WAAW7B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC/BS,QAAQ9B,GAAGqB,GAAG,YAAY,CAAC,CAAC;EAC5BU,eAAe/B,GAAGqB,GAChB,YACE,IAAIW,eAAe,EACjBC,MAAMC,GAAG;GACPA,EAAEC,MAAM;EACV,EACF,CAAC,CACL;EACAC,OAAOpC,GAAGqB,GAAG,OAAOgB,QAAgB;GAClCC,QAAQ;GACRb,UAAUY;GACVX,YAAYW;GACZG,OAAO;EACT,EAAE;EACF,GAAGtB;CACL;AACF;AAEA,SAAgBuB,WACdC,SACAlB,UACAmB,kBACuC;CACvC,MAAMC,OAAO,IAAI3C,sCACf;EAAEyC;EAASG,oBAAoB,CAAC;EAAarB;EAAUmB;CAAiB,GACxE7B,eACF;CAGA,KAMEgC,aAAaC,qBAAqB,aAAa,CAAC;CAClD,OAAOH;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.20",
|
|
4
4
|
"description": "Framework-agnostic core runtime for assistant-ui",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"assistant",
|
|
@@ -59,8 +59,8 @@
|
|
|
59
59
|
],
|
|
60
60
|
"sideEffects": false,
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"assistant-stream": "^0.3.
|
|
63
|
-
"nanoid": "^5.1.
|
|
62
|
+
"assistant-stream": "^0.3.25",
|
|
63
|
+
"nanoid": "^5.1.15"
|
|
64
64
|
},
|
|
65
65
|
"optionalDevDependencies": {
|
|
66
66
|
"@assistant-ui/x-generative-compiler": ">=0.0.3"
|
|
@@ -90,13 +90,13 @@
|
|
|
90
90
|
"devDependencies": {
|
|
91
91
|
"@types/react": "^19.2.17",
|
|
92
92
|
"react": "^19.2.7",
|
|
93
|
-
"vitest": "^4.1.
|
|
93
|
+
"vitest": "^4.1.9",
|
|
94
94
|
"zustand": "^5.0.14",
|
|
95
|
-
"@assistant-ui/store": "0.2.
|
|
96
|
-
"@assistant-ui/tap": "0.9.
|
|
97
|
-
"@assistant-ui/vite": "0.0.
|
|
98
|
-
"@assistant-ui/x-buildutils": "0.0.
|
|
99
|
-
"assistant-cloud": "0.1.
|
|
95
|
+
"@assistant-ui/store": "0.2.19",
|
|
96
|
+
"@assistant-ui/tap": "0.9.3",
|
|
97
|
+
"@assistant-ui/vite": "0.0.8",
|
|
98
|
+
"@assistant-ui/x-buildutils": "0.0.17",
|
|
99
|
+
"assistant-cloud": "0.1.34"
|
|
100
100
|
},
|
|
101
101
|
"publishConfig": {
|
|
102
102
|
"access": "public",
|