@assistant-ui/core 0.3.18 → 0.3.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/speech.d.ts.map +1 -1
- package/dist/adapters/speech.js +13 -3
- package/dist/adapters/speech.js.map +1 -1
- package/dist/adapters/thread-history.d.ts +4 -0
- package/dist/adapters/thread-history.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/model-context/frame/host.d.ts.map +1 -1
- package/dist/model-context/frame/host.js +26 -11
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/interactable-composer-metadata.js +11 -9
- package/dist/model-context/interactable-composer-metadata.js.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js +45 -7
- package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
- package/dist/react/client/DataRenderers.d.ts.map +1 -1
- package/dist/react/client/DataRenderers.js +20 -15
- package/dist/react/client/DataRenderers.js.map +1 -1
- package/dist/react/client/Interactables.d.ts.map +1 -1
- package/dist/react/client/Interactables.js +11 -5
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
- package/dist/react/client/RemoteThreadList.js +3 -2
- package/dist/react/client/RemoteThreadList.js.map +1 -1
- package/dist/react/client/interactable-model-context.d.ts.map +1 -1
- package/dist/react/client/interactable-model-context.js +3 -2
- package/dist/react/client/interactable-model-context.js.map +1 -1
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +2 -2
- package/dist/react/interactables-legacy/useAssistantInteractable.d.ts.map +1 -1
- package/dist/react/interactables-legacy/useAssistantInteractable.js +3 -0
- package/dist/react/interactables-legacy/useAssistantInteractable.js.map +1 -1
- package/dist/react/model-context/useInteractable.d.ts.map +1 -1
- package/dist/react/model-context/useInteractable.js +4 -1
- package/dist/react/model-context/useInteractable.js.map +1 -1
- package/dist/react/model-context/useInteractableVersions.js +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.d.ts +11 -2
- package/dist/react/primitives/message/MessageGroupedParts.d.ts.map +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.js +3 -2
- package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
- package/dist/react/primitives/part/PartMessages.d.ts +1 -0
- package/dist/react/primitives/part/PartMessages.d.ts.map +1 -1
- package/dist/react/primitives/part/PartMessages.js +1 -0
- package/dist/react/primitives/part/PartMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.d.ts.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.js +6 -5
- package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +2 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts +2 -24
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +135 -374
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts +1 -0
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js +22 -2
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.d.ts +40 -15
- package/dist/react/runtimes/cloud/auiV0.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.js +62 -15
- package/dist/react/runtimes/cloud/auiV0.js.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts +2 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js +4 -0
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/sdkIdentity.d.ts +6 -0
- package/dist/react/runtimes/cloud/sdkIdentity.d.ts.map +1 -0
- package/dist/react/runtimes/cloud/sdkIdentity.js +9 -0
- package/dist/react/runtimes/cloud/sdkIdentity.js.map +1 -0
- package/dist/react/runtimes/external-message-converter.d.ts +12 -2
- package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
- package/dist/react/runtimes/external-message-converter.js +26 -61
- package/dist/react/runtimes/external-message-converter.js.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
- package/dist/react/utils/groupParts.d.ts +6 -1
- package/dist/react/utils/groupParts.d.ts.map +1 -1
- package/dist/react/utils/groupParts.js +6 -0
- package/dist/react/utils/groupParts.js.map +1 -1
- package/dist/react/utils/useJSONEqual.d.ts +3 -1
- package/dist/react/utils/useJSONEqual.d.ts.map +1 -1
- package/dist/react/utils/useJSONEqual.js +6 -1
- package/dist/react/utils/useJSONEqual.js.map +1 -1
- package/dist/react/utils/useJSONSchemaDependency.d.ts +7 -0
- package/dist/react/utils/useJSONSchemaDependency.d.ts.map +1 -0
- package/dist/react/utils/useJSONSchemaDependency.js +20 -0
- package/dist/react/utils/useJSONSchemaDependency.js.map +1 -0
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js +2 -5
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts +1 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +46 -10
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.d.ts +2 -0
- package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js +155 -64
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/interfaces/thread-runtime-core.d.ts +6 -0
- package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/queue/message-queue.d.ts +5 -0
- package/dist/runtime/queue/message-queue.d.ts.map +1 -1
- package/dist/runtime/queue/message-queue.js +61 -6
- package/dist/runtime/queue/message-queue.js.map +1 -1
- package/dist/runtime/utils/auto-status.d.ts +6 -2
- package/dist/runtime/utils/auto-status.d.ts.map +1 -1
- package/dist/runtime/utils/auto-status.js +12 -4
- package/dist/runtime/utils/auto-status.js.map +1 -1
- package/dist/runtime/utils/external-message-conversion.d.ts +16 -4
- package/dist/runtime/utils/external-message-conversion.d.ts.map +1 -1
- package/dist/runtime/utils/external-message-conversion.js +48 -12
- package/dist/runtime/utils/external-message-conversion.js.map +1 -1
- package/dist/runtime/utils/message-repository.js +3 -3
- package/dist/runtime/utils/message-repository.js.map +1 -1
- package/dist/runtime/utils/thread-message-like.d.ts +2 -1
- package/dist/runtime/utils/thread-message-like.d.ts.map +1 -1
- package/dist/runtime/utils/thread-message-like.js +4 -2
- package/dist/runtime/utils/thread-message-like.js.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js +8 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/internal.d.ts +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +4 -1
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +2 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
- package/dist/store/clients/external-thread.d.ts.map +1 -1
- package/dist/store/clients/external-thread.js +241 -200
- package/dist/store/clients/external-thread.js.map +1 -1
- package/dist/store/clients/thread-tasks.d.ts +13 -0
- package/dist/store/clients/thread-tasks.d.ts.map +1 -0
- package/dist/store/clients/thread-tasks.js +69 -0
- package/dist/store/clients/thread-tasks.js.map +1 -0
- package/dist/store/index.d.ts +3 -2
- package/dist/store/index.js +3 -3
- package/dist/store/primitive-predicates.d.ts.map +1 -1
- package/dist/store/primitive-predicates.js +4 -4
- package/dist/store/primitive-predicates.js.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.js +176 -128
- package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
- package/dist/store/scope-registration.d.ts +2 -0
- package/dist/store/scope-registration.d.ts.map +1 -1
- package/dist/store/scopes/task.d.ts +36 -0
- package/dist/store/scopes/task.d.ts.map +1 -0
- package/dist/store/scopes/task.js +0 -0
- package/dist/store/scopes/thread.d.ts +20 -0
- package/dist/store/scopes/thread.d.ts.map +1 -1
- package/dist/subscribable/subscribable.d.ts +2 -1
- package/dist/subscribable/subscribable.d.ts.map +1 -1
- package/dist/subscribable/subscribable.js +23 -15
- package/dist/subscribable/subscribable.js.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/message.d.ts +8 -1
- package/dist/types/message.d.ts.map +1 -1
- package/dist/types/message.js.map +1 -1
- package/dist/utils/abortable-iterable.d.ts.map +1 -1
- package/dist/utils/abortable-iterable.js +30 -14
- package/dist/utils/abortable-iterable.js.map +1 -1
- package/dist/utils/getGroupStatus.d.ts +18 -2
- package/dist/utils/getGroupStatus.d.ts.map +1 -1
- package/dist/utils/getGroupStatus.js +32 -7
- package/dist/utils/getGroupStatus.js.map +1 -1
- package/dist/utils/wire-media.d.ts.map +1 -1
- package/dist/utils/wire-media.js +2 -2
- package/dist/utils/wire-media.js.map +1 -1
- package/package.json +6 -6
- package/src/adapters/speech.test.ts +236 -0
- package/src/adapters/speech.ts +17 -10
- package/src/adapters/thread-history.ts +3 -0
- package/src/index.ts +1 -0
- package/src/model-context/frame/host.test.ts +113 -1
- package/src/model-context/frame/host.ts +39 -12
- package/src/model-context/interactable-composer-metadata.test.ts +30 -0
- package/src/model-context/interactable-composer-metadata.ts +10 -10
- package/src/react/adapters/LocalStorageThreadListAdapter.test.ts +244 -0
- package/src/react/adapters/LocalStorageThreadListAdapter.tsx +104 -7
- package/src/react/client/DataRenderers.test.tsx +45 -0
- package/src/react/client/DataRenderers.ts +13 -9
- package/src/react/client/Interactables.test.ts +44 -1
- package/src/react/client/Interactables.ts +7 -1
- package/src/react/client/RemoteThreadList.test.ts +41 -1
- package/src/react/client/RemoteThreadList.ts +15 -2
- package/src/react/client/interactable-model-context.test.ts +44 -0
- package/src/react/client/interactable-model-context.ts +3 -2
- package/src/react/index.ts +5 -1
- package/src/react/interactables-legacy/useAssistantInteractable.test.tsx +132 -0
- package/src/react/interactables-legacy/useAssistantInteractable.ts +10 -1
- package/src/react/model-context/useInteractable.test.tsx +177 -0
- package/src/react/model-context/useInteractable.ts +3 -0
- package/src/react/primitive-hooks/useActionBarCopy.test.ts +0 -1
- package/src/react/primitive-hooks/useSuggestionTrigger.test.ts +0 -1
- package/src/react/primitives/message/MessageGroupedParts.test.tsx +96 -0
- package/src/react/primitives/message/MessageGroupedParts.tsx +15 -4
- package/src/react/primitives/part/PartMessages.test.tsx +104 -1
- package/src/react/primitives/part/PartMessages.tsx +1 -0
- package/src/react/primitives/thread/ThreadMessages.test.tsx +142 -0
- package/src/react/primitives/thread/ThreadMessages.tsx +8 -5
- package/src/react/providers/ReadonlyThreadProvider.test.tsx +56 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +7 -1
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.ts +20 -14
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +221 -1
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +166 -512
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.test.ts +77 -0
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.ts +27 -1
- package/src/react/runtimes/cloud/auiV0.ts +160 -25
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.test.ts +21 -0
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.ts +7 -1
- package/src/react/runtimes/cloud/sdkIdentity.ts +9 -0
- package/src/react/runtimes/cloud/useCloudThreadListAdapter.test.tsx +18 -4
- package/src/react/runtimes/external-message-converter.test.ts +136 -1
- package/src/react/runtimes/external-message-converter.ts +39 -93
- package/src/react/runtimes/useRemoteThreadListRuntime.ts +1 -1
- package/src/react/utils/groupParts.ts +12 -1
- package/src/react/utils/useJSONEqual.ts +9 -0
- package/src/react/utils/useJSONSchemaDependency.ts +22 -0
- package/src/runtime/api/thread-runtime.test.ts +58 -0
- package/src/runtime/api/thread-runtime.ts +2 -4
- package/src/runtime/base/base-composer-runtime-core.ts +69 -16
- package/src/runtime/base/base-thread-runtime-core.test.ts +1008 -1
- package/src/runtime/base/base-thread-runtime-core.ts +222 -83
- package/src/runtime/interfaces/thread-runtime-core.ts +6 -0
- package/src/runtime/queue/message-queue.ts +68 -6
- package/src/runtime/utils/auto-status.test.ts +112 -1
- package/src/runtime/utils/auto-status.ts +31 -5
- package/src/runtime/utils/external-message-conversion.test.ts +134 -0
- package/src/runtime/utils/external-message-conversion.ts +122 -31
- package/src/runtime/utils/message-repository.test.ts +49 -0
- package/src/runtime/utils/message-repository.ts +3 -3
- package/src/runtime/utils/thread-message-like.test.ts +52 -0
- package/src/runtime/utils/thread-message-like.ts +4 -0
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +31 -1
- package/src/runtimes/local/local-thread-runtime-core.test.ts +21 -0
- package/src/runtimes/local/local-thread-runtime-core.ts +11 -1
- package/src/runtimes/tool-invocations/EDGE_CASES.md +2 -6
- package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +133 -0
- package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +10 -6
- package/src/store/clients/external-thread.ts +19 -1
- package/src/store/clients/thread-tasks.test.ts +274 -0
- package/src/store/clients/thread-tasks.ts +138 -0
- package/src/store/index.ts +8 -0
- package/src/store/primitive-predicates.test.ts +48 -5
- package/src/store/primitive-predicates.ts +7 -2
- package/src/store/runtime-clients/thread-runtime-client.ts +31 -1
- package/src/store/scope-registration.ts +2 -0
- package/src/store/scopes/task.ts +34 -0
- package/src/store/scopes/thread.ts +16 -0
- package/src/store/thread-tasks.test.tsx +209 -0
- package/src/subscribable/subscribable.test.ts +156 -1
- package/src/subscribable/subscribable.ts +25 -15
- package/src/tests/MessageRepository.test.ts +1 -5
- package/src/tests/auiV0Encode.test.ts +300 -0
- package/src/tests/base-composer-runtime-core-send.test.ts +51 -0
- package/src/tests/base-composer-runtime-core.test.ts +314 -2
- package/src/tests/external-store-thread-runtime-core-adapter.test.ts +151 -0
- package/src/tests/external-thread-attachments.test.tsx +69 -0
- package/src/tests/external-thread-parity.test.tsx +34 -0
- package/src/tests/groupParts.test.ts +71 -0
- package/src/tests/message-queue.test.ts +253 -0
- package/src/tests/remote-thread-list-reactive-threadId.test.ts +51 -0
- package/src/tests/useRemoteThreadListRuntime-controlled.test.tsx +43 -0
- package/src/types/index.ts +1 -0
- package/src/types/message.ts +8 -0
- package/src/utils/abortable-iterable.test.ts +115 -0
- package/src/utils/abortable-iterable.ts +34 -23
- package/src/utils/getGroupStatus.test.ts +70 -4
- package/src/utils/getGroupStatus.ts +35 -12
- package/src/utils/wire-media.test.ts +10 -0
- package/src/utils/wire-media.ts +6 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","getAutoStatus","ExportedMessageRepository","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","ThreadMessage","MessageNotSentError","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","captureThreadRuntimeGeneration","invalidateThreadRuntime","isThreadRuntimeGenerationCurrent","AbortError","Error","name","detach","constructor","message","withLocalPauseReason","role","status","type","reason","content","some","c","result","undefined","interrupt","withLocalPauseReasons","data","messages","map","item","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","history","_options","adapters","update","bind","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","previousHistory","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadRequested","_loadPromise","length","__internal_load","error","console","promise","load","repo","repository","import","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","willRun","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","_rollbackAppend","messageId","deleteMessage","rawMessage","enrichAppendMetadata","newMessage","addOrUpdateMessage","initPromise","notSent","cause","historyWrite","runResult","historyResult","allSettled","resetHead","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","unstable_notifySessionReset","runCallback","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","active","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","hasStoredMessage","getMessage","ownsMessage","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","shouldCancelMessage","aborted","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","e","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","addToolResult","toolCallId","isError","artifact","messageData","added","found","newContent","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","text","findLast","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 { getAutoStatus } from \"../../runtime/utils/auto-status\";\nimport type { ExportedMessageRepository } from \"../../runtime/utils/message-repository\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\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, ThreadMessage } from \"../../types/message\";\nimport { MessageNotSentError, toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../runtime/queue/queue-item\";\nimport {\n captureThreadRuntimeGeneration,\n invalidateThreadRuntime,\n isThreadRuntimeGenerationCurrent,\n} from \"../../runtime/utils/thread-runtime-lifecycle\";\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\n// `shouldContinue` resumes only on `tool-calls` and `resumeToolCall` throws, so\n// an imported `interrupt` with no interrupt payload would be stranded here.\n// Provenance cannot gate it: a repository that went through JSON has no marker.\n// The replacement stays content-derived, so a message with nothing resultless\n// left to act on lands on `complete` rather than an unactionable pause.\nconst withLocalPauseReason = (message: ThreadMessage): ThreadMessage => {\n if (\n message.role !== \"assistant\" ||\n message.status.type !== \"requires-action\" ||\n message.status.reason !== \"interrupt\" ||\n message.content.some(\n (c) =>\n c.type === \"tool-call\" && c.result === undefined && c.interrupt != null,\n )\n )\n return message;\n return {\n ...message,\n status: getAutoStatus(\n false,\n false,\n false,\n message.content.some(\n (c) => c.type === \"tool-call\" && c.result === undefined,\n ),\n ),\n };\n};\n\nconst withLocalPauseReasons = (\n data: ExportedMessageRepository,\n): ExportedMessageRepository => ({\n ...data,\n messages: data.messages.map((item) => ({\n ...item,\n message: withLocalPauseReason(item.message),\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 refetchThread: false,\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 private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\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 const previousHistory = this._options?.adapters.history;\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 const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\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 if (\n this._loadRequested &&\n !this._loadPromise &&\n !previousHistory &&\n options.adapters.history &&\n this.messages.length === 0\n ) {\n void this.__internal_load().catch((error: unknown) => {\n console.error(\n \"[assistant-ui] local thread history load failed:\",\n error,\n );\n });\n }\n }\n\n private _loadPromise: Promise<void> | undefined;\n private _loadRequested = false;\n public __internal_load() {\n this._loadRequested = true;\n if (this._loadPromise) return this._loadPromise;\n if (!this.adapters.history) return Promise.resolve();\n\n const promise = this.adapters.history.load();\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(withLocalPauseReasons(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 if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\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 getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private _rollbackAppend(messageId: string) {\n try {\n this.repository.deleteMessage(messageId);\n } catch {\n return;\n }\n this._notifySubscribers();\n }\n\n private async _runAppend(rawMessage: AppendMessage): Promise<void> {\n // Stamped here rather than in `append` so a queued message is gated after\n // the flush re-pointed its parentId at the current tail.\n const generation = captureThreadRuntimeGeneration(this);\n const message = this.enrichAppendMetadata(rawMessage);\n this.ensureInitialized();\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._notifySubscribers();\n\n // Initialization only gates the history write and the run; the message\n // is already on screen. A failed barrier rolls the optimistic message\n // back and rejects as an unsent message so the composer restores the\n // draft; a thread invalidated mid-wait rolls back silently.\n try {\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n } catch (error) {\n this._rollbackAppend(newMessage.id);\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n const notSent = new MessageNotSentError();\n notSent.cause = error;\n throw notSent;\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) {\n this._rollbackAppend(newMessage.id);\n return;\n }\n const historyWrite = this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n void historyWrite?.catch(() => {});\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n const [runResult, historyResult] = await Promise.allSettled([\n this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n }),\n historyWrite,\n ]);\n if (runResult.status === \"rejected\") throw runResult.reason;\n if (historyResult.status === \"rejected\") throw historyResult.reason;\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n await historyWrite;\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 override import(data: ExportedMessageRepository) {\n super.import(withLocalPauseReasons(data));\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public unstable_notifySessionReset(): void {\n throw new Error(\"Runtime does not support resetting sessions.\");\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 // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n let active = false;\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 alreadyPersisted,\n run,\n runCallback,\n );\n runCallback = undefined;\n if (this._activeRun !== run) break;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n active &&\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n run: { cancelled: boolean },\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = 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 let hasStoredMessage = true;\n try {\n this.repository.getMessage(message.id);\n } catch {\n hasStoredMessage = false;\n }\n // Other writers replace the stored message object, so identity distinguishes this run from a newer owner.\n const ownsMessage = () => {\n if (!hasStoredMessage) return this._activeRun === run;\n try {\n return this.repository.getMessage(message.id).message === message;\n } catch {\n return false;\n }\n };\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n if (!ownsMessage()) return;\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 !== undefined\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 hasStoredMessage = true;\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\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 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 = abortController.signal;\n const shouldCancelMessage = () =>\n abortSignal.aborted &&\n (message.status.type === \"running\" ||\n (message.status.type === \"requires-action\" &&\n (this._activeRun !== run ||\n shouldContinue(message, this._options.unstable_humanToolNames))));\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 if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n }\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\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: toAssistantError(e),\n },\n });\n\n throw e;\n }\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (ownsMessage() && (isTerminal || (isPausing && history?.update))) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n invalidateThreadRuntime(this);\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = 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 === undefined) 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 } else if (added) {\n this._persistPausedMessage(parentId, message);\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 text,\n reason,\n }: RespondToToolApprovalOptions): Promise<void> {\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 ...(text != null && { text }),\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 } else {\n this._persistPausedMessage(parentId, message);\n }\n\n return Promise.resolve();\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,IAAMgC,aAAN,cA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AO;EAG9C,OAAO0C,QAAQM,QAAQ;CACzB;AACF"}
|
|
1
|
+
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","getAutoStatus","ExportedMessageRepository","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","ThreadMessage","MessageNotSentError","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","captureThreadRuntimeGeneration","invalidateThreadRuntime","isThreadRuntimeGenerationCurrent","AbortError","Error","name","detach","constructor","message","withLocalPauseReason","role","status","type","reason","content","some","c","result","undefined","interrupt","withLocalPauseReasons","data","messages","map","item","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","history","_options","adapters","update","bind","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","previousHistory","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadRequested","_loadPromise","length","__internal_load","error","console","promise","load","repo","repository","import","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","_isVoiceMessage","isTail","willRun","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","_rollbackAppend","messageId","deleteMessage","rawMessage","enrichAppendMetadata","newMessage","addOrUpdateMessage","initPromise","notSent","cause","historyWrite","runResult","historyResult","allSettled","resetHead","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","unstable_notifySessionReset","runCallback","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","active","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","hasStoredMessage","getMessage","ownsMessage","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","shouldCancelMessage","aborted","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","e","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","addToolResult","toolCallId","isError","artifact","messageData","added","found","newContent","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","text","findLast","approval","target","find","resolution","targetApproval","_notifyToolApprovalAnswered","toolName"],"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 { getAutoStatus } from \"../../runtime/utils/auto-status\";\nimport type { ExportedMessageRepository } from \"../../runtime/utils/message-repository\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\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, ThreadMessage } from \"../../types/message\";\nimport { MessageNotSentError, toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../runtime/queue/queue-item\";\nimport {\n captureThreadRuntimeGeneration,\n invalidateThreadRuntime,\n isThreadRuntimeGenerationCurrent,\n} from \"../../runtime/utils/thread-runtime-lifecycle\";\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\n// `shouldContinue` resumes only on `tool-calls` and `resumeToolCall` throws, so\n// an imported `interrupt` with no interrupt payload would be stranded here.\n// Provenance cannot gate it: a repository that went through JSON has no marker.\n// The replacement stays content-derived, so a message with nothing resultless\n// left to act on lands on `complete` rather than an unactionable pause.\nconst withLocalPauseReason = (message: ThreadMessage): ThreadMessage => {\n if (\n message.role !== \"assistant\" ||\n message.status.type !== \"requires-action\" ||\n message.status.reason !== \"interrupt\" ||\n message.content.some(\n (c) =>\n c.type === \"tool-call\" && c.result === undefined && c.interrupt != null,\n )\n )\n return message;\n return {\n ...message,\n status: getAutoStatus(\n false,\n false,\n false,\n message.content.some(\n (c) => c.type === \"tool-call\" && c.result === undefined,\n ),\n ),\n };\n};\n\nconst withLocalPauseReasons = (\n data: ExportedMessageRepository,\n): ExportedMessageRepository => ({\n ...data,\n messages: data.messages.map((item) => ({\n ...item,\n message: withLocalPauseReason(item.message),\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 refetchThread: false,\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 private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\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 const previousHistory = this._options?.adapters.history;\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 const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\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 if (\n this._loadRequested &&\n !this._loadPromise &&\n !previousHistory &&\n options.adapters.history &&\n this.messages.length === 0\n ) {\n void this.__internal_load().catch((error: unknown) => {\n console.error(\n \"[assistant-ui] local thread history load failed:\",\n error,\n );\n });\n }\n }\n\n private _loadPromise: Promise<void> | undefined;\n private _loadRequested = false;\n public __internal_load() {\n this._loadRequested = true;\n if (this._loadPromise) return this._loadPromise;\n if (!this.adapters.history) return Promise.resolve();\n\n const promise = this.adapters.history.load();\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(withLocalPauseReasons(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 if (this._isVoiceMessage(message.sourceId))\n throw new Error(\"Voice transcript messages cannot be edited\");\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 if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\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 getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private _rollbackAppend(messageId: string) {\n try {\n this.repository.deleteMessage(messageId);\n } catch {\n return;\n }\n this._notifySubscribers();\n }\n\n private async _runAppend(rawMessage: AppendMessage): Promise<void> {\n // Stamped here rather than in `append` so a queued message is gated after\n // the flush re-pointed its parentId at the current tail.\n const generation = captureThreadRuntimeGeneration(this);\n const message = this.enrichAppendMetadata(rawMessage);\n this.ensureInitialized();\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._notifySubscribers();\n\n // Initialization only gates the history write and the run; the message\n // is already on screen. A failed barrier rolls the optimistic message\n // back and rejects as an unsent message so the composer restores the\n // draft; a thread invalidated mid-wait rolls back silently.\n try {\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n } catch (error) {\n this._rollbackAppend(newMessage.id);\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n const notSent = new MessageNotSentError();\n notSent.cause = error;\n throw notSent;\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) {\n this._rollbackAppend(newMessage.id);\n return;\n }\n const historyWrite = this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n void historyWrite?.catch(() => {});\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n const [runResult, historyResult] = await Promise.allSettled([\n this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n }),\n historyWrite,\n ]);\n if (runResult.status === \"rejected\") throw runResult.reason;\n if (historyResult.status === \"rejected\") throw historyResult.reason;\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n await historyWrite;\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 override import(data: ExportedMessageRepository) {\n super.import(withLocalPauseReasons(data));\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public unstable_notifySessionReset(): void {\n throw new Error(\"Runtime does not support resetting sessions.\");\n }\n\n public async startRun(\n { parentId, sourceId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n if (this._isVoiceMessage(sourceId))\n throw new Error(\"Voice transcript messages cannot be reloaded\");\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 // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n let active = false;\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 alreadyPersisted,\n run,\n runCallback,\n );\n runCallback = undefined;\n if (this._activeRun !== run) break;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n active &&\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n run: { cancelled: boolean },\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = 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 let hasStoredMessage = true;\n try {\n this.repository.getMessage(message.id);\n } catch {\n hasStoredMessage = false;\n }\n // Other writers replace the stored message object, so identity distinguishes this run from a newer owner.\n const ownsMessage = () => {\n if (!hasStoredMessage) return this._activeRun === run;\n try {\n return this.repository.getMessage(message.id).message === message;\n } catch {\n return false;\n }\n };\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n if (!ownsMessage()) return;\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 !== undefined\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 hasStoredMessage = true;\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\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 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 = abortController.signal;\n const shouldCancelMessage = () =>\n abortSignal.aborted &&\n (message.status.type === \"running\" ||\n (message.status.type === \"requires-action\" &&\n (this._activeRun !== run ||\n shouldContinue(message, this._options.unstable_humanToolNames))));\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 if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n }\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\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: toAssistantError(e),\n },\n });\n\n throw e;\n }\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (ownsMessage() && (isTerminal || (isPausing && history?.update))) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n invalidateThreadRuntime(this);\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = 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 === undefined) 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 } else if (added) {\n this._persistPausedMessage(parentId, message);\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 text,\n reason,\n }: RespondToToolApprovalOptions): Promise<void> {\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 ...(text != null && { text }),\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 this._notifyToolApprovalAnswered(\n message.id,\n target.toolCallId,\n target.toolName,\n approved,\n );\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 } else {\n this._persistPausedMessage(parentId, message);\n }\n\n return Promise.resolve();\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,IAAMgC,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAOA,MAAMG,wBAAwBD,YAA0C;CACtE,IACEA,QAAQE,SAAS,eACjBF,QAAQG,OAAOC,SAAS,qBACxBJ,QAAQG,OAAOE,WAAW,eAC1BL,QAAQM,QAAQC,MACbC,MACCA,EAAEJ,SAAS,eAAeI,EAAEC,WAAWC,KAAAA,KAAaF,EAAEG,aAAa,IACvE,GAEA,OAAOX;CACT,OAAO;EACL,GAAGA;EACHG,QAAQnC,cACN,OACA,OACA,OACAgC,QAAQM,QAAQC,MACbC,MAAMA,EAAEJ,SAAS,eAAeI,EAAEC,WAAWC,KAAAA,CAChD,CACF;CACF;AACF;AAEA,MAAME,yBACJC,UAC+B;CAC/B,GAAGA;CACHC,UAAUD,KAAKC,SAASC,KAAKC,UAAU;EACrC,GAAGA;EACHhB,SAASC,qBAAqBe,KAAKhB,OAAO;CAC5C,EAAE;AACJ;AAEA,IAAaiB,yBAAb,cACUtC,sBAEV;CACE,eAA+B;EAC7BwC,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBA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GAAG/N;IAAGmO;GAAS;GACtC,OAAO;IACL,GAAGnO;IACHmO;IACAlO,QAAQ,EAAE4F,OAAOhG,UAAU,uBAAuB;IAClDyN,SAAS;GACX;EACF,CAAC;EAED9N,UAAU;GAAE,GAAGA;GAASM,SAAS6N;EAAW;EAC5C,MAAM,EAAE9K,aAAa,KAAKqD,WAAWmF,WAAW7L,QAAQ4C,EAAE;EAC1D,KAAK8D,WAAWiC,mBAAmBtF,UAAUrD,OAAO;EACpD,KAAKgG,mBAAmB;EACxB,KAAKgJ,4BACHhP,QAAQ4C,IACRgM,OAAOf,YACPe,OAAOK,UACPV,QACF;EAEA,IACE,KAAK7H,WAAWM,WAAWhH,QAAQ4C,MACnC7E,eAAeiC,SAAS,KAAKuD,SAASwH,uBAAuB,GAE7D,KAAKP,SAASnH,UAAUrD,SAAS,KAAK4D,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKT,sBAAsBC,UAAUrD,OAAO;EAG9C,OAAO0C,QAAQM,QAAQ;CACzB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolInvocationTracker.d.ts","names":[],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"mappings":";;;;;;;KAwBY;EACN;;EAEA;EACA;IAAW;IAAe;;;KAGpB;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;cA+EtB;mBACM;mBACA;mBACA;mBAIA;mBACA;mBAQA;;;;;;;mBAOA;mBACA;UAET;UAEA;UACA;;UAGA;UACA;UAEA;;;;;;;;;;;UAYA;UACA;EAGN,YAAA,gBAAgB,eAAe,mBAC/B,WAAW,sBAAsB,WACjC,oBAAoB,UAAU;;;;;;UAcxB;;;;;EAsDD,SAAS,UAAU,sBAAsB;;;;;;EAmEzC;;;;;;;;;;EA8BA,MAAM;IAAY;MAA6B;;;;;;;EA2C/C,OAAO,oBAAoB;;;;;;;EAoB3B,eAAe,oBAAoB;UAMlC;UA6CA;UAaA;UAmCA;UAcA;UA0BA;UAkCA;UAWA;UAaA;UAOA;UAUA;;;;;;;UAeA;UAcA;;;;;;;;UA8BA;UAqBA;UA0GA;;
|
|
1
|
+
{"version":3,"file":"ToolInvocationTracker.d.ts","names":[],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"mappings":";;;;;;;KAwBY;EACN;;EAEA;EACA;IAAW;IAAe;;;KAGpB;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;cA+EtB;mBACM;mBACA;mBACA;mBAIA;mBACA;mBAQA;;;;;;;mBAOA;mBACA;UAET;UAEA;UACA;;UAGA;UACA;UAEA;;;;;;;;;;;UAYA;UACA;EAGN,YAAA,gBAAgB,eAAe,mBAC/B,WAAW,sBAAsB,WACjC,oBAAoB,UAAU;;;;;;UAcxB;;;;;EAsDD,SAAS,UAAU,sBAAsB;;;;;;EAmEzC;;;;;;;;;;EA8BA,MAAM;IAAY;MAA6B;;;;;;;EA2C/C,OAAO,oBAAoB;;;;;;;EAoB3B,eAAe,oBAAoB;UAMlC;UA6CA;UAaA;UAmCA;UAcA;UA0BA;UAkCA;UAWA;UAaA;UAOA;UAUA;;;;;;;UAeA;UAcA;;;;;;;;UA8BA;UAqBA;UA0GA;;kBAuFO;OACH,kBAAkB;OAElB;aACD,mBAAmB;;aAEnB;;;;;;aAMA;;OAGC;;;;;IAKV,WAAW,SAAS;;;;;;IAMpB,mBACE,UAAU,oBAAoB"}
|
|
@@ -487,7 +487,8 @@ var ToolInvocationTracker = class {
|
|
|
487
487
|
let entry = existing;
|
|
488
488
|
if (content.result !== void 0) this._discardedToolCallIds.delete(content.toolCallId);
|
|
489
489
|
if (entry && !entry.controller) {
|
|
490
|
-
if (
|
|
490
|
+
if (entry.hasResult) continue;
|
|
491
|
+
if (!(content.argsText !== entry.argsText && !(isArgsTextComplete(entry.argsText) && isArgsTextComplete(content.argsText) && isEquivalentCompleteArgsText(entry.argsText, content.argsText))) && content.result === void 0) continue;
|
|
491
492
|
this._entries.delete(content.toolCallId);
|
|
492
493
|
entry = void 0;
|
|
493
494
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolInvocationTracker.js","names":["process","env","NODE_ENV","createAssistantStreamController","ToolCallStreamController","ToolResponse","unstable_toolResultStream","Tool","ToolModelContentPart","ToolResultStreamOptions","AssistantMetaTransformStream","ReadonlyJSONValue","isJSONValueEqual","ThreadMessage","ToolCallMessagePart","walkToolCallTree","TOOL_EXECUTION_ID","Symbol","for","ToolExecutionStatus","type","payload","AddToolResultCommand","toolCallId","toolName","result","isError","artifact","modelContent","ToolCallEntry","argsText","hasResult","executionId","skipExecute","controller","argsComplete","clientOwned","SettledResolver","executionIds","ReadonlySet","resolve","isArgsTextComplete","JSON","parse","parseArgsText","undefined","isEquivalentCompleteArgsText","previous","next","previousValue","nextValue","getToolExecutionId","value","Record","PropertyKey","ToolInvocationTracker","_getTools","_callbacks","Callbacks","_isClientToolCall","toolCall","_entries","Map","_humanInput","reject","reason","_executing","Set","_discardedToolCallIds","_settledResolvers","_statuses","_ac","AbortController","_pendingRestore","_lastSnapshot","Snapshot","_isRunning","_controller","ReturnType","_pipelineDead","_pipelineRestartUsed","constructor","getTools","callbacks","isClientToolCall","_initPipeline","stream","human","_onHumanInput","transform","_getWrappedTools","signal","onExecutionStart","id","_name","_onExecutionStart","onExecutionEnd","_onExecutionEnd","pipeThrough","pipeTo","WritableStream","write","chunk","_handleResultChunk","err","console","error","catch","setState","snapshot","_demoteEntriesToRestored","clear","messages","isRunning","isLoading","restoreFromLoading","previousIsRunning","_processMessages","reset","abort","size","_invokeOnStatusesChange","options","discardPending","Promise","forEach","Error","entry","add","push","resume","handlers","get","delete","_setStatus","getStatuses","ReadonlyMap","tools","Object","fromEntries","entries","map","name","tool","execute","streamCall","wrappedTool","args","context","Parameters","_captureExecution","reader","set","_deleteStatus","pending","some","has","length","meta","_invokeOnResult","command","onResult","onStatusesChange","status","_warnProviderOwnedSkip","warn","_shouldCloseArgsStream","_startActiveEntry","toolCallController","addToolCallPart","_processArgsText","content","shouldWriteArgsText","startsWith","shouldClose","close","delta","slice","append","isRestore","part","existing","signatureChanged","ownership","providerOwned","approval","activeController","setResponse","ExecutionStatus","statuses"],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"sourcesContent":["declare const process: { env: { NODE_ENV?: string } };\n\nimport {\n createAssistantStreamController,\n type ToolCallStreamController,\n ToolResponse,\n unstable_toolResultStream,\n type Tool,\n type ToolModelContentPart,\n type ToolResultStreamOptions,\n} from \"assistant-stream\";\nimport {\n AssistantMetaTransformStream,\n type ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\nimport { isJSONValueEqual } from \"../../utils/json/is-json-equal\";\nimport type { ThreadMessage, ToolCallMessagePart } from \"../../types/message\";\nimport { walkToolCallTree } from \"../../runtime/utils/tool-call-tree\";\n\nconst TOOL_EXECUTION_ID = Symbol.for(\"assistant-stream.tool-execution-id\");\n\n/**\n * Streaming execution state for a frontend tool.\n */\nexport type ToolExecutionStatus =\n | { type: \"executing\" }\n | {\n type: \"interrupt\";\n payload: { type: \"human\"; payload: unknown };\n };\n\nexport type AddToolResultCommand = {\n readonly type: \"add-tool-result\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly result: ReadonlyJSONValue;\n readonly isError: boolean;\n readonly artifact?: ReadonlyJSONValue;\n readonly modelContent?: readonly ToolModelContentPart[];\n};\n\ntype ToolCallEntry = {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n executionId?: symbol;\n skipExecute?: boolean;\n} & (\n | {\n /** Restored phase — observed during a history-load snapshot. */\n controller?: undefined;\n argsComplete?: undefined;\n }\n | {\n /** Active phase — chunks are flowing through `controller`. */\n controller: ToolCallStreamController;\n argsComplete: boolean;\n clientOwned: boolean;\n }\n);\n\ntype SettledResolver = {\n executionIds: ReadonlySet<symbol>;\n resolve: () => void;\n};\n\nconst isArgsTextComplete = (argsText: string) => {\n try {\n JSON.parse(argsText);\n return true;\n } catch {\n return false;\n }\n};\n\nconst parseArgsText = (argsText: string) => {\n try {\n return JSON.parse(argsText);\n } catch {\n return undefined;\n }\n};\n\nconst isEquivalentCompleteArgsText = (previous: string, next: string) => {\n const previousValue = parseArgsText(previous);\n const nextValue = parseArgsText(next);\n if (previousValue === undefined || nextValue === undefined) return false;\n return isJSONValueEqual(previousValue, nextValue);\n};\n\nconst getToolExecutionId = (value: object): symbol | undefined =>\n (value as Record<PropertyKey, unknown>)[TOOL_EXECUTION_ID] as\n | symbol\n | undefined;\n\n/**\n * Plain-class port of the former `useToolInvocations` React hook. Owns the\n * assistant-stream pipeline that drives client-side `streamCall` / `execute`\n * for tool-call parts surfaced by a thread runtime, plus the per-tool-call\n * status map that consumers render against.\n *\n * **Contract**: `streamCall` (and `execute`) fires exactly once per logical\n * `toolCallId`. Args mutations after first completion, result replacement,\n * and result clearing are *not* surfaced through additional `streamCall`\n * invocations — by design — so hosts cannot observe spurious re-fires of\n * side effects. The follow-up `reader.events()` API will expose those\n * post-completion transitions to consumers that opt in.\n *\n * State-transition safety: every public method that observes runtime state\n * (`setState`, `reset`, `abort`, `resume`) wraps its work in try/catch and\n * logs to `console.error` rather than throwing. The tracker is built into\n * the hot message-processing path, so a malformed snapshot must never crash\n * the host runtime. See ./EDGE_CASES.md for the known non-trivial state\n * transitions and what each does today.\n *\n * @deprecated Internal — for framework bindings; not a public API. May change without notice.\n */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTracker.Callbacks;\n private readonly _isClientToolCall:\n | ((toolCall: ToolCallMessagePart) => boolean | undefined)\n | undefined;\n\n private readonly _entries = new Map<string, ToolCallEntry>();\n private readonly _humanInput = new Map<\n string,\n {\n executionId: symbol;\n resolve: (payload: unknown) => void;\n reject: (reason: unknown) => void;\n }\n >();\n private readonly _executing = new Set<symbol>();\n /**\n * Tool calls whose turn ended before they reached the executor. Held here\n * rather than on the entry because an entry is rebuilt whenever a snapshot\n * re-creates the call, and this is the one reason to skip that no later\n * snapshot carries.\n */\n private readonly _discardedToolCallIds = new Set<string>();\n private readonly _settledResolvers: SettledResolver[] = [];\n\n private _statuses = new Map<string, ToolExecutionStatus>();\n\n private _ac: AbortController = new AbortController();\n private _pendingRestore = true;\n\n /** Cached last snapshot, used to skip processing on identical re-renders. */\n private _lastSnapshot: ToolInvocationTracker.Snapshot | null = null;\n private _isRunning = false;\n\n private _controller!: ReturnType<typeof createAssistantStreamController>[1];\n\n /**\n * Set when the assistant-stream pipeline has died (errored out via\n * `.pipeTo(...).catch(...)`). The next `setState` re-initializes the\n * pipeline and demotes each active entry that reached the executor to\n * restored, so it survives the restart without re-firing `streamCall`.\n * A restart is an execution boundary like `reset()`: an entry that had\n * not reached it starts over and fires once there (F.4). Capped at a\n * single auto-restart per session — repeated failures keep the tracker\n * dead with a more visible error.\n */\n private _pipelineDead = false;\n private _pipelineRestartUsed = false;\n\n constructor(\n getTools: () => Record<string, Tool> | undefined,\n callbacks: ToolInvocationTracker.Callbacks,\n isClientToolCall?: (toolCall: ToolCallMessagePart) => boolean | undefined,\n ) {\n this._getTools = getTools;\n this._callbacks = callbacks;\n this._isClientToolCall = isClientToolCall;\n\n this._initPipeline();\n }\n\n /**\n * Build the assistant-stream pipeline. Called once from the constructor\n * and at most once again if `_pipelineDead` is set (see F.4 in\n * EDGE_CASES.md).\n */\n private _initPipeline(): void {\n const [stream, controller] = createAssistantStreamController();\n this._controller = controller;\n\n const human = (\n toolCallId: string,\n payload: unknown,\n executionId?: symbol,\n ) => this._onHumanInput(toolCallId, payload, executionId);\n const transform = unstable_toolResultStream(\n () => this._getWrappedTools(),\n () => this._ac.signal,\n human,\n {\n onExecutionStart: (id: string, _name: string, executionId?: symbol) =>\n this._onExecutionStart(id, executionId),\n onExecutionEnd: (id: string, _name: string, executionId?: symbol) =>\n this._onExecutionEnd(id, executionId),\n } as ToolResultStreamOptions,\n );\n\n stream\n .pipeThrough(transform)\n .pipeThrough(new AssistantMetaTransformStream())\n .pipeTo(\n new WritableStream({\n write: (chunk) => {\n try {\n if (chunk.type !== \"result\") return;\n this._handleResultChunk(chunk);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] result chunk handling failed\",\n err,\n );\n }\n },\n }),\n )\n .catch((err) => {\n console.error(\n \"[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState\",\n err,\n );\n this._pipelineDead = true;\n });\n }\n\n // ───────────────────────── public API ─────────────────────────\n\n /**\n * Feed the next observed snapshot into the tracker. Called from the host\n * runtime whenever its message list / running state changes.\n */\n public setState(snapshot: ToolInvocationTracker.Snapshot): void {\n try {\n // Recover from a dead pipeline before processing anything. Entries\n // that reached the executor are demoted to \"restored\" so the rebuilt\n // pipeline does not re-fire `streamCall` for them; the rest start over\n // across the boundary the restart opens (F.4).\n if (this._pipelineDead) {\n if (this._pipelineRestartUsed) {\n // Already retried once and failed again. Stay dead.\n return;\n }\n this._pipelineRestartUsed = true;\n this._pipelineDead = false;\n this._demoteEntriesToRestored();\n this._executing.clear();\n this._ac = new AbortController();\n this._initPipeline();\n // Fall through and process the snapshot against the fresh pipeline.\n }\n\n // Identical snapshot — skip processing entirely. Note: external-store\n // runtimes rebuild the messages array on every adapter update, so this\n // fast-path rarely triggers there; it's primarily for the React-hook\n // shim where state references are stable.\n if (\n this._lastSnapshot &&\n this._lastSnapshot.messages === snapshot.messages &&\n this._lastSnapshot.isRunning === snapshot.isRunning &&\n this._lastSnapshot.isLoading === snapshot.isLoading\n ) {\n return;\n }\n\n // While the host is still loading initial state, treat every snapshot\n // as historical: tool calls are recorded so the next live snapshot can\n // diff against them, but `streamCall` / `execute` do not fire.\n const restoreFromLoading = snapshot.isLoading === true;\n if (restoreFromLoading) {\n this._pendingRestore = true;\n }\n\n // E.4 / AF3 — only mark `_lastSnapshot`/`_isRunning` as observed after\n // processing succeeds. If `_processMessages` throws, the next snapshot\n // (even if identical) gets re-processed against the recovered state.\n const previousIsRunning = this._isRunning;\n this._isRunning = snapshot.isRunning;\n try {\n this._processMessages(snapshot.messages);\n } catch (err) {\n this._isRunning = previousIsRunning;\n throw err;\n }\n this._lastSnapshot = snapshot;\n this._pendingRestore = false;\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] setState failed; snapshot dropped\",\n err,\n );\n }\n }\n\n /**\n * Reset the tracker so the next observed snapshot is treated as historical.\n * Clears entries and aborts any in-flight executions. Used by callers like\n * `importExternalState` to mark a freshly loaded state as restored.\n */\n public reset(): void {\n try {\n this._pendingRestore = true;\n this._entries.clear();\n this._discardedToolCallIds.clear();\n this._lastSnapshot = null;\n void this.abort();\n // Statuses are cleared synchronously: discarded executions may never\n // settle (aborting hands the signal to the tool, it does not force\n // settlement), and a late settlement of one sibling must not republish\n // the others. `_deleteStatus` no-ops for cleared ids, so post-reset\n // settlements stay silent.\n if (this._statuses.size > 0) {\n this._statuses = new Map();\n this._invokeOnStatusesChange();\n }\n } catch (err) {\n console.error(\"[ToolInvocationTracker] reset failed\", err);\n }\n }\n\n /**\n * Abort any in-flight `execute()` invocations. Resolves once all of them\n * have settled (or immediately if none are running).\n *\n * `discardPending` additionally kills the calls that never reached the\n * executor, for a caller ending the turn rather than interrupting it. The\n * signal cannot reach those: they are waiting on the run to settle (A.10),\n * and the settled snapshot arrives after this installs a fresh controller.\n */\n public abort(options?: { discardPending?: boolean }): Promise<void> {\n try {\n this._humanInput.forEach(({ reject }) => {\n try {\n reject(new Error(\"Tool execution aborted\"));\n } catch {\n // host rejection handler threw — already in the abort path,\n // swallow so we continue cleaning up.\n }\n });\n this._humanInput.clear();\n\n if (options?.discardPending) {\n for (const [toolCallId, entry] of this._entries) {\n if (!entry.controller) continue;\n if (entry.argsComplete || entry.hasResult) continue;\n this._discardedToolCallIds.add(toolCallId);\n entry.skipExecute = true;\n }\n }\n\n this._ac.abort();\n this._ac = new AbortController();\n\n if (this._executing.size === 0) {\n return Promise.resolve();\n }\n const executionIds = new Set(this._executing);\n return new Promise<void>((resolve) => {\n this._settledResolvers.push({ executionIds, resolve });\n });\n } catch (err) {\n console.error(\"[ToolInvocationTracker] abort failed\", err);\n return Promise.resolve();\n }\n }\n\n /**\n * Resolve a pending human-input request for the given tool call. Returns\n * `true` if a pending request was resumed, `false` if the tracker has no\n * outstanding request for that id (the caller should fall back to its own\n * dispatch path).\n */\n public resume(toolCallId: string, payload: unknown): boolean {\n try {\n const handlers = this._humanInput.get(toolCallId);\n if (!handlers) return false;\n this._humanInput.delete(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n handlers.resolve(payload);\n return true;\n } catch (err) {\n console.error(\"[ToolInvocationTracker] resume failed\", err);\n return false;\n }\n }\n\n /**\n * Returns the current tool execution status map. The returned `Map` is\n * the tracker's internal store — do not mutate it. Treat the reference\n * as a snapshot that may be replaced wholesale on the next status\n * transition.\n */\n public getStatuses(): ReadonlyMap<string, ToolExecutionStatus> {\n return this._statuses;\n }\n\n // ───────────────────── internal: tool wrapping ─────────────────────\n\n private _getWrappedTools(): Record<string, Tool> | undefined {\n const tools = this._getTools();\n if (!tools) return undefined;\n\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => {\n const execute = tool.execute;\n const streamCall = tool.streamCall;\n if (execute === undefined && streamCall === undefined)\n return [name, tool];\n\n const wrappedTool = {\n ...tool,\n ...(execute !== undefined && {\n execute: (...[args, context]: Parameters<typeof execute>) => {\n const executionId = getToolExecutionId(context);\n const entry = this._captureExecution(\n context.toolCallId,\n executionId,\n );\n if (!entry || entry.skipExecute) {\n return new Promise(() => {}) as never;\n }\n return execute(args, context);\n },\n }),\n ...(streamCall !== undefined && {\n streamCall: (\n ...[reader, context]: Parameters<typeof streamCall>\n ) => {\n const executionId = getToolExecutionId(context);\n const entry = this._captureExecution(\n context.toolCallId,\n executionId,\n );\n if (!entry) return;\n return streamCall(reader, context);\n },\n }),\n } as Tool;\n return [name, wrappedTool];\n }),\n ) as Record<string, Tool>;\n }\n\n private _captureExecution(\n toolCallId: string,\n executionId: symbol | undefined,\n ): ToolCallEntry | undefined {\n if (executionId === undefined) return undefined;\n const entry = this._entries.get(toolCallId);\n if (!entry?.controller) return undefined;\n if (entry.executionId === undefined) entry.executionId = executionId;\n return entry.executionId === executionId ? entry : undefined;\n }\n\n // ──────────────── internal: execution lifecycle callbacks ────────────────\n\n private _onHumanInput(\n toolCallId: string,\n payload: unknown,\n executionId?: symbol,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n // A discarded execution must not resurrect a status entry or park an\n // unanswerable request after its id has been reused.\n const entry = this._entries.get(toolCallId);\n if (!entry?.controller || entry.executionId !== executionId) {\n reject(new Error(\"Tool execution aborted\"));\n return;\n }\n const previous = this._humanInput.get(toolCallId);\n if (previous) {\n try {\n previous.reject(\n new Error(\"Human input request was superseded by a new request\"),\n );\n } catch {\n // host rejection handler threw; ignore and proceed\n }\n }\n this._humanInput.set(toolCallId, {\n executionId: executionId!,\n resolve,\n reject,\n });\n this._setStatus(toolCallId, {\n type: \"interrupt\",\n payload: { type: \"human\", payload },\n });\n });\n }\n\n private _onExecutionStart(\n toolCallId: string,\n executionId: symbol | undefined,\n ): void {\n if (!this._captureExecution(toolCallId, executionId)) return;\n const entry = this._entries.get(toolCallId)!;\n if (entry.skipExecute) return;\n\n this._executing.add(executionId!);\n // execute can park human() before onExecutionStart; preserve this execution's interrupt.\n if (this._humanInput.get(toolCallId)?.executionId === executionId) return;\n this._setStatus(toolCallId, { type: \"executing\" });\n }\n\n private _onExecutionEnd(\n toolCallId: string,\n executionId: symbol | undefined,\n ): void {\n if (executionId === undefined || !this._executing.delete(executionId))\n return;\n\n const entry = this._entries.get(toolCallId);\n if (entry?.executionId === executionId) this._deleteStatus(toolCallId);\n\n const pending: SettledResolver[] = [];\n this._settledResolvers.forEach(({ executionIds, resolve }) => {\n if ([...executionIds].some((id) => this._executing.has(id))) {\n pending.push({ executionIds, resolve });\n return;\n }\n try {\n resolve();\n } catch {\n // ignore — settled-resolver consumer threw\n }\n });\n this._settledResolvers.length = 0;\n this._settledResolvers.push(...pending);\n }\n\n private _handleResultChunk(chunk: {\n type: \"result\";\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue;\n modelContent?: readonly ToolModelContentPart[];\n meta: { toolCallId: string; toolName: string };\n }): void {\n const toolCallId = chunk.meta.toolCallId;\n const executionId = getToolExecutionId(chunk);\n const entry = this._entries.get(toolCallId);\n\n if (!entry || entry.executionId !== executionId) return;\n\n // The host already set the result (via the live snapshot's\n // `setResponse` path). Suppress the executor's redundant emit.\n if (entry?.hasResult) return;\n if (entry.skipExecute) return;\n\n this._invokeOnResult({\n type: \"add-tool-result\",\n toolCallId,\n toolName: chunk.meta.toolName,\n result: chunk.result,\n isError: chunk.isError,\n ...(chunk.artifact !== undefined && { artifact: chunk.artifact }),\n ...(chunk.modelContent !== undefined && {\n modelContent: chunk.modelContent,\n }),\n });\n }\n\n // ──────────────── internal: callback invocation (AF1/AF2) ────────────────\n\n private _invokeOnResult(command: AddToolResultCommand): void {\n try {\n this._callbacks.onResult(command);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onResult callback threw; result dropped\",\n err,\n );\n }\n }\n\n private _invokeOnStatusesChange(): void {\n try {\n this._callbacks.onStatusesChange(this._statuses);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated\",\n err,\n );\n }\n }\n\n // ──────────────── internal: status map mutations ────────────────\n\n private _setStatus(toolCallId: string, status: ToolExecutionStatus): void {\n const next = new Map(this._statuses);\n next.set(toolCallId, status);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n private _deleteStatus(toolCallId: string): void {\n if (!this._statuses.has(toolCallId)) return;\n const next = new Map(this._statuses);\n next.delete(toolCallId);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n // ──────────────── internal: snapshot processing ────────────────\n\n private _warnProviderOwnedSkip(toolName: string, toolCallId: string): void {\n if (process.env.NODE_ENV === \"production\") return;\n if (this._getTools()?.[toolName]?.execute === undefined) return;\n console.warn(\n \"[ToolInvocationTracker] the runtime reports this tool call as provider-owned, so the registered execute is skipped; the provider has to hand the call to the client for it to run (see EDGE_CASES.md A.9)\",\n { toolCallId, toolName },\n );\n }\n\n /**\n * Closing the args stream hands the call to the client executor, so it may\n * only happen once the provider can no longer speak about that call. The run\n * ending is the only universal signal for that; an adapter that reports the\n * call as client-owned has said it earlier, per call.\n */\n private _shouldCloseArgsStream({\n argsText,\n hasResult,\n clientOwned,\n }: {\n argsText: string;\n hasResult: boolean;\n clientOwned: boolean;\n }): boolean {\n if (hasResult) return true;\n if (!isArgsTextComplete(argsText)) return false;\n return clientOwned || !this._isRunning;\n }\n\n private _startActiveEntry(\n toolCallId: string,\n toolName: string,\n skipExecute: boolean,\n clientOwned: boolean,\n ): ToolCallEntry {\n const toolCallController = this._controller.addToolCallPart({\n toolName,\n toolCallId,\n });\n const entry: ToolCallEntry = {\n toolName,\n controller: toolCallController,\n argsText: \"\",\n hasResult: false,\n skipExecute,\n argsComplete: false,\n clientOwned,\n };\n this._entries.set(toolCallId, entry);\n return entry;\n }\n\n /**\n * Demote every active entry back to the restored phase. Used by the\n * pipeline-restart path so that, after a fresh pipeline is built, the\n * next observed snapshot does not re-fire `streamCall` for tool calls\n * that already fired pre-death. Args / hasResult tracking is preserved\n * so signature comparisons still work.\n */\n private _demoteEntriesToRestored(): void {\n for (const [toolCallId, entry] of this._entries) {\n if (!entry.controller) continue;\n if (!entry.argsComplete && !entry.hasResult) {\n // The call never reached the executor. A restored entry is promoted\n // only when its signature changes, and a call waiting on the run to\n // settle already holds its final args, so demoting it would strand it\n // unexecuted. Dropping it lets the next snapshot start it over; a call\n // whose turn was discarded is held by `_discardedToolCallIds`, not by\n // the entry, so starting over does not revive it.\n this._entries.delete(toolCallId);\n continue;\n }\n this._entries.set(toolCallId, {\n toolName: entry.toolName,\n argsText: entry.argsText,\n hasResult: entry.hasResult,\n });\n }\n }\n\n private _processArgsText(\n entry: ToolCallEntry,\n content: {\n toolCallId: string;\n toolName: string;\n argsText: string;\n result?: unknown;\n },\n ): void {\n if (!entry.controller) return;\n const hasResult = content.result !== undefined;\n\n if (content.argsText !== entry.argsText) {\n let shouldWriteArgsText = true;\n\n if (entry.argsComplete) {\n if (isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {\n // A.3 — key reorder. Track new text, no re-fire needed.\n entry.argsText = content.argsText;\n shouldWriteArgsText = false;\n } else {\n // A.4 — args changed after first completion. Under the\n // \"exactly once per toolCallId\" contract we do not restart the\n // stream. The host's existing `streamCall` keeps its original\n // args view; the snapshot's new text is recorded for diffing\n // but not surfaced. Events API in a follow-up will expose this\n // to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText changed after first completion; not re-firing streamCall (see EDGE_CASES.md A.4)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n } else if (!content.argsText.startsWith(entry.argsText)) {\n if (\n isArgsTextComplete(entry.argsText) &&\n isArgsTextComplete(content.argsText) &&\n isEquivalentCompleteArgsText(entry.argsText, content.argsText)\n ) {\n const shouldClose = this._shouldCloseArgsStream({\n argsText: content.argsText,\n hasResult,\n clientOwned: entry.clientOwned,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n shouldWriteArgsText = false;\n } else {\n // A.2 — args regressed mid-stream. Under the \"exactly once\"\n // contract we do not restart. The controller keeps whatever\n // prefix we already streamed; subsequent prefix-respecting\n // updates can still flow against it. Snapshots that never\n // re-converge to a prefix will leave the controller's args\n // view stale relative to the snapshot. Events API in a\n // follow-up will expose this to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText regressed mid-stream; not restarting (see EDGE_CASES.md A.2)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n }\n\n if (shouldWriteArgsText && entry.controller) {\n const delta = content.argsText.slice(entry.argsText.length);\n entry.controller.argsText.append(delta);\n const shouldClose = this._shouldCloseArgsStream({\n argsText: content.argsText,\n hasResult,\n clientOwned: entry.clientOwned,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n }\n }\n\n if (!entry.argsComplete && entry.controller) {\n // ToolExecutionStream parses the streamed prefix on close, so the close\n // gates on the streamed content; a divergent snapshot (A.2) can be\n // complete while the controller still holds an incomplete stale prefix.\n const shouldClose = this._shouldCloseArgsStream({\n argsText: entry.argsText,\n hasResult,\n clientOwned: entry.clientOwned,\n });\n if (shouldClose) {\n entry.controller.argsText.close();\n entry.argsComplete = true;\n }\n }\n }\n\n private _processMessages(messages: readonly ThreadMessage[]): void {\n const isRestore = this._pendingRestore;\n\n for (const { part: content } of walkToolCallTree(messages)) {\n const existing = this._entries.get(content.toolCallId);\n\n if (isRestore) {\n // Don't overwrite an already-active entry (e.g. live tool-call\n // observed before this restore snapshot landed). Restore can\n // only seed entries the runtime has never seen.\n if (!existing?.controller) {\n this._entries.set(content.toolCallId, {\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult: content.result !== undefined,\n });\n }\n continue;\n }\n\n // Live snapshot.\n let entry = existing;\n\n // A discarded id is remembered only until the call is answered, which\n // bounds the set to the open calls of a discarded turn.\n if (content.result !== undefined)\n this._discardedToolCallIds.delete(content.toolCallId);\n\n if (entry && !entry.controller) {\n // Restored entry observed in a live snapshot. Promote if its\n // signature has changed; otherwise treat as still-historical.\n const signatureChanged =\n content.argsText !== entry.argsText ||\n (content.result !== undefined) !== entry.hasResult;\n if (!signatureChanged) continue;\n this._entries.delete(content.toolCallId);\n entry = undefined;\n }\n\n if (!entry) {\n const ownership = this._isClientToolCall?.(content);\n const providerOwned =\n content.result === undefined && ownership === false;\n if (providerOwned)\n this._warnProviderOwnedSkip(content.toolName, content.toolCallId);\n entry = this._startActiveEntry(\n content.toolCallId,\n content.toolName,\n content.result !== undefined ||\n providerOwned ||\n this._discardedToolCallIds.has(content.toolCallId),\n ownership === true,\n );\n }\n\n if (content.approval !== undefined) entry.skipExecute = true;\n\n this._processArgsText(entry, content);\n\n if (content.result !== undefined && !entry.hasResult) {\n // `entry` is in active phase from this point — either just\n // created by `_startActiveEntry`, or pre-existing with a live\n // controller. Narrow once instead of asserting at every use.\n const { controller: activeController } = entry;\n if (!activeController) continue;\n entry.hasResult = true;\n entry.argsComplete = true;\n activeController.setResponse(\n new ToolResponse({\n result: content.result as ReadonlyJSONValue,\n artifact: content.artifact as ReadonlyJSONValue | undefined,\n isError: content.isError,\n ...(content.modelContent !== undefined\n ? { modelContent: content.modelContent }\n : {}),\n }),\n );\n activeController.close();\n }\n }\n }\n}\n\nexport namespace ToolInvocationTracker {\n export type ExecutionStatus = ToolExecutionStatus;\n\n export type Snapshot = {\n readonly messages: readonly ThreadMessage[];\n /** Whether the producing runtime is currently streaming new output. */\n readonly isRunning: boolean;\n /**\n * Whether the producing runtime is still loading historical state.\n * When `true`, every snapshot is treated as historical (no `streamCall` /\n * `execute` fires). When `false`, processing resumes as live.\n */\n readonly isLoading?: boolean;\n };\n\n export type Callbacks = {\n /**\n * Invoked when a client-side `execute()` returns a result and the runtime\n * needs to feed it back into the conversation.\n */\n onResult: (command: AddToolResultCommand) => void;\n /**\n * Invoked whenever the per-tool-call status map changes (executing /\n * interrupt / cleared). The callback receives a fresh map; mutating the\n * argument is not supported.\n */\n onStatusesChange: (\n statuses: ReadonlyMap<string, ToolExecutionStatus>,\n ) => void;\n };\n}\n"],"mappings":";;;;;AAmBA,MAAMgB,oBAAoBC,OAAOC,IAAI,oCAAoC;AA+CzE,MAAMuB,sBAAsBX,aAAqB;CAC/C,IAAI;EACFY,KAAKC,MAAMb,QAAQ;EACnB,OAA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,IAAI,EAFFyI,QAAQ7I,aAAaiG,MAAMjG,YAC1B6I,QAAQlJ,WAAWoB,KAAAA,MAAekF,MAAMhG,YACpB;IACvB,KAAK8B,SAASwE,OAAOsC,QAAQpJ,UAAU;IACvCwG,QAAQlF,KAAAA;GACV;GAEA,IAAI,CAACkF,OAAO;IACV,MAAMwD,YAAY,KAAK5H,oBAAoBgH,OAAO;IAClD,MAAMa,gBACJb,QAAQlJ,WAAWoB,KAAAA,KAAa0I,cAAc;IAChD,IAAIC,eACF,KAAKpB,uBAAuBO,QAAQnJ,UAAUmJ,QAAQpJ,UAAU;IAClEwG,QAAQ,KAAKwC,kBACXI,QAAQpJ,YACRoJ,QAAQnJ,UACRmJ,QAAQlJ,WAAWoB,KAAAA,KACjB2I,iBACA,KAAKpH,sBAAsBwF,IAAIe,QAAQpJ,UAAU,GACnDgK,cAAc,IAChB;GACF;GAEA,IAAIZ,QAAQc,aAAa5I,KAAAA,GAAWkF,MAAM9F,cAAc;GAExD,KAAKyI,iBAAiB3C,OAAO4C,OAAO;GAEpC,IAAIA,QAAQlJ,WAAWoB,KAAAA,KAAa,CAACkF,MAAMhG,WAAW;IAIpD,MAAM,EAAEG,YAAYwJ,qBAAqB3D;IACzC,IAAI,CAAC2D,kBAAkB;IACvB3D,MAAMhG,YAAY;IAClBgG,MAAM5F,eAAe;IACrBuJ,iBAAiBC,YACf,IAAItL,aAAa;KACfoB,QAAQkJ,QAAQlJ;KAChBE,UAAUgJ,QAAQhJ;KAClBD,SAASiJ,QAAQjJ;KACjB,GAAIiJ,QAAQ/I,iBAAiBiB,KAAAA,IACzB,EAAEjB,cAAc+I,QAAQ/I,aAAa,IACrC,CAAC;IACP,CAAC,CACH;IACA8J,iBAAiBX,MAAM;GACzB;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"ToolInvocationTracker.js","names":["process","env","NODE_ENV","createAssistantStreamController","ToolCallStreamController","ToolResponse","unstable_toolResultStream","Tool","ToolModelContentPart","ToolResultStreamOptions","AssistantMetaTransformStream","ReadonlyJSONValue","isJSONValueEqual","ThreadMessage","ToolCallMessagePart","walkToolCallTree","TOOL_EXECUTION_ID","Symbol","for","ToolExecutionStatus","type","payload","AddToolResultCommand","toolCallId","toolName","result","isError","artifact","modelContent","ToolCallEntry","argsText","hasResult","executionId","skipExecute","controller","argsComplete","clientOwned","SettledResolver","executionIds","ReadonlySet","resolve","isArgsTextComplete","JSON","parse","parseArgsText","undefined","isEquivalentCompleteArgsText","previous","next","previousValue","nextValue","getToolExecutionId","value","Record","PropertyKey","ToolInvocationTracker","_getTools","_callbacks","Callbacks","_isClientToolCall","toolCall","_entries","Map","_humanInput","reject","reason","_executing","Set","_discardedToolCallIds","_settledResolvers","_statuses","_ac","AbortController","_pendingRestore","_lastSnapshot","Snapshot","_isRunning","_controller","ReturnType","_pipelineDead","_pipelineRestartUsed","constructor","getTools","callbacks","isClientToolCall","_initPipeline","stream","human","_onHumanInput","transform","_getWrappedTools","signal","onExecutionStart","id","_name","_onExecutionStart","onExecutionEnd","_onExecutionEnd","pipeThrough","pipeTo","WritableStream","write","chunk","_handleResultChunk","err","console","error","catch","setState","snapshot","_demoteEntriesToRestored","clear","messages","isRunning","isLoading","restoreFromLoading","previousIsRunning","_processMessages","reset","abort","size","_invokeOnStatusesChange","options","discardPending","Promise","forEach","Error","entry","add","push","resume","handlers","get","delete","_setStatus","getStatuses","ReadonlyMap","tools","Object","fromEntries","entries","map","name","tool","execute","streamCall","wrappedTool","args","context","Parameters","_captureExecution","reader","set","_deleteStatus","pending","some","has","length","meta","_invokeOnResult","command","onResult","onStatusesChange","status","_warnProviderOwnedSkip","warn","_shouldCloseArgsStream","_startActiveEntry","toolCallController","addToolCallPart","_processArgsText","content","shouldWriteArgsText","startsWith","shouldClose","close","delta","slice","append","isRestore","part","existing","argsChanged","ownership","providerOwned","approval","activeController","setResponse","ExecutionStatus","statuses"],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"sourcesContent":["declare const process: { env: { NODE_ENV?: string } };\n\nimport {\n createAssistantStreamController,\n type ToolCallStreamController,\n ToolResponse,\n unstable_toolResultStream,\n type Tool,\n type ToolModelContentPart,\n type ToolResultStreamOptions,\n} from \"assistant-stream\";\nimport {\n AssistantMetaTransformStream,\n type ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\nimport { isJSONValueEqual } from \"../../utils/json/is-json-equal\";\nimport type { ThreadMessage, ToolCallMessagePart } from \"../../types/message\";\nimport { walkToolCallTree } from \"../../runtime/utils/tool-call-tree\";\n\nconst TOOL_EXECUTION_ID = Symbol.for(\"assistant-stream.tool-execution-id\");\n\n/**\n * Streaming execution state for a frontend tool.\n */\nexport type ToolExecutionStatus =\n | { type: \"executing\" }\n | {\n type: \"interrupt\";\n payload: { type: \"human\"; payload: unknown };\n };\n\nexport type AddToolResultCommand = {\n readonly type: \"add-tool-result\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly result: ReadonlyJSONValue;\n readonly isError: boolean;\n readonly artifact?: ReadonlyJSONValue;\n readonly modelContent?: readonly ToolModelContentPart[];\n};\n\ntype ToolCallEntry = {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n executionId?: symbol;\n skipExecute?: boolean;\n} & (\n | {\n /** Restored phase — observed during a history-load snapshot. */\n controller?: undefined;\n argsComplete?: undefined;\n }\n | {\n /** Active phase — chunks are flowing through `controller`. */\n controller: ToolCallStreamController;\n argsComplete: boolean;\n clientOwned: boolean;\n }\n);\n\ntype SettledResolver = {\n executionIds: ReadonlySet<symbol>;\n resolve: () => void;\n};\n\nconst isArgsTextComplete = (argsText: string) => {\n try {\n JSON.parse(argsText);\n return true;\n } catch {\n return false;\n }\n};\n\nconst parseArgsText = (argsText: string) => {\n try {\n return JSON.parse(argsText);\n } catch {\n return undefined;\n }\n};\n\nconst isEquivalentCompleteArgsText = (previous: string, next: string) => {\n const previousValue = parseArgsText(previous);\n const nextValue = parseArgsText(next);\n if (previousValue === undefined || nextValue === undefined) return false;\n return isJSONValueEqual(previousValue, nextValue);\n};\n\nconst getToolExecutionId = (value: object): symbol | undefined =>\n (value as Record<PropertyKey, unknown>)[TOOL_EXECUTION_ID] as\n | symbol\n | undefined;\n\n/**\n * Plain-class port of the former `useToolInvocations` React hook. Owns the\n * assistant-stream pipeline that drives client-side `streamCall` / `execute`\n * for tool-call parts surfaced by a thread runtime, plus the per-tool-call\n * status map that consumers render against.\n *\n * **Contract**: `streamCall` (and `execute`) fires exactly once per logical\n * `toolCallId`. Args mutations after first completion, result replacement,\n * and result clearing are *not* surfaced through additional `streamCall`\n * invocations — by design — so hosts cannot observe spurious re-fires of\n * side effects. The follow-up `reader.events()` API will expose those\n * post-completion transitions to consumers that opt in.\n *\n * State-transition safety: every public method that observes runtime state\n * (`setState`, `reset`, `abort`, `resume`) wraps its work in try/catch and\n * logs to `console.error` rather than throwing. The tracker is built into\n * the hot message-processing path, so a malformed snapshot must never crash\n * the host runtime. See ./EDGE_CASES.md for the known non-trivial state\n * transitions and what each does today.\n *\n * @deprecated Internal — for framework bindings; not a public API. May change without notice.\n */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTracker.Callbacks;\n private readonly _isClientToolCall:\n | ((toolCall: ToolCallMessagePart) => boolean | undefined)\n | undefined;\n\n private readonly _entries = new Map<string, ToolCallEntry>();\n private readonly _humanInput = new Map<\n string,\n {\n executionId: symbol;\n resolve: (payload: unknown) => void;\n reject: (reason: unknown) => void;\n }\n >();\n private readonly _executing = new Set<symbol>();\n /**\n * Tool calls whose turn ended before they reached the executor. Held here\n * rather than on the entry because an entry is rebuilt whenever a snapshot\n * re-creates the call, and this is the one reason to skip that no later\n * snapshot carries.\n */\n private readonly _discardedToolCallIds = new Set<string>();\n private readonly _settledResolvers: SettledResolver[] = [];\n\n private _statuses = new Map<string, ToolExecutionStatus>();\n\n private _ac: AbortController = new AbortController();\n private _pendingRestore = true;\n\n /** Cached last snapshot, used to skip processing on identical re-renders. */\n private _lastSnapshot: ToolInvocationTracker.Snapshot | null = null;\n private _isRunning = false;\n\n private _controller!: ReturnType<typeof createAssistantStreamController>[1];\n\n /**\n * Set when the assistant-stream pipeline has died (errored out via\n * `.pipeTo(...).catch(...)`). The next `setState` re-initializes the\n * pipeline and demotes each active entry that reached the executor to\n * restored, so it survives the restart without re-firing `streamCall`.\n * A restart is an execution boundary like `reset()`: an entry that had\n * not reached it starts over and fires once there (F.4). Capped at a\n * single auto-restart per session — repeated failures keep the tracker\n * dead with a more visible error.\n */\n private _pipelineDead = false;\n private _pipelineRestartUsed = false;\n\n constructor(\n getTools: () => Record<string, Tool> | undefined,\n callbacks: ToolInvocationTracker.Callbacks,\n isClientToolCall?: (toolCall: ToolCallMessagePart) => boolean | undefined,\n ) {\n this._getTools = getTools;\n this._callbacks = callbacks;\n this._isClientToolCall = isClientToolCall;\n\n this._initPipeline();\n }\n\n /**\n * Build the assistant-stream pipeline. Called once from the constructor\n * and at most once again if `_pipelineDead` is set (see F.4 in\n * EDGE_CASES.md).\n */\n private _initPipeline(): void {\n const [stream, controller] = createAssistantStreamController();\n this._controller = controller;\n\n const human = (\n toolCallId: string,\n payload: unknown,\n executionId?: symbol,\n ) => this._onHumanInput(toolCallId, payload, executionId);\n const transform = unstable_toolResultStream(\n () => this._getWrappedTools(),\n () => this._ac.signal,\n human,\n {\n onExecutionStart: (id: string, _name: string, executionId?: symbol) =>\n this._onExecutionStart(id, executionId),\n onExecutionEnd: (id: string, _name: string, executionId?: symbol) =>\n this._onExecutionEnd(id, executionId),\n } as ToolResultStreamOptions,\n );\n\n stream\n .pipeThrough(transform)\n .pipeThrough(new AssistantMetaTransformStream())\n .pipeTo(\n new WritableStream({\n write: (chunk) => {\n try {\n if (chunk.type !== \"result\") return;\n this._handleResultChunk(chunk);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] result chunk handling failed\",\n err,\n );\n }\n },\n }),\n )\n .catch((err) => {\n console.error(\n \"[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState\",\n err,\n );\n this._pipelineDead = true;\n });\n }\n\n // ───────────────────────── public API ─────────────────────────\n\n /**\n * Feed the next observed snapshot into the tracker. Called from the host\n * runtime whenever its message list / running state changes.\n */\n public setState(snapshot: ToolInvocationTracker.Snapshot): void {\n try {\n // Recover from a dead pipeline before processing anything. Entries\n // that reached the executor are demoted to \"restored\" so the rebuilt\n // pipeline does not re-fire `streamCall` for them; the rest start over\n // across the boundary the restart opens (F.4).\n if (this._pipelineDead) {\n if (this._pipelineRestartUsed) {\n // Already retried once and failed again. Stay dead.\n return;\n }\n this._pipelineRestartUsed = true;\n this._pipelineDead = false;\n this._demoteEntriesToRestored();\n this._executing.clear();\n this._ac = new AbortController();\n this._initPipeline();\n // Fall through and process the snapshot against the fresh pipeline.\n }\n\n // Identical snapshot — skip processing entirely. Note: external-store\n // runtimes rebuild the messages array on every adapter update, so this\n // fast-path rarely triggers there; it's primarily for the React-hook\n // shim where state references are stable.\n if (\n this._lastSnapshot &&\n this._lastSnapshot.messages === snapshot.messages &&\n this._lastSnapshot.isRunning === snapshot.isRunning &&\n this._lastSnapshot.isLoading === snapshot.isLoading\n ) {\n return;\n }\n\n // While the host is still loading initial state, treat every snapshot\n // as historical: tool calls are recorded so the next live snapshot can\n // diff against them, but `streamCall` / `execute` do not fire.\n const restoreFromLoading = snapshot.isLoading === true;\n if (restoreFromLoading) {\n this._pendingRestore = true;\n }\n\n // E.4 / AF3 — only mark `_lastSnapshot`/`_isRunning` as observed after\n // processing succeeds. If `_processMessages` throws, the next snapshot\n // (even if identical) gets re-processed against the recovered state.\n const previousIsRunning = this._isRunning;\n this._isRunning = snapshot.isRunning;\n try {\n this._processMessages(snapshot.messages);\n } catch (err) {\n this._isRunning = previousIsRunning;\n throw err;\n }\n this._lastSnapshot = snapshot;\n this._pendingRestore = false;\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] setState failed; snapshot dropped\",\n err,\n );\n }\n }\n\n /**\n * Reset the tracker so the next observed snapshot is treated as historical.\n * Clears entries and aborts any in-flight executions. Used by callers like\n * `importExternalState` to mark a freshly loaded state as restored.\n */\n public reset(): void {\n try {\n this._pendingRestore = true;\n this._entries.clear();\n this._discardedToolCallIds.clear();\n this._lastSnapshot = null;\n void this.abort();\n // Statuses are cleared synchronously: discarded executions may never\n // settle (aborting hands the signal to the tool, it does not force\n // settlement), and a late settlement of one sibling must not republish\n // the others. `_deleteStatus` no-ops for cleared ids, so post-reset\n // settlements stay silent.\n if (this._statuses.size > 0) {\n this._statuses = new Map();\n this._invokeOnStatusesChange();\n }\n } catch (err) {\n console.error(\"[ToolInvocationTracker] reset failed\", err);\n }\n }\n\n /**\n * Abort any in-flight `execute()` invocations. Resolves once all of them\n * have settled (or immediately if none are running).\n *\n * `discardPending` additionally kills the calls that never reached the\n * executor, for a caller ending the turn rather than interrupting it. The\n * signal cannot reach those: they are waiting on the run to settle (A.10),\n * and the settled snapshot arrives after this installs a fresh controller.\n */\n public abort(options?: { discardPending?: boolean }): Promise<void> {\n try {\n this._humanInput.forEach(({ reject }) => {\n try {\n reject(new Error(\"Tool execution aborted\"));\n } catch {\n // host rejection handler threw — already in the abort path,\n // swallow so we continue cleaning up.\n }\n });\n this._humanInput.clear();\n\n if (options?.discardPending) {\n for (const [toolCallId, entry] of this._entries) {\n if (!entry.controller) continue;\n if (entry.argsComplete || entry.hasResult) continue;\n this._discardedToolCallIds.add(toolCallId);\n entry.skipExecute = true;\n }\n }\n\n this._ac.abort();\n this._ac = new AbortController();\n\n if (this._executing.size === 0) {\n return Promise.resolve();\n }\n const executionIds = new Set(this._executing);\n return new Promise<void>((resolve) => {\n this._settledResolvers.push({ executionIds, resolve });\n });\n } catch (err) {\n console.error(\"[ToolInvocationTracker] abort failed\", err);\n return Promise.resolve();\n }\n }\n\n /**\n * Resolve a pending human-input request for the given tool call. Returns\n * `true` if a pending request was resumed, `false` if the tracker has no\n * outstanding request for that id (the caller should fall back to its own\n * dispatch path).\n */\n public resume(toolCallId: string, payload: unknown): boolean {\n try {\n const handlers = this._humanInput.get(toolCallId);\n if (!handlers) return false;\n this._humanInput.delete(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n handlers.resolve(payload);\n return true;\n } catch (err) {\n console.error(\"[ToolInvocationTracker] resume failed\", err);\n return false;\n }\n }\n\n /**\n * Returns the current tool execution status map. The returned `Map` is\n * the tracker's internal store — do not mutate it. Treat the reference\n * as a snapshot that may be replaced wholesale on the next status\n * transition.\n */\n public getStatuses(): ReadonlyMap<string, ToolExecutionStatus> {\n return this._statuses;\n }\n\n // ───────────────────── internal: tool wrapping ─────────────────────\n\n private _getWrappedTools(): Record<string, Tool> | undefined {\n const tools = this._getTools();\n if (!tools) return undefined;\n\n return Object.fromEntries(\n Object.entries(tools).map(([name, tool]) => {\n const execute = tool.execute;\n const streamCall = tool.streamCall;\n if (execute === undefined && streamCall === undefined)\n return [name, tool];\n\n const wrappedTool = {\n ...tool,\n ...(execute !== undefined && {\n execute: (...[args, context]: Parameters<typeof execute>) => {\n const executionId = getToolExecutionId(context);\n const entry = this._captureExecution(\n context.toolCallId,\n executionId,\n );\n if (!entry || entry.skipExecute) {\n return new Promise(() => {}) as never;\n }\n return execute(args, context);\n },\n }),\n ...(streamCall !== undefined && {\n streamCall: (\n ...[reader, context]: Parameters<typeof streamCall>\n ) => {\n const executionId = getToolExecutionId(context);\n const entry = this._captureExecution(\n context.toolCallId,\n executionId,\n );\n if (!entry) return;\n return streamCall(reader, context);\n },\n }),\n } as Tool;\n return [name, wrappedTool];\n }),\n ) as Record<string, Tool>;\n }\n\n private _captureExecution(\n toolCallId: string,\n executionId: symbol | undefined,\n ): ToolCallEntry | undefined {\n if (executionId === undefined) return undefined;\n const entry = this._entries.get(toolCallId);\n if (!entry?.controller) return undefined;\n if (entry.executionId === undefined) entry.executionId = executionId;\n return entry.executionId === executionId ? entry : undefined;\n }\n\n // ──────────────── internal: execution lifecycle callbacks ────────────────\n\n private _onHumanInput(\n toolCallId: string,\n payload: unknown,\n executionId?: symbol,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n // A discarded execution must not resurrect a status entry or park an\n // unanswerable request after its id has been reused.\n const entry = this._entries.get(toolCallId);\n if (!entry?.controller || entry.executionId !== executionId) {\n reject(new Error(\"Tool execution aborted\"));\n return;\n }\n const previous = this._humanInput.get(toolCallId);\n if (previous) {\n try {\n previous.reject(\n new Error(\"Human input request was superseded by a new request\"),\n );\n } catch {\n // host rejection handler threw; ignore and proceed\n }\n }\n this._humanInput.set(toolCallId, {\n executionId: executionId!,\n resolve,\n reject,\n });\n this._setStatus(toolCallId, {\n type: \"interrupt\",\n payload: { type: \"human\", payload },\n });\n });\n }\n\n private _onExecutionStart(\n toolCallId: string,\n executionId: symbol | undefined,\n ): void {\n if (!this._captureExecution(toolCallId, executionId)) return;\n const entry = this._entries.get(toolCallId)!;\n if (entry.skipExecute) return;\n\n this._executing.add(executionId!);\n // execute can park human() before onExecutionStart; preserve this execution's interrupt.\n if (this._humanInput.get(toolCallId)?.executionId === executionId) return;\n this._setStatus(toolCallId, { type: \"executing\" });\n }\n\n private _onExecutionEnd(\n toolCallId: string,\n executionId: symbol | undefined,\n ): void {\n if (executionId === undefined || !this._executing.delete(executionId))\n return;\n\n const entry = this._entries.get(toolCallId);\n if (entry?.executionId === executionId) this._deleteStatus(toolCallId);\n\n const pending: SettledResolver[] = [];\n this._settledResolvers.forEach(({ executionIds, resolve }) => {\n if ([...executionIds].some((id) => this._executing.has(id))) {\n pending.push({ executionIds, resolve });\n return;\n }\n try {\n resolve();\n } catch {\n // ignore — settled-resolver consumer threw\n }\n });\n this._settledResolvers.length = 0;\n this._settledResolvers.push(...pending);\n }\n\n private _handleResultChunk(chunk: {\n type: \"result\";\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue;\n modelContent?: readonly ToolModelContentPart[];\n meta: { toolCallId: string; toolName: string };\n }): void {\n const toolCallId = chunk.meta.toolCallId;\n const executionId = getToolExecutionId(chunk);\n const entry = this._entries.get(toolCallId);\n\n if (!entry || entry.executionId !== executionId) return;\n\n // The host already set the result (via the live snapshot's\n // `setResponse` path). Suppress the executor's redundant emit.\n if (entry?.hasResult) return;\n if (entry.skipExecute) return;\n\n this._invokeOnResult({\n type: \"add-tool-result\",\n toolCallId,\n toolName: chunk.meta.toolName,\n result: chunk.result,\n isError: chunk.isError,\n ...(chunk.artifact !== undefined && { artifact: chunk.artifact }),\n ...(chunk.modelContent !== undefined && {\n modelContent: chunk.modelContent,\n }),\n });\n }\n\n // ──────────────── internal: callback invocation (AF1/AF2) ────────────────\n\n private _invokeOnResult(command: AddToolResultCommand): void {\n try {\n this._callbacks.onResult(command);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onResult callback threw; result dropped\",\n err,\n );\n }\n }\n\n private _invokeOnStatusesChange(): void {\n try {\n this._callbacks.onStatusesChange(this._statuses);\n } catch (err) {\n console.error(\n \"[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated\",\n err,\n );\n }\n }\n\n // ──────────────── internal: status map mutations ────────────────\n\n private _setStatus(toolCallId: string, status: ToolExecutionStatus): void {\n const next = new Map(this._statuses);\n next.set(toolCallId, status);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n private _deleteStatus(toolCallId: string): void {\n if (!this._statuses.has(toolCallId)) return;\n const next = new Map(this._statuses);\n next.delete(toolCallId);\n this._statuses = next;\n this._invokeOnStatusesChange();\n }\n\n // ──────────────── internal: snapshot processing ────────────────\n\n private _warnProviderOwnedSkip(toolName: string, toolCallId: string): void {\n if (process.env.NODE_ENV === \"production\") return;\n if (this._getTools()?.[toolName]?.execute === undefined) return;\n console.warn(\n \"[ToolInvocationTracker] the runtime reports this tool call as provider-owned, so the registered execute is skipped; the provider has to hand the call to the client for it to run (see EDGE_CASES.md A.9)\",\n { toolCallId, toolName },\n );\n }\n\n /**\n * Closing the args stream hands the call to the client executor, so it may\n * only happen once the provider can no longer speak about that call. The run\n * ending is the only universal signal for that; an adapter that reports the\n * call as client-owned has said it earlier, per call.\n */\n private _shouldCloseArgsStream({\n argsText,\n hasResult,\n clientOwned,\n }: {\n argsText: string;\n hasResult: boolean;\n clientOwned: boolean;\n }): boolean {\n if (hasResult) return true;\n if (!isArgsTextComplete(argsText)) return false;\n return clientOwned || !this._isRunning;\n }\n\n private _startActiveEntry(\n toolCallId: string,\n toolName: string,\n skipExecute: boolean,\n clientOwned: boolean,\n ): ToolCallEntry {\n const toolCallController = this._controller.addToolCallPart({\n toolName,\n toolCallId,\n });\n const entry: ToolCallEntry = {\n toolName,\n controller: toolCallController,\n argsText: \"\",\n hasResult: false,\n skipExecute,\n argsComplete: false,\n clientOwned,\n };\n this._entries.set(toolCallId, entry);\n return entry;\n }\n\n /**\n * Demote every active entry back to the restored phase. Used by the\n * pipeline-restart path so that, after a fresh pipeline is built, the\n * next observed snapshot does not re-fire `streamCall` for tool calls\n * that already fired pre-death. Args / hasResult tracking is preserved\n * so signature comparisons still work.\n */\n private _demoteEntriesToRestored(): void {\n for (const [toolCallId, entry] of this._entries) {\n if (!entry.controller) continue;\n if (!entry.argsComplete && !entry.hasResult) {\n // The call never reached the executor. A restored entry is promoted\n // only when its signature changes, and a call waiting on the run to\n // settle already holds its final args, so demoting it would strand it\n // unexecuted. Dropping it lets the next snapshot start it over; a call\n // whose turn was discarded is held by `_discardedToolCallIds`, not by\n // the entry, so starting over does not revive it.\n this._entries.delete(toolCallId);\n continue;\n }\n this._entries.set(toolCallId, {\n toolName: entry.toolName,\n argsText: entry.argsText,\n hasResult: entry.hasResult,\n });\n }\n }\n\n private _processArgsText(\n entry: ToolCallEntry,\n content: {\n toolCallId: string;\n toolName: string;\n argsText: string;\n result?: unknown;\n },\n ): void {\n if (!entry.controller) return;\n const hasResult = content.result !== undefined;\n\n if (content.argsText !== entry.argsText) {\n let shouldWriteArgsText = true;\n\n if (entry.argsComplete) {\n if (isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {\n // A.3 — key reorder. Track new text, no re-fire needed.\n entry.argsText = content.argsText;\n shouldWriteArgsText = false;\n } else {\n // A.4 — args changed after first completion. Under the\n // \"exactly once per toolCallId\" contract we do not restart the\n // stream. The host's existing `streamCall` keeps its original\n // args view; the snapshot's new text is recorded for diffing\n // but not surfaced. Events API in a follow-up will expose this\n // to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText changed after first completion; not re-firing streamCall (see EDGE_CASES.md A.4)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n } else if (!content.argsText.startsWith(entry.argsText)) {\n if (\n isArgsTextComplete(entry.argsText) &&\n isArgsTextComplete(content.argsText) &&\n isEquivalentCompleteArgsText(entry.argsText, content.argsText)\n ) {\n const shouldClose = this._shouldCloseArgsStream({\n argsText: content.argsText,\n hasResult,\n clientOwned: entry.clientOwned,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n shouldWriteArgsText = false;\n } else {\n // A.2 — args regressed mid-stream. Under the \"exactly once\"\n // contract we do not restart. The controller keeps whatever\n // prefix we already streamed; subsequent prefix-respecting\n // updates can still flow against it. Snapshots that never\n // re-converge to a prefix will leave the controller's args\n // view stale relative to the snapshot. Events API in a\n // follow-up will expose this to consumers that opt in.\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[ToolInvocationTracker] argsText regressed mid-stream; not restarting (see EDGE_CASES.md A.2)\",\n {\n previous: entry.argsText,\n next: content.argsText,\n toolCallId: content.toolCallId,\n },\n );\n }\n shouldWriteArgsText = false;\n }\n }\n\n if (shouldWriteArgsText && entry.controller) {\n const delta = content.argsText.slice(entry.argsText.length);\n entry.controller.argsText.append(delta);\n const shouldClose = this._shouldCloseArgsStream({\n argsText: content.argsText,\n hasResult,\n clientOwned: entry.clientOwned,\n });\n if (shouldClose) entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = shouldClose;\n }\n }\n\n if (!entry.argsComplete && entry.controller) {\n // ToolExecutionStream parses the streamed prefix on close, so the close\n // gates on the streamed content; a divergent snapshot (A.2) can be\n // complete while the controller still holds an incomplete stale prefix.\n const shouldClose = this._shouldCloseArgsStream({\n argsText: entry.argsText,\n hasResult,\n clientOwned: entry.clientOwned,\n });\n if (shouldClose) {\n entry.controller.argsText.close();\n entry.argsComplete = true;\n }\n }\n }\n\n private _processMessages(messages: readonly ThreadMessage[]): void {\n const isRestore = this._pendingRestore;\n\n for (const { part: content } of walkToolCallTree(messages)) {\n const existing = this._entries.get(content.toolCallId);\n\n if (isRestore) {\n // Don't overwrite an already-active entry (e.g. live tool-call\n // observed before this restore snapshot landed). Restore can\n // only seed entries the runtime has never seen.\n if (!existing?.controller) {\n this._entries.set(content.toolCallId, {\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult: content.result !== undefined,\n });\n }\n continue;\n }\n\n // Live snapshot.\n let entry = existing;\n\n // A discarded id is remembered only until the call is answered, which\n // bounds the set to the open calls of a discarded turn.\n if (content.result !== undefined)\n this._discardedToolCallIds.delete(content.toolCallId);\n\n if (entry && !entry.controller) {\n // A restored entry with a result remains historical.\n if (entry.hasResult) continue;\n const argsChanged =\n content.argsText !== entry.argsText &&\n !(\n isArgsTextComplete(entry.argsText) &&\n isArgsTextComplete(content.argsText) &&\n isEquivalentCompleteArgsText(entry.argsText, content.argsText)\n );\n if (!argsChanged && content.result === undefined) continue;\n this._entries.delete(content.toolCallId);\n entry = undefined;\n }\n\n if (!entry) {\n const ownership = this._isClientToolCall?.(content);\n const providerOwned =\n content.result === undefined && ownership === false;\n if (providerOwned)\n this._warnProviderOwnedSkip(content.toolName, content.toolCallId);\n entry = this._startActiveEntry(\n content.toolCallId,\n content.toolName,\n content.result !== undefined ||\n providerOwned ||\n this._discardedToolCallIds.has(content.toolCallId),\n ownership === true,\n );\n }\n\n if (content.approval !== undefined) entry.skipExecute = true;\n\n this._processArgsText(entry, content);\n\n if (content.result !== undefined && !entry.hasResult) {\n // `entry` is in active phase from this point — either just\n // created by `_startActiveEntry`, or pre-existing with a live\n // controller. Narrow once instead of asserting at every use.\n const { controller: activeController } = entry;\n if (!activeController) continue;\n entry.hasResult = true;\n entry.argsComplete = true;\n activeController.setResponse(\n new ToolResponse({\n result: content.result as ReadonlyJSONValue,\n artifact: content.artifact as ReadonlyJSONValue | undefined,\n isError: content.isError,\n ...(content.modelContent !== undefined\n ? { modelContent: content.modelContent }\n : {}),\n }),\n );\n activeController.close();\n }\n }\n }\n}\n\nexport namespace ToolInvocationTracker {\n export type ExecutionStatus = ToolExecutionStatus;\n\n export type Snapshot = {\n readonly messages: readonly ThreadMessage[];\n /** Whether the producing runtime is currently streaming new output. */\n readonly isRunning: boolean;\n /**\n * Whether the producing runtime is still loading historical state.\n * When `true`, every snapshot is treated as historical (no `streamCall` /\n * `execute` fires). When `false`, processing resumes as live.\n */\n readonly isLoading?: boolean;\n };\n\n export type Callbacks = {\n /**\n * Invoked when a client-side `execute()` returns a result and the runtime\n * needs to feed it back into the conversation.\n */\n onResult: (command: AddToolResultCommand) => void;\n /**\n * Invoked whenever the per-tool-call status map changes (executing /\n * interrupt / cleared). The callback receives a fresh map; mutating the\n * argument is not supported.\n */\n onStatusesChange: (\n statuses: ReadonlyMap<string, ToolExecutionStatus>,\n ) => void;\n };\n}\n"],"mappings":";;;;;AAmBA,MAAMgB,oBAAoBC,OAAOC,IAAI,oCAAoC;AA+CzE,MAAMuB,sBAAsBX,aAAqB;CAC/C,IAAI;EACFY,KAAKC,MAAMb,QAAQ;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAMc,iBAAiBd,aAAqB;CAC1C,IAAI;EACF,OAAOY,KAAKC,MAAMb,QAAQ;CAC5B,QAAQ;EACN;CACF;AACF;AAEA,MAAMgB,gCAAgCC,UAAkBC,SAAiB;CACvE,MAAMC,gBAAgBL,cAAcG,QAAQ;CAC5C,MAAMG,YAA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AW;IAClD,KAAKgB,SAASwE,OAAOsC,QAAQpJ,UAAU;IACvCwG,QAAQlF,KAAAA;GACV;GAEA,IAAI,CAACkF,OAAO;IACV,MAAMwD,YAAY,KAAK5H,oBAAoBgH,OAAO;IAClD,MAAMa,gBACJb,QAAQlJ,WAAWoB,KAAAA,KAAa0I,cAAc;IAChD,IAAIC,eACF,KAAKpB,uBAAuBO,QAAQnJ,UAAUmJ,QAAQpJ,UAAU;IAClEwG,QAAQ,KAAKwC,kBACXI,QAAQpJ,YACRoJ,QAAQnJ,UACRmJ,QAAQlJ,WAAWoB,KAAAA,KACjB2I,iBACA,KAAKpH,sBAAsBwF,IAAIe,QAAQpJ,UAAU,GACnDgK,cAAc,IAChB;GACF;GAEA,IAAIZ,QAAQc,aAAa5I,KAAAA,GAAWkF,MAAM9F,cAAc;GAExD,KAAKyI,iBAAiB3C,OAAO4C,OAAO;GAEpC,IAAIA,QAAQlJ,WAAWoB,KAAAA,KAAa,CAACkF,MAAMhG,WAAW;IAIpD,MAAM,EAAEG,YAAYwJ,qBAAqB3D;IACzC,IAAI,CAAC2D,kBAAkB;IACvB3D,MAAMhG,YAAY;IAClBgG,MAAM5F,eAAe;IACrBuJ,iBAAiBC,YACf,IAAItL,aAAa;KACfoB,QAAQkJ,QAAQlJ;KAChBE,UAAUgJ,QAAQhJ;KAClBD,SAASiJ,QAAQjJ;KACjB,GAAIiJ,QAAQ/I,iBAAiBiB,KAAAA,IACzB,EAAEjB,cAAc+I,QAAQ/I,aAAa,IACrC,CAAC;IACP,CAAC,CACH;IACA8J,iBAAiBX,MAAM;GACzB;EACF;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-thread.d.ts","names":[],"sources":["../../../src/store/clients/external-thread.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"external-thread.d.ts","names":[],"sources":["../../../src/store/clients/external-thread.ts"],"mappings":";;;;;;;;;;KAkEY,wBAAwB;EAClC;;KAgBU;EACV,mBAAmB;EACnB;EACA;EACA,QAAQ;EACR;;;;;;;EAOA;;;;;EAKA,SAAS,SAAS;EAClB,UAAU,SAAS;EACnB,YAAY;EACZ;EACA;EACA;;;;;;;EAOA,yBAAyB;EACzB,oBAAoB,SAAS;;EAE7B,qBAAqB,SAAS;EAC9B,wBAAwB;EACxB,oBAAoB;EACpB,kBAAkB;EAClB,gBAAgB;;EAEhB,QAAQ;;EAER,WAAW;;EAEX,2BACE,SAAS,wCACC;;cAklCD,4CAAc,SAAA,yBAAA"}
|