@assistant-ui/core 0.2.21 → 0.2.22
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/attachment.d.ts.map +1 -1
- package/dist/adapters/speech.d.ts.map +1 -1
- package/dist/adapters/speech.js +9 -2
- package/dist/adapters/speech.js.map +1 -1
- package/dist/adapters/voice.d.ts.map +1 -1
- package/dist/adapters/voice.js +13 -5
- package/dist/adapters/voice.js.map +1 -1
- package/dist/internal.d.ts +3 -1
- package/dist/internal.js +3 -1
- package/dist/model-context/frame/host.d.ts +1 -0
- package/dist/model-context/frame/host.d.ts.map +1 -1
- package/dist/model-context/frame/host.js +5 -0
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/frame/provider.d.ts.map +1 -1
- package/dist/model-context/frame/provider.js +1 -0
- package/dist/model-context/frame/provider.js.map +1 -1
- package/dist/model-context/interactable-composer-metadata.js.map +1 -1
- package/dist/react/AssistantProvider.js.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js +77 -50
- package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/Tools.d.ts.map +1 -1
- package/dist/react/client/interactable-model-context.d.ts.map +1 -1
- package/dist/react/model-context/useInteractable.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarCopy.js +13 -13
- package/dist/react/primitive-hooks/useActionBarCopy.js.map +1 -1
- package/dist/react/primitive-hooks/useComposerAddAttachment.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useComposerSend.d.ts.map +1 -1
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.d.ts.map +1 -1
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js +1 -1
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js.map +1 -1
- package/dist/react/primitives/composer/ComposerAttachments.js.map +1 -1
- package/dist/react/primitives/composer/ComposerQueue.d.ts.map +1 -1
- package/dist/react/primitives/composer/ComposerQueue.js.map +1 -1
- package/dist/react/primitives/generativeUI/GenerativeUI.d.ts.map +1 -1
- package/dist/react/primitives/message/MessageAttachments.js.map +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
- package/dist/react/primitives/message/MessageParts.d.ts +2 -1
- package/dist/react/primitives/message/MessageParts.d.ts.map +1 -1
- package/dist/react/primitives/message/MessageParts.js +46 -36
- package/dist/react/primitives/message/MessageParts.js.map +1 -1
- package/dist/react/primitives/part/PartMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadSuggestions.js.map +1 -1
- package/dist/react/primitives/threadList/ThreadListItems.js.map +1 -1
- package/dist/react/providers/ChainOfThoughtPartByIndexProvider.d.ts.map +1 -1
- package/dist/react/providers/ChainOfThoughtPartByIndexProvider.js +18 -30
- package/dist/react/providers/ChainOfThoughtPartByIndexProvider.js.map +1 -1
- package/dist/react/providers/PartByIndexProvider.d.ts.map +1 -1
- package/dist/react/providers/PartByIndexProvider.js +18 -30
- package/dist/react/providers/PartByIndexProvider.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +1 -0
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +9 -2
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +49 -8
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js +2 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js.map +1 -1
- package/dist/react/runtimes/createMessageConverter.d.ts.map +1 -1
- package/dist/react/runtimes/external-message-converter.js +1 -1
- package/dist/react/runtimes/external-message-converter.js.map +1 -1
- package/dist/react/runtimes/useLocalRuntime.d.ts +1 -0
- package/dist/react/runtimes/useLocalRuntime.d.ts.map +1 -1
- package/dist/react/runtimes/useLocalRuntime.js +9 -1
- package/dist/react/runtimes/useLocalRuntime.js.map +1 -1
- package/dist/runtime/api/assistant-runtime.d.ts.map +1 -1
- package/dist/runtime/api/attachment-runtime.d.ts.map +1 -1
- package/dist/runtime/api/composer-runtime.d.ts.map +1 -1
- package/dist/runtime/api/message-part-runtime.d.ts.map +1 -1
- package/dist/runtime/api/message-runtime.d.ts.map +1 -1
- package/dist/runtime/api/message-runtime.js +4 -4
- package/dist/runtime/api/message-runtime.js.map +1 -1
- package/dist/runtime/api/thread-list-item-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-item-runtime.js +2 -1
- package/dist/runtime/api/thread-list-item-runtime.js.map +1 -1
- package/dist/runtime/api/thread-list-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts +4 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +41 -14
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js +2 -1
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/base/default-edit-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/default-edit-composer-runtime-core.js +4 -2
- package/dist/runtime/base/default-edit-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/default-thread-composer-runtime-core.js +2 -2
- package/dist/runtime/base/default-thread-composer-runtime-core.js.map +1 -1
- package/dist/runtime/utils/message-repository.d.ts.map +1 -1
- package/dist/runtime/utils/thread-message-like.js +4 -1
- package/dist/runtime/utils/thread-message-like.js.map +1 -1
- package/dist/runtimes/external-store/external-store-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.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.map +1 -1
- package/dist/runtimes/local/local-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-list-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +5 -2
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/optimistic-state.d.ts +4 -4
- package/dist/runtimes/remote-thread-list/optimistic-state.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/optimistic-state.js +22 -9
- package/dist/runtimes/remote-thread-list/optimistic-state.js.map +1 -1
- package/dist/runtimes/remote-thread-list/types.d.ts +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +1 -2
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
- package/dist/store/clients/chain-of-thought-client.d.ts.map +1 -1
- package/dist/store/clients/no-op-composer-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/attachment-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/message-part-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/message-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
- package/dist/subscribable/subscribable.d.ts +1 -1
- package/dist/subscribable/subscribable.d.ts.map +1 -1
- package/dist/subscribable/subscribable.js +11 -3
- package/dist/subscribable/subscribable.js.map +1 -1
- package/dist/tests/remote-thread-list-test-helpers.d.ts +2 -1
- package/dist/tests/remote-thread-list-test-helpers.d.ts.map +1 -1
- package/dist/tests/remote-thread-list-test-helpers.js +5 -2
- package/dist/tests/remote-thread-list-test-helpers.js.map +1 -1
- package/dist/types/attachment.d.ts +2 -1
- package/dist/types/attachment.d.ts.map +1 -1
- package/dist/types/attachment.js +6 -0
- package/dist/types/attachment.js.map +1 -0
- package/dist/types/message.d.ts +1 -0
- package/dist/types/message.d.ts.map +1 -1
- package/dist/types/message.js.map +1 -1
- package/dist/utils/data-url.d.ts +9 -0
- package/dist/utils/data-url.d.ts.map +1 -0
- package/dist/utils/data-url.js +14 -0
- package/dist/utils/data-url.js.map +1 -0
- package/dist/utils/notify-event-listeners.d.ts +6 -0
- package/dist/utils/notify-event-listeners.d.ts.map +1 -0
- package/dist/utils/notify-event-listeners.js +16 -0
- package/dist/utils/notify-event-listeners.js.map +1 -0
- package/package.json +10 -9
- package/src/adapters/speech.test.ts +88 -0
- package/src/adapters/speech.ts +17 -2
- package/src/adapters/voice.test.ts +130 -0
- package/src/adapters/voice.ts +26 -6
- package/src/internal.ts +5 -0
- package/src/model-context/frame/host.test.ts +100 -0
- package/src/model-context/frame/host.ts +10 -0
- package/src/model-context/frame/provider.test.ts +83 -0
- package/src/model-context/frame/provider.ts +1 -0
- package/src/react/adapters/LocalStorageThreadListAdapter.test.ts +82 -0
- package/src/react/adapters/LocalStorageThreadListAdapter.tsx +94 -54
- package/src/react/primitive-hooks/useActionBarCopy.test.ts +79 -0
- package/src/react/primitive-hooks/useActionBarCopy.ts +4 -3
- package/src/react/primitives/chainOfThought/ChainOfThoughtParts.tsx +1 -3
- package/src/react/primitives/message/MessageParts.tsx +48 -35
- package/src/react/providers/ChainOfThoughtPartByIndexProvider.tsx +19 -2
- package/src/react/providers/PartByIndexProvider.tsx +16 -2
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.test.tsx +18 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +1 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +48 -7
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +69 -0
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +1 -1
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.test.ts +16 -0
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.ts +2 -1
- package/src/react/runtimes/external-message-converter.test.tsx +21 -0
- package/src/react/runtimes/external-message-converter.ts +1 -1
- package/src/react/runtimes/useLocalRuntime.test.tsx +56 -0
- package/src/react/runtimes/useLocalRuntime.ts +13 -1
- package/src/runtime/api/message-runtime.test.ts +81 -0
- package/src/runtime/api/message-runtime.ts +4 -6
- package/src/runtime/api/thread-list-item-runtime.ts +6 -1
- package/src/runtime/base/base-composer-runtime-core.ts +77 -31
- package/src/runtime/base/base-thread-runtime-core.ts +2 -1
- package/src/runtime/base/default-edit-composer-runtime-core.ts +4 -2
- package/src/runtime/base/default-thread-composer-runtime-core.ts +2 -2
- package/src/runtime/utils/thread-message-like.ts +1 -0
- package/src/runtimes/local/local-thread-runtime-core.test.ts +150 -1
- package/src/runtimes/local/local-thread-runtime-core.ts +4 -2
- package/src/runtimes/remote-thread-list/optimistic-state.test.ts +63 -0
- package/src/runtimes/remote-thread-list/optimistic-state.ts +49 -17
- package/src/runtimes/remote-thread-list/types.ts +1 -1
- package/src/runtimes/tool-invocations/EDGE_CASES.md +13 -19
- package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +127 -6
- package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +4 -2
- package/src/subscribable/subscribable.test.ts +58 -0
- package/src/subscribable/subscribable.ts +13 -3
- package/src/tests/OptimisticState-list-race.test.ts +33 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-switchToThread-order.test.ts +223 -0
- package/src/tests/base-composer-runtime-core-addAttachment.test.ts +44 -0
- package/src/tests/base-composer-runtime-core-send.test.ts +433 -5
- package/src/tests/default-edit-composer-runtime-core.test.ts +43 -5
- package/src/tests/event-subscription-listener-errors.test.ts +205 -0
- package/src/tests/remote-thread-list-test-helpers.ts +14 -7
- package/src/tests/thread-message-like.test.ts +57 -0
- package/src/types/attachment.ts +5 -0
- package/src/types/message.ts +1 -0
- package/src/utils/data-url.test.ts +50 -0
- package/src/utils/data-url.ts +9 -0
- package/src/utils/notify-event-listeners.ts +30 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;cA6Ca,+BACH,iCACG;WAEK;;;;;;;;;;;;;;;UAgBR;UAEA;UACA;WAEQ;WACA;UAER;MACG;UAIH;UACA;MACG,wBAAwB;MAIxB;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"local-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;cA6Ca,+BACH,iCACG;WAEK;;;;;;;;;;;;;;;UAgBR;UAEA;UACA;WAEQ;WACA;UAER;MACG;UAIH;UACA;MACG,wBAAwB;MAIxB;;;;;;;;;;EAKT,YAAA,iBAAiB,sBACjB,SAAS;UAMH;UAEA;UAEA;EAED,0BAA0B;UAIzB;EAED,mCACL,kBAAkB;MAKT;EAIJ,sBAAsB,SAAS;UAuE9B;EACD,mBAAe;EAuCT,OAAO,SAAS,gBAAgB;EAWtC,0BAA0B;EAM1B,eAAe;EAIf,gBAAgB;UAIT;EAgCD,cAAc,oBAAoB;EAmBxC,YAAY,WAAW,eAAe,kBAAkB;EAMxD;EAIA;EAIM,WACT,UAAU,aAAa,gBACzB,cAAc,0BACb;UAuBW;UA2DA;EAiLP;EASA;EASA,gBACL,WACA,YACA,QACA,SACA,YACC;EA2CI,eAAe,UAAU;EAMzB,wBACL,YACA,UACA,UACA,UACC"}
|
|
@@ -284,7 +284,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
284
284
|
status: m.status ?? message.status,
|
|
285
285
|
...m.metadata ? { metadata: {
|
|
286
286
|
...message.metadata,
|
|
287
|
-
...m.metadata.unstable_state ? { unstable_state: m.metadata.unstable_state } : void 0,
|
|
287
|
+
...m.metadata.unstable_state !== void 0 ? { unstable_state: m.metadata.unstable_state } : void 0,
|
|
288
288
|
...annotations ? { unstable_annotations: annotations } : void 0,
|
|
289
289
|
...data ? { unstable_data: data } : void 0,
|
|
290
290
|
...steps ? { steps } : void 0,
|
|
@@ -339,7 +339,10 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
339
339
|
updateMessage(r);
|
|
340
340
|
}
|
|
341
341
|
else updateMessage(await promiseOrGenerator);
|
|
342
|
-
if (message.status.type === "running") updateMessage({ status: {
|
|
342
|
+
if (message.status.type === "running") updateMessage({ status: abortSignal.aborted ? {
|
|
343
|
+
type: "incomplete",
|
|
344
|
+
reason: "cancelled"
|
|
345
|
+
} : {
|
|
343
346
|
type: "complete",
|
|
344
347
|
reason: "unknown"
|
|
345
348
|
} });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","adapters","_options","contextProvider","options","__internal_setOptions","_lastRunConfig","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","Promise","__internal_setGetInitializePromise","getPromise","extras","undefined","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","history","canQueue","unstable_enableMessageQueue","run","_runAppend","finally","notifyIdle","catch","subscribe","_notifySubscribers","adapter","clear","_loadPromise","__internal_load","promise","load","resolve","then","repo","repository","import","messages","length","ensureInitialized","resume","bind","unstable_resume","startRun","parentId","headId","sourceId","runConfig","append","isTail","at","id","willRun","role","enqueue","steer","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","initPromise","newMessage","type","reason","addOrUpdateMessage","resetHead","deleteMessage","messageId","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","runCallback","status","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","data","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","aborted","e","error","cancelRun","addToolResult","toolCallId","result","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { 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 } from \"../../types/message\";\nimport { toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n void this._runAppend(message)\n .finally(() => {\n this._queueRunInFlight = false;\n this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue.adapter.clear(\"cancel-run\");\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n this._queue.adapter.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n if (this._queue && !isTail) this._queue.adapter.clear(\"edit\");\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string): void {\n this._queue?.adapter.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private async _runAppend(message: AppendMessage): Promise<void> {\n this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // queue-driven runs release from the driver settle handler; a direct\n // run (regenerate, resume) releases here\n if (!this._queueRunInFlight) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\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 runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n }\n\n try {\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = this.abortController.signal;\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n 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 this.abortController = null;\n\n if (\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\"\n ) {\n await this._options.adapters.history?.append({\n parentId,\n message: message,\n runConfig: this._lastRunConfig,\n });\n }\n }\n return message;\n }\n\n public detach() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n 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) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n}\n"],"mappings":";;;;;;;;;AAmCA,IAAMwB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUhB,sBAEV;CACE,eAA+B;EAC7BkB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAE5B,aAA6B;CAC7B,iBAAiC;CAEjC,aAAqB;CACrB,IAAWQ,YAAY;EACrB,OAAO,KAAKD;CACd;CAEA,eAAoD,CAAA;CACpD,yBAAyD;CACzD,IAAWI,cAA2C;EACpD,OAAO,KAAKF;CACd;CAEA,IAAWG,WAAW;EACpB,OAAO,KAAKC,SAASD;CACvB;CAEA5B,YACE8B,iBACAC,SACA;EACA,MAAMD,eAAe;EACrB,KAAKE,sBAAsBD,OAAO;CACpC;CAEA;CAEA,iBAAoC,CAAC;CAErC;CAEA,0BAAiCK,aAAuC;EACtE,KAAKF,eAAeE;CACtB;CAEA;CAEA,mCACEI,YACA;EACA,KAAKH,wBAAwBG;CAC/B;CAEA,IAAWC,SAAS,CAEpB;CAEA,sBAA6BV,SAAkC;EAC7D,IAAI,KAAKF,aAAaE,SAAS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AOD,SAASJ,aAAa9I,KAAAA,GAC/B,MAAM,IAAI7C,MAAM,sDAAsD;EAExE,MAAMmM,iBAAiBH,OAAOD;EAC9B,MAAMV,aAAajL,QAAQkH,QAAQgE,KAAKC,MAAM;GAC5C,IAAIA,MAAMS,QAAQ,OAAOT;GACzB,MAAMQ,WAAW;IACf,GAAGI;IACHR;IACA,GAAIC,YAAY,QAAQ,EAAEA,SAAS;IACnC,GAAItF,UAAU,QAAQ,EAAEA,OAAO;GACjC;GACA,IAAIqF,UAAU,OAAO;IAAE,GAAGJ;IAAGQ;GAAS;GACtC,OAAO;IACL,GAAGR;IACHQ;IACAjB,QAAQ,EAAEJ,OAAOpE,UAAU,uBAAuB;IAClDyE,SAAS;GACX;EACF,CAAC;EAED3K,UAAU;GAAE,GAAGA;GAASkH,SAAS+D;EAAW;EAC5C,MAAM,EAAEpG,aAAa,KAAKT,WAAW0G,WAAW9K,QAAQoF,EAAE;EAC1D,KAAKhB,WAAW+B,mBAAmBtB,UAAU7E,OAAO;EACpD,KAAK0D,mBAAmB;EAExB,IACE,KAAKU,WAAWU,WAAW9E,QAAQoF,MACnC7G,eAAeyB,SAAS,KAAK4B,SAASqG,uBAAuB,GAE7D,KAAKL,SAAS/C,UAAU7E,SAAS,KAAKgC,cAAc,CAAC,CAACwB,YAAY,CAAC,CAAC;CAExE;AACF"}
|
|
1
|
+
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","adapters","_options","contextProvider","options","__internal_setOptions","_lastRunConfig","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","Promise","__internal_setGetInitializePromise","getPromise","extras","undefined","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","history","canQueue","unstable_enableMessageQueue","run","_runAppend","finally","notifyIdle","catch","subscribe","_notifySubscribers","adapter","clear","_loadPromise","__internal_load","promise","load","resolve","then","repo","repository","import","messages","length","ensureInitialized","resume","bind","unstable_resume","startRun","parentId","headId","sourceId","runConfig","append","isTail","at","id","willRun","role","enqueue","steer","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","initPromise","newMessage","type","reason","addOrUpdateMessage","resetHead","deleteMessage","messageId","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","runCallback","status","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","data","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","aborted","e","error","cancelRun","addToolResult","toolCallId","result","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { 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 } from \"../../types/message\";\nimport { toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n void this._runAppend(message)\n .finally(() => {\n this._queueRunInFlight = false;\n this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue.adapter.clear(\"cancel-run\");\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n this._queue.adapter.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n if (this._queue && !isTail) this._queue.adapter.clear(\"edit\");\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string): void {\n this._queue?.adapter.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private async _runAppend(message: AppendMessage): Promise<void> {\n this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // queue-driven runs release from the driver settle handler; a direct\n // run (regenerate, resume) releases here\n if (!this._queueRunInFlight) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\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 runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n this.abortController = new AbortController();\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state !== 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 this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n // reached max tool steps\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n } else {\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n }\n\n try {\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = this.abortController.signal;\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: abortSignal.aborted\n ? { type: \"incomplete\", reason: \"cancelled\" }\n : { 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 this.abortController = null;\n\n if (\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\"\n ) {\n await this._options.adapters.history?.append({\n parentId,\n message: message,\n runConfig: this._lastRunConfig,\n });\n }\n }\n return message;\n }\n\n public detach() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n 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) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n }\n }\n}\n"],"mappings":";;;;;;;;;AAmCA,IAAMwB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUhB,sBAEV;CACE,eAA+B;EAC7BkB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAE5B,aAA6B;CAC7B,iBAAiC;CAEjC,aAAqB;CACrB,IAAWQ,YAAY;EACrB,OAAO,KAAKD;CACd;CAEA,eAAoD,CAAA;CACpD,yBAAyD;CACzD,IAAWI,cAA2C;EACpD,OAAO,KAAKF;CACd;CAEA,IAAWG,WAAW;EACpB,OAAO,KAAKC,SAASD;CACvB;CAEA5B,YACE8B,iBACAC,SACA;EACA,MAAMD,eAAe;EACrB,KAAKE,sBAAsBD,OAAO;CACpC;CAEA;CAEA,iBAAoC,CAAC;CAErC;CAEA,0BAAiCK,aAAuC;EACtE,KAAKF,eAAeE;CACtB;CAEA;CAEA,mCACEI,YACA;EACA,KAAKH,wBAAwBG;CAC/B;CAEA,IAAWC,SAAS,CAEpB;CAEA,sBAA6BV,SAAkC;EAC7D,IAAI,KAAKF,aAAaE,SAAS;EAE/B,KAAKF,WAAWE;EAEhB,IAAIY,aAAa;EAEjB,MAAMC,WAAWb,QAAQH,UAAUjB,WAAW+B,KAAAA;EAC9C,IAAI,KAAKvC,aAAaQ,WAAWi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,sDAAsD;EAExE,MAAMmM,iBAAiBH,OAAOD;EAC9B,MAAMV,aAAajL,QAAQkH,QAAQgE,KAAKC,MAAM;GAC5C,IAAIA,MAAMS,QAAQ,OAAOT;GACzB,MAAMQ,WAAW;IACf,GAAGI;IACHR;IACA,GAAIC,YAAY,QAAQ,EAAEA,SAAS;IACnC,GAAItF,UAAU,QAAQ,EAAEA,OAAO;GACjC;GACA,IAAIqF,UAAU,OAAO;IAAE,GAAGJ;IAAGQ;GAAS;GACtC,OAAO;IACL,GAAGR;IACHQ;IACAjB,QAAQ,EAAEJ,OAAOpE,UAAU,uBAAuB;IAClDyE,SAAS;GACX;EACF,CAAC;EAED3K,UAAU;GAAE,GAAGA;GAASkH,SAAS+D;EAAW;EAC5C,MAAM,EAAEpG,aAAa,KAAKT,WAAW0G,WAAW9K,QAAQoF,EAAE;EAC1D,KAAKhB,WAAW+B,mBAAmBtB,UAAU7E,OAAO;EACpD,KAAK0D,mBAAmB;EAExB,IACE,KAAKU,WAAWU,WAAW9E,QAAQoF,MACnC7G,eAAeyB,SAAS,KAAK4B,SAASqG,uBAAuB,GAE7D,KAAKL,SAAS/C,UAAU7E,SAAS,KAAKgC,cAAc,CAAC,CAACwB,YAAY,CAAC,CAAC;CAExE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ReadonlyThreadRuntimeCore.d.ts","names":[],"sources":["../../../src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts"],"mappings":";;;;;cASa,kCACH,4BACG;UAEH;MAEJ,qBAAQ;EAIZ,YAAY,mBAAmB;EAM/B,eAAe;;;;;EAUf,YAAY;EAMZ;EAIA;EAIA;EAIA;EAIA;EAIA;EAEA;EAIA;EAIA;EAIA;EAIA;EAEA;EAIA;EAEA;EACA,4BAA2B;EAE3B;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA
|
|
1
|
+
{"version":3,"file":"ReadonlyThreadRuntimeCore.d.ts","names":[],"sources":["../../../src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts"],"mappings":";;;;;cASa,kCACH,4BACG;UAEH;MAEJ,qBAAQ;EAIZ,YAAY,mBAAmB;EAM/B,eAAe;;;;;EAUf,YAAY;EAMZ;EAIA;EAIA;EAIA;EAIA;EAIA;EAEA;EAIA;EAIA;EAIA;EAIA;EAEA;EAIA;EAEA;EACA,4BAA2B;EAE3B;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;IACqB;;;;;;;;;;;;;;;;;;IAiDN;;;;;;;;;;;EA6Bf;EAIA;EAIA;EACA;EAEA;;;;;;;;;;;;;;;EAgBA;EACA;EACA;EAEA;EACA;EACA;EAEA;EAIA;;;;;;EASA;EAIA,eAAe"}
|
|
@@ -12,14 +12,14 @@ type Transform<TState, TResult> = {
|
|
|
12
12
|
declare class OptimisticState<TState> extends BaseSubscribable {
|
|
13
13
|
private readonly _pendingTransforms;
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* (e.g. delete). Cleared when no pending transforms remain.
|
|
15
|
+
* Completed optimistic callbacks remain active while any transform is
|
|
16
|
+
* pending, so later state replacements cannot erase them. Invocation order
|
|
17
|
+
* determines which overlapping optimistic update wins.
|
|
19
18
|
*
|
|
20
19
|
* Correctness requirement: `optimistic` callbacks must be idempotent.
|
|
21
20
|
*/
|
|
22
21
|
private readonly _completedOptimistics;
|
|
22
|
+
private _nextTransformOrder;
|
|
23
23
|
private _baseValue;
|
|
24
24
|
private _cachedValue;
|
|
25
25
|
constructor(initialState: TState);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"optimistic-state.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/optimistic-state.ts"],"mappings":";;KAEK,UAAU,QAAQ;EACrB,eAAe,QAAQ;;EAGvB,QAAQ,OAAO,QAAQ,QAAQ,YAAY;;EAG3C,cAAc,OAAO,WAAW;;EAGhC,WAAW,OAAO,QAAQ,MAAM,QAAQ,aAAa;;
|
|
1
|
+
{"version":3,"file":"optimistic-state.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/optimistic-state.ts"],"mappings":";;KAEK,UAAU,QAAQ;EACrB,eAAe,QAAQ;;EAGvB,QAAQ,OAAO,QAAQ,QAAQ,YAAY;;EAG3C,cAAc,OAAO,WAAW;;EAGhC,WAAW,OAAO,QAAQ,MAAM,QAAQ,aAAa;;cAuB1C,gBAAgB,gBAAgB;mBAC1B;;;;;;;;mBAUA;UAGT;UAEA;UACA;EAEW,YAAA,cAAc;UAMzB;MAwBG,aAAa;MAIb,SAAS;EAIb,OAAO,OAAO;EAKR,iBAAiB,SAC5B,WAAW,UAAU,QAAQ,WAC5B,QAAQ"}
|
|
@@ -8,14 +8,14 @@ const pipeTransforms = (initialState, extraParam, transforms) => {
|
|
|
8
8
|
var OptimisticState = class extends BaseSubscribable {
|
|
9
9
|
_pendingTransforms = [];
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* (e.g. delete). Cleared when no pending transforms remain.
|
|
11
|
+
* Completed optimistic callbacks remain active while any transform is
|
|
12
|
+
* pending, so later state replacements cannot erase them. Invocation order
|
|
13
|
+
* determines which overlapping optimistic update wins.
|
|
15
14
|
*
|
|
16
15
|
* Correctness requirement: `optimistic` callbacks must be idempotent.
|
|
17
16
|
*/
|
|
18
17
|
_completedOptimistics = [];
|
|
18
|
+
_nextTransformOrder = 0;
|
|
19
19
|
_baseValue;
|
|
20
20
|
_cachedValue;
|
|
21
21
|
constructor(initialState) {
|
|
@@ -24,9 +24,14 @@ var OptimisticState = class extends BaseSubscribable {
|
|
|
24
24
|
this._cachedValue = initialState;
|
|
25
25
|
}
|
|
26
26
|
_updateState() {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
const activeTransforms = [...this._pendingTransforms.map((transform) => ({
|
|
28
|
+
order: transform.order,
|
|
29
|
+
apply: (state) => pipeTransforms(state, transform.task, [transform.loading, transform.optimistic])
|
|
30
|
+
})), ...this._completedOptimistics.map(({ order, optimistic }) => ({
|
|
31
|
+
order,
|
|
32
|
+
apply: optimistic
|
|
33
|
+
}))].sort((a, b) => a.order - b.order);
|
|
34
|
+
this._cachedValue = activeTransforms.reduce((state, transform) => transform.apply(state), this._baseValue);
|
|
30
35
|
this._notifySubscribers();
|
|
31
36
|
}
|
|
32
37
|
get baseValue() {
|
|
@@ -40,9 +45,11 @@ var OptimisticState = class extends BaseSubscribable {
|
|
|
40
45
|
this._updateState();
|
|
41
46
|
}
|
|
42
47
|
async optimisticUpdate(transform) {
|
|
48
|
+
const order = this._nextTransformOrder++;
|
|
43
49
|
const task = transform.execute();
|
|
44
50
|
const pendingTransform = {
|
|
45
51
|
...transform,
|
|
52
|
+
order,
|
|
46
53
|
task
|
|
47
54
|
};
|
|
48
55
|
try {
|
|
@@ -50,8 +57,14 @@ var OptimisticState = class extends BaseSubscribable {
|
|
|
50
57
|
this._updateState();
|
|
51
58
|
const result = await task;
|
|
52
59
|
this._baseValue = pipeTransforms(this._baseValue, result, [transform.optimistic, transform.then]);
|
|
53
|
-
for (const
|
|
54
|
-
if (transform.optimistic)
|
|
60
|
+
for (const completed of this._completedOptimistics) if (transform.then || completed.order > pendingTransform.order) this._baseValue = completed.optimistic(this._baseValue);
|
|
61
|
+
if (transform.optimistic) {
|
|
62
|
+
this._completedOptimistics.push({
|
|
63
|
+
order: pendingTransform.order,
|
|
64
|
+
optimistic: transform.optimistic
|
|
65
|
+
});
|
|
66
|
+
this._completedOptimistics.sort((a, b) => a.order - b.order);
|
|
67
|
+
}
|
|
55
68
|
return result;
|
|
56
69
|
} finally {
|
|
57
70
|
const index = this._pendingTransforms.indexOf(pendingTransform);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"optimistic-state.js","names":["BaseSubscribable","Transform","execute","Promise","TResult","then","state","TState","result","optimistic","loading","task","PendingTransform","pipeTransforms","initialState","extraParam","TExtra","transforms","extra","reduce","transform","OptimisticState","_pendingTransforms","Array","_completedOptimistics","_baseValue","_cachedValue","constructor","_updateState","_notifySubscribers","baseValue","value","update","optimisticUpdate","pendingTransform","push","
|
|
1
|
+
{"version":3,"file":"optimistic-state.js","names":["BaseSubscribable","Transform","execute","Promise","TResult","then","state","TState","result","optimistic","loading","task","PendingTransform","order","CompletedOptimistic","pipeTransforms","initialState","extraParam","TExtra","transforms","extra","reduce","transform","OptimisticState","_pendingTransforms","Array","_completedOptimistics","_nextTransformOrder","_baseValue","_cachedValue","constructor","_updateState","activeTransforms","map","apply","sort","a","b","_notifySubscribers","baseValue","value","update","optimisticUpdate","pendingTransform","push","completed","index","indexOf","splice","length"],"sources":["../../../src/runtimes/remote-thread-list/optimistic-state.ts"],"sourcesContent":["import { BaseSubscribable } from \"../../subscribable/subscribable\";\n\ntype Transform<TState, TResult> = {\n execute: () => Promise<TResult>;\n\n /** transform the state after the promise resolves */\n then?: (state: TState, result: TResult) => TState;\n\n /** transform the state during resolution and afterwards */\n optimistic?: (state: TState) => TState;\n\n /** transform the state only while loading */\n loading?: (state: TState, task: Promise<TResult>) => TState;\n};\n\ntype PendingTransform<TState, TResult> = Transform<TState, TResult> & {\n order: number;\n task: Promise<TResult>;\n};\n\ntype CompletedOptimistic<TState> = {\n order: number;\n optimistic: (state: TState) => TState;\n};\n\nconst pipeTransforms = <TState, TExtra>(\n initialState: TState,\n extraParam: TExtra,\n transforms: (((state: TState, extra: TExtra) => TState) | undefined)[],\n): TState => {\n return transforms.reduce((state, transform) => {\n return transform?.(state, extraParam) ?? state;\n }, initialState);\n};\n\nexport class OptimisticState<TState> extends BaseSubscribable {\n private readonly _pendingTransforms: Array<PendingTransform<TState, any>> =\n [];\n\n /**\n * Completed optimistic callbacks remain active while any transform is\n * pending, so later state replacements cannot erase them. Invocation order\n * determines which overlapping optimistic update wins.\n *\n * Correctness requirement: `optimistic` callbacks must be idempotent.\n */\n private readonly _completedOptimistics: Array<CompletedOptimistic<TState>> =\n [];\n\n private _nextTransformOrder = 0;\n\n private _baseValue: TState;\n private _cachedValue: TState;\n\n public constructor(initialState: TState) {\n super();\n this._baseValue = initialState;\n this._cachedValue = initialState;\n }\n\n private _updateState(): void {\n const activeTransforms = [\n ...this._pendingTransforms.map((transform) => ({\n order: transform.order,\n apply: (state: TState) =>\n pipeTransforms(state, transform.task, [\n transform.loading,\n transform.optimistic,\n ]),\n })),\n ...this._completedOptimistics.map(({ order, optimistic }) => ({\n order,\n apply: optimistic,\n })),\n ].sort((a, b) => a.order - b.order);\n\n this._cachedValue = activeTransforms.reduce(\n (state, transform) => transform.apply(state),\n this._baseValue,\n );\n\n this._notifySubscribers();\n }\n\n public get baseValue(): TState {\n return this._baseValue;\n }\n\n public get value(): TState {\n return this._cachedValue;\n }\n\n public update(state: TState): void {\n this._baseValue = state;\n this._updateState();\n }\n\n public async optimisticUpdate<TResult>(\n transform: Transform<TState, TResult>,\n ): Promise<TResult> {\n const order = this._nextTransformOrder++;\n const task = transform.execute();\n const pendingTransform = {\n ...transform,\n order,\n task,\n };\n try {\n this._pendingTransforms.push(pendingTransform);\n this._updateState();\n\n const result = await task;\n this._baseValue = pipeTransforms(this._baseValue, result, [\n transform.optimistic,\n transform.then,\n ]);\n\n // `then` can replace state with a stale snapshot, so replay every\n // completed effect; otherwise replay only newer overlapping effects.\n for (const completed of this._completedOptimistics) {\n if (transform.then || completed.order > pendingTransform.order) {\n this._baseValue = completed.optimistic(this._baseValue);\n }\n }\n\n if (transform.optimistic) {\n this._completedOptimistics.push({\n order: pendingTransform.order,\n optimistic: transform.optimistic,\n });\n this._completedOptimistics.sort((a, b) => a.order - b.order);\n }\n\n return result;\n } finally {\n const index = this._pendingTransforms.indexOf(pendingTransform);\n if (index > -1) {\n this._pendingTransforms.splice(index, 1);\n }\n\n if (this._pendingTransforms.length === 0) {\n this._completedOptimistics.length = 0;\n }\n\n this._updateState();\n }\n }\n}\n"],"mappings":";;AAyBA,MAAMe,kBACJC,cACAC,YACAE,eACW;CACX,OAAOA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AAYpB,QAAQ,CACxDc,UAAUb,YACVa,UAAUjB,IAAI,CACf;GAID,KAAK,MAAMwC,aAAa,KAAKnB,uBAC3B,IAAIJ,UAAUjB,QAAQwC,UAAUhC,QAAQ8B,iBAAiB9B,OACvD,KAAKe,aAAaiB,UAAUpC,WAAW,KAAKmB,UAAU;GAI1D,IAAIN,UAAUb,YAAY;IACxB,KAAKiB,sBAAsBkB,KAAK;KAC9B/B,OAAO8B,iBAAiB9B;KACxBJ,YAAYa,UAAUb;IACxB,CAAC;IACD,KAAKiB,sBAAsBS,MAAMC,GAAGC,MAAMD,EAAEvB,QAAQwB,EAAExB,KAAK;GAC7D;GAEA,OAAOL;EACT,UAAU;GACR,MAAMsC,QAAQ,KAAKtB,mBAAmBuB,QAAQJ,gBAAgB;GAC9D,IAAIG,QAAQ,IACV,KAAKtB,mBAAmBwB,OAAOF,OAAO,CAAC;GAGzC,IAAI,KAAKtB,mBAAmByB,WAAW,GACrC,KAAKvB,sBAAsBuB,SAAS;GAGtC,KAAKlB,aAAa;EACpB;CACF;AACF"}
|
|
@@ -5,7 +5,7 @@ import { ComponentType, PropsWithChildren } from "react";
|
|
|
5
5
|
//#region src/runtimes/remote-thread-list/types.d.ts
|
|
6
6
|
type RemoteThreadInitializeResponse = {
|
|
7
7
|
remoteId: string;
|
|
8
|
-
externalId
|
|
8
|
+
externalId?: string | undefined;
|
|
9
9
|
};
|
|
10
10
|
type RemoteThreadMetadata = {
|
|
11
11
|
readonly status: "regular" | "archived";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolInvocationTracker.d.ts","names":[],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"mappings":";;;;;;;KAoBY;EACN;;EAEA;EACA;IAAW;IAAe;;;KAGpB;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB;WACD,mBAAmB;;WAEnB;;;;;;WAMA;;KAGC;;;;;EAKV,WAAW,SAAS;;;;;;EAMpB,mBACE,UAAU,oBAAoB;;;;;;;;;;;;;;;;;;;;;;cAiErB;mBACM;mBACA;mBAEA;;;;;;;;;;;mBAWA;mBACA;;mBAQA;mBACA;UAET;UAEA;UACA;;UAGA;UACA;UAEA;;;;;;;;;UAUA;UACA;
|
|
1
|
+
{"version":3,"file":"ToolInvocationTracker.d.ts","names":[],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"mappings":";;;;;;;KAoBY;EACN;;EAEA;EACA;IAAW;IAAe;;;KAGpB;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB;WACD,mBAAmB;;WAEnB;;;;;;WAMA;;KAGC;;;;;EAKV,WAAW,SAAS;;;;;;EAMpB,mBACE,UAAU,oBAAoB;;;;;;;;;;;;;;;;;;;;;;cAiErB;mBACM;mBACA;mBAEA;;;;;;;;;;;mBAWA;mBACA;;mBAQA;mBACA;UAET;UAEA;UACA;;UAGA;UACA;UAEA;;;;;;;;;UAUA;UACA;EAGN,YAAA,gBAAgB,eAAe,mBAC/B,WAAW;;;;;;UAaL;;;;;EA+CD,SAAS,UAAU;;;;;;EAmEnB;;;;;EAkBA,SAAS;;;;;;;EAiCT,OAAO,oBAAoB;;;;;;;EAoB3B,eAAe,oBAAoB;UAMlC;UA8BA;UAuBA;UAOA;UAiBA;UAqCA;UAWA;UAaA;UAOA;UAUA;UAKA;UAgBA;;;;;;;;UA8BA;UAWA;UA0GA"}
|
|
@@ -389,11 +389,10 @@ var ToolInvocationTracker = class {
|
|
|
389
389
|
if (!entry.argsComplete && entry.controller) {
|
|
390
390
|
if (this._shouldCloseArgsStream({
|
|
391
391
|
toolName: content.toolName,
|
|
392
|
-
argsText:
|
|
392
|
+
argsText: entry.argsText,
|
|
393
393
|
hasResult
|
|
394
394
|
})) {
|
|
395
395
|
entry.controller.argsText.close();
|
|
396
|
-
entry.argsText = content.argsText;
|
|
397
396
|
entry.argsComplete = true;
|
|
398
397
|
}
|
|
399
398
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolInvocationTracker.js","names":["process","env","NODE_ENV","createAssistantStreamController","ToolCallStreamController","ToolResponse","unstable_toolResultStream","Tool","ToolModelContentPart","AssistantMetaTransformStream","ReadonlyJSONValue","isJSONValueEqual","ThreadMessage","ToolExecutionStatus","type","payload","AddToolResultCommand","toolCallId","toolName","result","isError","artifact","modelContent","ToolInvocationTrackerSnapshot","messages","isRunning","isLoading","ToolInvocationTrackerCallbacks","onResult","command","onStatusesChange","statuses","ReadonlyMap","ToolCallEntry","argsText","hasResult","controller","argsComplete","isArgsTextComplete","JSON","parse","parseArgsText","undefined","isEquivalentCompleteArgsText","previous","next","previousValue","nextValue","ToolInvocationTracker","_getTools","Record","_callbacks","_entries","Map","_skipExecuteStreamIds","Set","_humanInput","resolve","reject","reason","_executing","_settledResolvers","Array","_statuses","_ac","AbortController","_pendingRestore","_lastSnapshot","_isRunning","_controller","ReturnType","_pipelineDead","_pipelineRestartUsed","constructor","getTools","callbacks","_initPipeline","stream","transform","_getWrappedTools","signal","_onHumanInput","onExecutionStart","id","_onExecutionStart","onExecutionEnd","_onExecutionEnd","pipeThrough","pipeTo","WritableStream","write","chunk","_handleResultChunk","err","console","error","catch","setState","snapshot","_demoteEntriesToRestored","clear","restoreFromLoading","previousIsRunning","_processMessages","reset","abort","finally","Promise","forEach","Error","size","push","resume","handlers","get","delete","_setStatus","getStatuses","tools","Object","fromEntries","entries","map","name","tool","execute","wrappedTool","args","context","Parameters","NonNullable","has","set","add","_deleteStatus","resolvers","splice","meta","entry","_invokeOnResult","_invokeOnStatusesChange","status","_hasExecutableTool","streamCall","_shouldCloseArgsStream","_startActiveEntry","skipExecute","toolCallController","addToolCallPart","_processArgsText","content","shouldWriteArgsText","warn","startsWith","shouldClose","close","delta","slice","length","append","isRestore","message","isArray","existing","signatureChanged","activeController","setResponse"],"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} 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 } from \"../../types/message\";\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\nexport type ToolInvocationTrackerSnapshot = {\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\nexport type ToolInvocationTrackerCallbacks = {\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\ntype ToolCallEntry = {\n toolName: string;\n argsText: string;\n hasResult: 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 }\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\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 */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTrackerCallbacks;\n\n private readonly _entries = new Map<string, ToolCallEntry>();\n /**\n * Tool call ids whose `execute` should be short-circuited in the wrapper.\n * Populated when an entry is created with a result already attached\n * (history reload, mid-run resume, etc.) — `execute` is suppressed so\n * client-side side effects don't double-run. Membership outlives the\n * entry: `reset()` deliberately does *not* clear this so post-abort\n * cancellation `result` chunks for pre-resolved entries can still be\n * recognized and dropped. Growth is bounded by the number of pre-resolved\n * tool calls observed in the session.\n */\n private readonly _skipExecuteStreamIds = new Set<string>();\n private readonly _humanInput = new Map<\n string,\n {\n resolve: (payload: unknown) => void;\n reject: (reason: unknown) => void;\n }\n >();\n /** In-flight `execute` invocations keyed by tool call id. */\n private readonly _executing = new Set<string>();\n private readonly _settledResolvers: Array<() => void> = [];\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: ToolInvocationTrackerSnapshot | 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 all active entries to restored so they survive\n * across the restart without re-firing `streamCall` (preserves the\n * \"exactly once\" contract). Capped at a single auto-restart per session\n * — repeated failures keep the tracker 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: ToolInvocationTrackerCallbacks,\n ) {\n this._getTools = getTools;\n this._callbacks = callbacks;\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 transform = unstable_toolResultStream(\n () => this._getWrappedTools(),\n () => this._ac.signal,\n (toolCallId, payload) => this._onHumanInput(toolCallId, payload),\n {\n onExecutionStart: (id) => this._onExecutionStart(id),\n onExecutionEnd: (id) => this._onExecutionEnd(id),\n },\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: ToolInvocationTrackerSnapshot): void {\n try {\n // Recover from a dead pipeline before processing anything. We demote\n // all active entries to \"restored\" so the rebuilt pipeline does not\n // re-fire `streamCall` for tool calls that already fired pre-death;\n // preserves the \"exactly once per toolCallId\" contract.\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._lastSnapshot = null;\n // `_skipExecuteStreamIds` is intentionally not cleared — see field doc.\n void this.abort().finally(() => {\n this._executing.clear();\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 public abort(): 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 this._ac.abort();\n this._ac = new AbortController();\n\n if (this._executing.size === 0) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n this._settledResolvers.push(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 if (execute === undefined) return [name, tool];\n\n const wrappedTool = {\n ...tool,\n execute: (\n ...[args, context]: Parameters<NonNullable<typeof execute>>\n ) => {\n if (this._skipExecuteStreamIds.has(context.toolCallId)) {\n // Pre-resolved tool call: never invoke the host's execute.\n // Returning a never-settling Promise keeps the executor's\n // pending entry alive but enqueues nothing.\n return new Promise(() => {}) as never;\n }\n return execute(args, context);\n },\n } as Tool;\n return [name, wrappedTool];\n }),\n ) as Record<string, Tool>;\n }\n\n // ──────────────── internal: execution lifecycle callbacks ────────────────\n\n private _onHumanInput(\n toolCallId: string,\n payload: unknown,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\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, { resolve, reject });\n this._setStatus(toolCallId, {\n type: \"interrupt\",\n payload: { type: \"human\", payload },\n });\n });\n }\n\n private _onExecutionStart(toolCallId: string): void {\n if (this._skipExecuteStreamIds.has(toolCallId)) return;\n\n this._executing.add(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n }\n\n private _onExecutionEnd(toolCallId: string): void {\n if (!this._executing.delete(toolCallId)) return;\n\n this._deleteStatus(toolCallId);\n\n if (this._executing.size === 0) {\n const resolvers = this._settledResolvers.splice(0);\n resolvers.forEach((resolve) => {\n try {\n resolve();\n } catch {\n // ignore — settled-resolver consumer threw\n }\n });\n }\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 entry = this._entries.get(toolCallId);\n\n // Pre-resolved tool call whose entry has been cleared by `reset()`.\n // The post-abort cancellation chunk lands here after the entry is\n // gone; suppress via the long-lived skip-execute marker.\n if (!entry && this._skipExecuteStreamIds.has(toolCallId)) {\n return;\n }\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\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 _hasExecutableTool(toolName: string): boolean {\n const tool = this._getTools()?.[toolName];\n return tool?.execute !== undefined || tool?.streamCall !== undefined;\n }\n\n private _shouldCloseArgsStream({\n toolName,\n argsText,\n hasResult,\n }: {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n }): boolean {\n if (hasResult) return true;\n if (!this._hasExecutableTool(toolName)) {\n return !this._isRunning && isArgsTextComplete(argsText);\n }\n return isArgsTextComplete(argsText);\n }\n\n private _startActiveEntry(\n toolCallId: string,\n toolName: string,\n skipExecute: boolean,\n ): ToolCallEntry {\n const toolCallController = this._controller.addToolCallPart({\n toolName,\n toolCallId,\n });\n if (skipExecute) {\n this._skipExecuteStreamIds.add(toolCallId);\n }\n const entry: ToolCallEntry = {\n toolName,\n controller: toolCallController,\n argsText: \"\",\n hasResult: false,\n argsComplete: false,\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 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 toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\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 toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\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 const shouldClose = this._shouldCloseArgsStream({\n toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\n });\n if (shouldClose) {\n entry.controller.argsText.close();\n entry.argsText = content.argsText;\n entry.argsComplete = true;\n }\n }\n }\n\n private _processMessages(messages: readonly ThreadMessage[]): void {\n const isRestore = this._pendingRestore;\n\n for (const message of messages) {\n if (!message || !Array.isArray((message as ThreadMessage).content)) {\n continue;\n }\n for (const content of message.content as readonly ThreadMessage[\"content\"][number][]) {\n if (!content || content.type !== \"tool-call\") continue;\n\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 if (content.messages) this._processMessages(content.messages);\n continue;\n }\n\n // Live snapshot.\n let entry = existing;\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) {\n if (content.messages) this._processMessages(content.messages);\n continue;\n }\n this._entries.delete(content.toolCallId);\n entry = undefined;\n }\n\n if (!entry) {\n entry = this._startActiveEntry(\n content.toolCallId,\n content.toolName,\n content.result !== undefined,\n );\n }\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 if (content.messages) this._processMessages(content.messages);\n }\n }\n }\n}\n"],"mappings":";;;;AAkFA,MAAMsC,sBAAsBJ,aAAqB;CAC/C,IAAI;EACFK,KAAKC,MAAMN,QAAQ;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAMO,iBAAiBP,aAAqB;CAC1C,IAAI;EACF,OAAOK,KAAKC,MAAMN,QAAQ;CAC5B,QAAQ;EACN;CACF;AACF;AAEA,MAAMS,gCAAgCC,UAAkBC,SAAiB;CACvE,MAAMC,gBAAgBL,cAAcG,QAAQ;CAC5C,MAAMG,YAAYN,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ToolCallStreamController","ToolResponse","unstable_toolResultStream","Tool","ToolModelContentPart","AssistantMetaTransformStream","ReadonlyJSONValue","isJSONValueEqual","ThreadMessage","ToolExecutionStatus","type","payload","AddToolResultCommand","toolCallId","toolName","result","isError","artifact","modelContent","ToolInvocationTrackerSnapshot","messages","isRunning","isLoading","ToolInvocationTrackerCallbacks","onResult","command","onStatusesChange","statuses","ReadonlyMap","ToolCallEntry","argsText","hasResult","controller","argsComplete","isArgsTextComplete","JSON","parse","parseArgsText","undefined","isEquivalentCompleteArgsText","previous","next","previousValue","nextValue","ToolInvocationTracker","_getTools","Record","_callbacks","_entries","Map","_skipExecuteStreamIds","Set","_humanInput","resolve","reject","reason","_executing","_settledResolvers","Array","_statuses","_ac","AbortController","_pendingRestore","_lastSnapshot","_isRunning","_controller","ReturnType","_pipelineDead","_pipelineRestartUsed","constructor","getTools","callbacks","_initPipeline","stream","transform","_getWrappedTools","signal","_onHumanInput","onExecutionStart","id","_onExecutionStart","onExecutionEnd","_onExecutionEnd","pipeThrough","pipeTo","WritableStream","write","chunk","_handleResultChunk","err","console","error","catch","setState","snapshot","_demoteEntriesToRestored","clear","restoreFromLoading","previousIsRunning","_processMessages","reset","abort","finally","Promise","forEach","Error","size","push","resume","handlers","get","delete","_setStatus","getStatuses","tools","Object","fromEntries","entries","map","name","tool","execute","wrappedTool","args","context","Parameters","NonNullable","has","set","add","_deleteStatus","resolvers","splice","meta","entry","_invokeOnResult","_invokeOnStatusesChange","status","_hasExecutableTool","streamCall","_shouldCloseArgsStream","_startActiveEntry","skipExecute","toolCallController","addToolCallPart","_processArgsText","content","shouldWriteArgsText","warn","startsWith","shouldClose","close","delta","slice","length","append","isRestore","message","isArray","existing","signatureChanged","activeController","setResponse"],"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} 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 } from \"../../types/message\";\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\nexport type ToolInvocationTrackerSnapshot = {\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\nexport type ToolInvocationTrackerCallbacks = {\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\ntype ToolCallEntry = {\n toolName: string;\n argsText: string;\n hasResult: 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 }\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\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 */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTrackerCallbacks;\n\n private readonly _entries = new Map<string, ToolCallEntry>();\n /**\n * Tool call ids whose `execute` should be short-circuited in the wrapper.\n * Populated when an entry is created with a result already attached\n * (history reload, mid-run resume, etc.) — `execute` is suppressed so\n * client-side side effects don't double-run. Membership outlives the\n * entry: `reset()` deliberately does *not* clear this so post-abort\n * cancellation `result` chunks for pre-resolved entries can still be\n * recognized and dropped. Growth is bounded by the number of pre-resolved\n * tool calls observed in the session.\n */\n private readonly _skipExecuteStreamIds = new Set<string>();\n private readonly _humanInput = new Map<\n string,\n {\n resolve: (payload: unknown) => void;\n reject: (reason: unknown) => void;\n }\n >();\n /** In-flight `execute` invocations keyed by tool call id. */\n private readonly _executing = new Set<string>();\n private readonly _settledResolvers: Array<() => void> = [];\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: ToolInvocationTrackerSnapshot | 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 all active entries to restored so they survive\n * across the restart without re-firing `streamCall` (preserves the\n * \"exactly once\" contract). Capped at a single auto-restart per session\n * — repeated failures keep the tracker 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: ToolInvocationTrackerCallbacks,\n ) {\n this._getTools = getTools;\n this._callbacks = callbacks;\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 transform = unstable_toolResultStream(\n () => this._getWrappedTools(),\n () => this._ac.signal,\n (toolCallId, payload) => this._onHumanInput(toolCallId, payload),\n {\n onExecutionStart: (id) => this._onExecutionStart(id),\n onExecutionEnd: (id) => this._onExecutionEnd(id),\n },\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: ToolInvocationTrackerSnapshot): void {\n try {\n // Recover from a dead pipeline before processing anything. We demote\n // all active entries to \"restored\" so the rebuilt pipeline does not\n // re-fire `streamCall` for tool calls that already fired pre-death;\n // preserves the \"exactly once per toolCallId\" contract.\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._lastSnapshot = null;\n // `_skipExecuteStreamIds` is intentionally not cleared — see field doc.\n void this.abort().finally(() => {\n this._executing.clear();\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 public abort(): 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 this._ac.abort();\n this._ac = new AbortController();\n\n if (this._executing.size === 0) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n this._settledResolvers.push(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 if (execute === undefined) return [name, tool];\n\n const wrappedTool = {\n ...tool,\n execute: (\n ...[args, context]: Parameters<NonNullable<typeof execute>>\n ) => {\n if (this._skipExecuteStreamIds.has(context.toolCallId)) {\n // Pre-resolved tool call: never invoke the host's execute.\n // Returning a never-settling Promise keeps the executor's\n // pending entry alive but enqueues nothing.\n return new Promise(() => {}) as never;\n }\n return execute(args, context);\n },\n } as Tool;\n return [name, wrappedTool];\n }),\n ) as Record<string, Tool>;\n }\n\n // ──────────────── internal: execution lifecycle callbacks ────────────────\n\n private _onHumanInput(\n toolCallId: string,\n payload: unknown,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\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, { resolve, reject });\n this._setStatus(toolCallId, {\n type: \"interrupt\",\n payload: { type: \"human\", payload },\n });\n });\n }\n\n private _onExecutionStart(toolCallId: string): void {\n if (this._skipExecuteStreamIds.has(toolCallId)) return;\n\n this._executing.add(toolCallId);\n this._setStatus(toolCallId, { type: \"executing\" });\n }\n\n private _onExecutionEnd(toolCallId: string): void {\n if (!this._executing.delete(toolCallId)) return;\n\n this._deleteStatus(toolCallId);\n\n if (this._executing.size === 0) {\n const resolvers = this._settledResolvers.splice(0);\n resolvers.forEach((resolve) => {\n try {\n resolve();\n } catch {\n // ignore — settled-resolver consumer threw\n }\n });\n }\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 entry = this._entries.get(toolCallId);\n\n // Pre-resolved tool call whose entry has been cleared by `reset()`.\n // The post-abort cancellation chunk lands here after the entry is\n // gone; suppress via the long-lived skip-execute marker.\n if (!entry && this._skipExecuteStreamIds.has(toolCallId)) {\n return;\n }\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\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 _hasExecutableTool(toolName: string): boolean {\n const tool = this._getTools()?.[toolName];\n return tool?.execute !== undefined || tool?.streamCall !== undefined;\n }\n\n private _shouldCloseArgsStream({\n toolName,\n argsText,\n hasResult,\n }: {\n toolName: string;\n argsText: string;\n hasResult: boolean;\n }): boolean {\n if (hasResult) return true;\n if (!this._hasExecutableTool(toolName)) {\n return !this._isRunning && isArgsTextComplete(argsText);\n }\n return isArgsTextComplete(argsText);\n }\n\n private _startActiveEntry(\n toolCallId: string,\n toolName: string,\n skipExecute: boolean,\n ): ToolCallEntry {\n const toolCallController = this._controller.addToolCallPart({\n toolName,\n toolCallId,\n });\n if (skipExecute) {\n this._skipExecuteStreamIds.add(toolCallId);\n }\n const entry: ToolCallEntry = {\n toolName,\n controller: toolCallController,\n argsText: \"\",\n hasResult: false,\n argsComplete: false,\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 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 toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\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 toolName: content.toolName,\n argsText: content.argsText,\n hasResult,\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 toolName: content.toolName,\n argsText: entry.argsText,\n hasResult,\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 message of messages) {\n if (!message || !Array.isArray((message as ThreadMessage).content)) {\n continue;\n }\n for (const content of message.content as readonly ThreadMessage[\"content\"][number][]) {\n if (!content || content.type !== \"tool-call\") continue;\n\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 if (content.messages) this._processMessages(content.messages);\n continue;\n }\n\n // Live snapshot.\n let entry = existing;\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) {\n if (content.messages) this._processMessages(content.messages);\n continue;\n }\n this._entries.delete(content.toolCallId);\n entry = undefined;\n }\n\n if (!entry) {\n entry = this._startActiveEntry(\n content.toolCallId,\n content.toolName,\n content.result !== undefined,\n );\n }\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 if (content.messages) this._processMessages(content.messages);\n }\n }\n }\n}\n"],"mappings":";;;;AAkFA,MAAMsC,sBAAsBJ,aAAqB;CAC/C,IAAI;EACFK,KAAKC,MAAMN,QAAQ;EACnB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAMO,iBAAiBP,aAAqB;CAC1C,IAAI;EACF,OAAOK,KAAKC,MAAMN,QAAQ;CAC5B,QAAQ;EACN;CACF;AACF;AAEA,MAAMS,gCAAgCC,UAAkBC,SAAiB;CACvE,MAAMC,gBAAgBL,cAAcG,QAAQ;CAC5C,MAAMG,YAAYN,cAAcI,IAAI;CACpC,IAAIC,kBAA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MAClBC,WAAWmH,QAAQnI,WAAWuB,KAAAA;KAChC,CAAC;KAEH,IAAI4G,QAAQ9H,UAAU,KAAK+E,iBAAiB+C,QAAQ9H,QAAQ;KAC5D;IACF;IAGA,IAAIkH,QAAQyB;IAEZ,IAAIzB,SAAS,CAACA,MAAMtG,YAAY;KAM9B,IAAI,EAFFkH,QAAQpH,aAAawG,MAAMxG,YAC1BoH,QAAQnI,WAAWuB,KAAAA,MAAegG,MAAMvG,YACpB;MACrB,IAAImH,QAAQ9H,UAAU,KAAK+E,iBAAiB+C,QAAQ9H,QAAQ;MAC5D;KACF;KACA,KAAK4B,SAAS+D,OAAOmC,QAAQrI,UAAU;KACvCyH,QAAQhG,KAAAA;IACV;IAEA,IAAI,CAACgG,OACHA,QAAQ,KAAKO,kBACXK,QAAQrI,YACRqI,QAAQpI,UACRoI,QAAQnI,WAAWuB,KAAAA,CACrB;IAGF,KAAK2G,iBAAiBX,OAAOY,OAAO;IAEpC,IAAIA,QAAQnI,WAAWuB,KAAAA,KAAa,CAACgG,MAAMvG,WAAW;KAIpD,MAAM,EAAEC,YAAYiI,qBAAqB3B;KACzC,IAAI,CAAC2B,kBAAkB;KACvB3B,MAAMvG,YAAY;KAClBuG,MAAMrG,eAAe;KACrBgI,iBAAiBC,YACf,IAAIjK,aAAa;MACfc,QAAQmI,QAAQnI;MAChBE,UAAUiI,QAAQjI;MAClBD,SAASkI,QAAQlI;MACjB,GAAIkI,QAAQhI,iBAAiBoB,KAAAA,IACzB,EAAEpB,cAAcgI,QAAQhI,aAAa,IACrC,CAAC;KACP,CAAC,CACH;KACA+I,iBAAiBV,MAAM;IACzB;IAEA,IAAIL,QAAQ9H,UAAU,KAAK+E,iBAAiB+C,QAAQ9H,QAAQ;GAC9D;EACF;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chain-of-thought-client.d.ts","names":[],"sources":["../../../src/store/clients/chain-of-thought-client.ts"],"mappings":";;;;cAwCa,kDAAoB,SAAA;
|
|
1
|
+
{"version":3,"file":"chain-of-thought-client.d.ts","names":[],"sources":["../../../src/store/clients/chain-of-thought-client.ts"],"mappings":";;;;cAwCa,kDAAoB,SAAA;EAtBxB,gBAAS;EACA,iBAAC;IAAY;QAAoB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-op-composer-client.d.ts","names":[],"sources":["../../../src/store/clients/no-op-composer-client.ts"],"mappings":";;cA2Ea,gDAAkB,SAAA"}
|
|
1
|
+
{"version":3,"file":"no-op-composer-client.d.ts","names":[],"sources":["../../../src/store/clients/no-op-composer-client.ts"],"mappings":";;cA2Ea,gDAAkB,SAAA;EAnEvB"}
|