@assistant-ui/core 0.3.9 → 0.3.11

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.
Files changed (40) hide show
  1. package/dist/model-context/frame/provider.js +1 -3
  2. package/dist/model-context/frame/provider.js.map +1 -1
  3. package/dist/model-context/types.js +4 -2
  4. package/dist/model-context/types.js.map +1 -1
  5. package/dist/react/AssistantProvider.js +5 -4
  6. package/dist/react/AssistantProvider.js.map +1 -1
  7. package/dist/react/adapters/LocalStorageThreadListAdapter.js +2 -1
  8. package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
  9. package/dist/react/client/Interactables.js +12 -10
  10. package/dist/react/client/Interactables.js.map +1 -1
  11. package/dist/react/model-context/useInteractable.js.map +1 -1
  12. package/dist/react/primitives/message/MessageGroupedParts.js +11 -8
  13. package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
  14. package/dist/react/primitives/message/MessageParts.js +27 -22
  15. package/dist/react/primitives/message/MessageParts.js.map +1 -1
  16. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.d.ts.map +1 -1
  17. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +22 -14
  18. package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js.map +1 -1
  19. package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
  20. package/dist/react/runtimes/external-message-converter.js +18 -3
  21. package/dist/react/runtimes/external-message-converter.js.map +1 -1
  22. package/dist/react/runtimes/useLocalRuntime.js +2 -1
  23. package/dist/react/runtimes/useLocalRuntime.js.map +1 -1
  24. package/dist/runtime/api/message-runtime.js +4 -2
  25. package/dist/runtime/api/message-runtime.js.map +1 -1
  26. package/dist/runtimes/external-store/external-store-thread-runtime-core.js +8 -4
  27. package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
  28. package/dist/runtimes/local/local-thread-runtime-core.js +9 -6
  29. package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
  30. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +31 -28
  31. package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
  32. package/dist/subscribable/subscribable.js +6 -4
  33. package/dist/subscribable/subscribable.js.map +1 -1
  34. package/package.json +10 -10
  35. package/src/react/runtimes/cloud/useCloudThreadListAdapter.test.tsx +49 -0
  36. package/src/react/runtimes/cloud/useCloudThreadListAdapter.tsx +11 -2
  37. package/src/react/runtimes/external-message-converter.test.ts +71 -0
  38. package/src/react/runtimes/external-message-converter.test.tsx +9 -0
  39. package/src/react/runtimes/external-message-converter.ts +35 -2
  40. package/src/runtimes/local/local-thread-runtime-core.test.ts +18 -22
@@ -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","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","status","type","history","_options","adapters","update","bind","item","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","undefined","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","messages","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadPromise","__internal_load","promise","load","repo","repository","import","length","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","willRun","role","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","initPromise","newMessage","reason","addOrUpdateMessage","resetHead","deleteMessage","messageId","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","runCallback","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","active","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","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","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 type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\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 refetchThread: false,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\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 if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private 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 // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n alreadyPersisted,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n const active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = abortController;\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n 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 try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = abortController.signal;\n const 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 if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (isTerminal || (isPausing && history?.update)) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (c.result === undefined) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else if (added) {\n this._persistPausedMessage(parentId, message);\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n 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 } else {\n this._persistPausedMessage(parentId, message);\n }\n }\n}\n"],"mappings":";;;;;;;;;AAoCA,IAAMyB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUjB,sBAEV;CACE,eAA+B;EAC7BmB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAC5B,aAAoD;CACpD,iBAAyB;CAEzB,iCAAyB,IAAIS,IAA2B;CAIxD,mBACEG,IACAC,OACe;EACf,MAAMC,QAAQ,KAAKN,eAAeO,IAAIH,EAAE,KAAKF,QAAQM,QAAQ,EAAA,CAAGC,KAC9DJ,OACAA,KACF;EACA,MAAMK,SAASJ,KAAKG,WACZ,CAAC,SACD,CAAC,CACT;EACA,KAAKT,eAAeW,IAAIP,IAAIM,MAAM;EAClC,OAAYD,WAAW;GACrB,IAAI,KAAKT,eAAeO,IAAIH,EAAE,MAAMM,QAClC,KAAKV,eAAelB,OAAOsB,EAAE;EAEjC,CAAC;EACD,OAAOE;CACT;CAIA,sBACEO,UACArC,SACA;EACA,IAAIA,QAAQsC,QA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AC5C,MAAM,EAAEvK,aAAa,KAAKqD,WAAW+G,WAAWzM,QAAQ4B,EAAE;EAC1D,KAAK8D,WAAW+B,mBAAmBpF,UAAUrC,OAAO;EACpD,KAAKoF,mBAAmB;EAExB,IACE,KAAKM,WAAWO,WAAWjG,QAAQ4B,MACnCtD,eAAe0B,SAAS,KAAKyC,SAAS8G,uBAAuB,GAE7D,KAAKN,SAAS5G,UAAUrC,SAAS,KAAK+C,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKZ,sBAAsBC,UAAUrC,OAAO;CAEhD;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","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","status","type","history","_options","adapters","update","bind","item","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","undefined","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","messages","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadPromise","__internal_load","promise","load","repo","repository","import","length","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","willRun","role","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","initPromise","newMessage","reason","addOrUpdateMessage","resetHead","deleteMessage","messageId","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","runCallback","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","active","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","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","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 type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\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 refetchThread: false,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\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 if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private 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 // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n alreadyPersisted,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n const active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = abortController;\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n 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 try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = abortController.signal;\n const 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 if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (isTerminal || (isPausing && history?.update)) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (c.result === undefined) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else if (added) {\n this._persistPausedMessage(parentId, message);\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n 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 } else {\n this._persistPausedMessage(parentId, message);\n }\n }\n}\n"],"mappings":";;;;;;;;;AAoCA,IAAMyB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUjB,sBAEV;CACE,eAA+B;EAC7BmB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAC5B,aAAoD;CACpD,iBAAyB;CAEzB,iCAAyB,IAAIS,IAA2B;CAIxD,mBACEG,IACAC,OACe;EACf,MAAMC,QAAQ,KAAKN,eAAeO,IAAIH,EAAE,KAAKF,QAAQM,QAAQ,EAAA,CAAGC,KAC9DJ,OACAA,KACF;EACA,MAAMK,SAASJ,KAAKG,WACZ,CAAC,SACD,CAAC,CACT;EACA,KAAKT,eAAeW,IAAIP,IAAIM,MAAM;EAClC,OAAYD,WAAW;GACrB,IAAI,KAAKT,eAAeO,IAAIH,EAAE,MAAMM,QAClC,KAAKV,eAAelB,OAAOsB,EAAE;EAEjC,CAAC;EACD,OAAOE;CACT;CAIA,sBACEO,UACArC,SACA;EACA,IAAIA,QAAQsC,QAAQC,SAAS,mBAAmB;EAChD,MAAMC,UAAU,KAAKC,SAASC,SAASF;EAC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KqD,WAAW+G,WAAWzM,QAAQ4B,EAAE;EAC1D,KAAK8D,WAAW+B,mBAAmBpF,UAAUrC,OAAO;EACpD,KAAKoF,mBAAmB;EAExB,IACE,KAAKM,WAAWO,WAAWjG,QAAQ4B,MACnCtD,eAAe0B,SAAS,KAAKyC,SAAS8G,uBAAuB,GAE7D,KAAKN,SAAS5G,UAAUrC,SAAS,KAAK+C,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKZ,sBAAsBC,UAAUrC,OAAO;CAEhD;AACF"}
@@ -346,34 +346,37 @@ var ToolInvocationTracker = class {
346
346
  const hasResult = content.result !== void 0;
347
347
  if (content.argsText !== entry.argsText) {
348
348
  let shouldWriteArgsText = true;
349
- if (entry.argsComplete) if (isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {
350
- entry.argsText = content.argsText;
351
- shouldWriteArgsText = false;
352
- } else {
353
- if (process.env.NODE_ENV !== "production") console.warn("[ToolInvocationTracker] argsText changed after first completion; not re-firing streamCall (see EDGE_CASES.md A.4)", {
354
- previous: entry.argsText,
355
- next: content.argsText,
356
- toolCallId: content.toolCallId
357
- });
358
- shouldWriteArgsText = false;
359
- }
360
- else if (!content.argsText.startsWith(entry.argsText)) if (isArgsTextComplete(entry.argsText) && isArgsTextComplete(content.argsText) && isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {
361
- const shouldClose = this._shouldCloseArgsStream({
362
- toolName: content.toolName,
363
- argsText: content.argsText,
364
- hasResult
365
- });
366
- if (shouldClose) entry.controller.argsText.close();
367
- entry.argsText = content.argsText;
368
- entry.argsComplete = shouldClose;
369
- shouldWriteArgsText = false;
370
- } else {
371
- if (process.env.NODE_ENV !== "production") console.warn("[ToolInvocationTracker] argsText regressed mid-stream; not restarting (see EDGE_CASES.md A.2)", {
372
- previous: entry.argsText,
373
- next: content.argsText,
374
- toolCallId: content.toolCallId
375
- });
376
- shouldWriteArgsText = false;
349
+ if (entry.argsComplete) {
350
+ if (isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {
351
+ entry.argsText = content.argsText;
352
+ shouldWriteArgsText = false;
353
+ } else {
354
+ if (process.env.NODE_ENV !== "production") console.warn("[ToolInvocationTracker] argsText changed after first completion; not re-firing streamCall (see EDGE_CASES.md A.4)", {
355
+ previous: entry.argsText,
356
+ next: content.argsText,
357
+ toolCallId: content.toolCallId
358
+ });
359
+ shouldWriteArgsText = false;
360
+ }
361
+ } else if (!content.argsText.startsWith(entry.argsText)) {
362
+ if (isArgsTextComplete(entry.argsText) && isArgsTextComplete(content.argsText) && isEquivalentCompleteArgsText(entry.argsText, content.argsText)) {
363
+ const shouldClose = this._shouldCloseArgsStream({
364
+ toolName: content.toolName,
365
+ argsText: content.argsText,
366
+ hasResult
367
+ });
368
+ if (shouldClose) entry.controller.argsText.close();
369
+ entry.argsText = content.argsText;
370
+ entry.argsComplete = shouldClose;
371
+ shouldWriteArgsText = false;
372
+ } else {
373
+ if (process.env.NODE_ENV !== "production") console.warn("[ToolInvocationTracker] argsText regressed mid-stream; not restarting (see EDGE_CASES.md A.2)", {
374
+ previous: entry.argsText,
375
+ next: content.argsText,
376
+ toolCallId: content.toolCallId
377
+ });
378
+ shouldWriteArgsText = false;
379
+ }
377
380
  }
378
381
  if (shouldWriteArgsText && entry.controller) {
379
382
  const delta = content.argsText.slice(entry.argsText.length);
@@ -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","ToolCallEntry","argsText","hasResult","controller","argsComplete","isArgsTextComplete","JSON","parse","parseArgsText","undefined","isEquivalentCompleteArgsText","previous","next","previousValue","nextValue","ToolInvocationTracker","_getTools","Record","_callbacks","Callbacks","_entries","Map","_skipExecuteStreamIds","Set","_humanInput","resolve","reject","reason","_executing","_settledResolvers","Array","_statuses","_ac","AbortController","_pendingRestore","_lastSnapshot","Snapshot","_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","messages","isRunning","isLoading","restoreFromLoading","previousIsRunning","_processMessages","reset","abort","finally","Promise","forEach","Error","size","push","resume","handlers","get","delete","_setStatus","getStatuses","ReadonlyMap","tools","Object","fromEntries","entries","map","name","tool","execute","wrappedTool","args","context","Parameters","NonNullable","has","set","add","_deleteStatus","resolvers","splice","meta","entry","_invokeOnResult","command","onResult","_invokeOnStatusesChange","onStatusesChange","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","ExecutionStatus","statuses"],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"sourcesContent":["declare const process: { env: { NODE_ENV?: string } };\n\nimport {\n createAssistantStreamController,\n type ToolCallStreamController,\n ToolResponse,\n unstable_toolResultStream,\n type Tool,\n type ToolModelContentPart,\n} 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\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 *\n * @deprecated Internal — for framework bindings; not a public API. May change without notice.\n */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTracker.Callbacks;\n\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: ToolInvocationTracker.Snapshot | null = null;\n private _isRunning = false;\n\n private _controller!: ReturnType<typeof createAssistantStreamController>[1];\n\n /**\n * Set when the assistant-stream pipeline has died (errored out via\n * `.pipeTo(...).catch(...)`). The next `setState` re-initializes the\n * pipeline and demotes 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: ToolInvocationTracker.Callbacks,\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: ToolInvocationTracker.Snapshot): 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\nexport namespace ToolInvocationTracker {\n export type ExecutionStatus = ToolExecutionStatus;\n\n export type Snapshot = {\n readonly messages: readonly ThreadMessage[];\n /** Whether the producing runtime is currently streaming new output. */\n readonly isRunning: boolean;\n /**\n * Whether the producing runtime is still loading historical state.\n * When `true`, every snapshot is treated as historical (no `streamCall` /\n * `execute` fires). When `false`, processing resumes as live.\n */\n readonly isLoading?: boolean;\n };\n\n export type Callbacks = {\n /**\n * Invoked when a client-side `execute()` returns a result and the runtime\n * needs to feed it back into the conversation.\n */\n onResult: (command: AddToolResultCommand) => void;\n /**\n * Invoked whenever the per-tool-call status map changes (executing /\n * interrupt / cleared). The callback receives a fresh map; mutating the\n * argument is not supported.\n */\n onStatusesChange: (\n statuses: ReadonlyMap<string, ToolExecutionStatus>,\n ) => void;\n };\n}\n"],"mappings":";;;;AAsDA,MAAM4B,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,kBAAkBJ,KAAAA,KAAaK,cAAcL,KAAAA,GAAW,OAAO;CACnE,OAAOrB,iBAAiByB,eAAeC,SAAS;AAClD;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAaC,wBAAb,MAAmC;CACjC;CACA;CAEA,2BAA4B,IAAIM,IAA2B;;;;;;;;;;;CAW3D,wCAAyC,IAAIE,IAAY;CACzD,8BAA+B,IAAIF,IAMjC;;CAEF,6BAA8B,I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MAAesG,MAAM7G,YACpB;MACrB,IAAI4H,QAAQxD,UAAU,KAAKK,iBAAiBmD,QAAQxD,QAAQ;MAC5D;KACF;KACA,KAAKlD,SAASmE,OAAOuC,QAAQpI,UAAU;KACvCqH,QAAQtG,KAAAA;IACV;IAEA,IAAI,CAACsG,OACHA,QAAQ,KAAKU,kBACXK,QAAQpI,YACRoI,QAAQnI,UACRmI,QAAQlI,WAAWa,KAAAA,CACrB;IAGF,KAAKoH,iBAAiBd,OAAOe,OAAO;IAEpC,IAAIA,QAAQlI,WAAWa,KAAAA,KAAa,CAACsG,MAAM7G,WAAW;KAIpD,MAAM,EAAEC,YAAY0I,qBAAqB9B;KACzC,IAAI,CAAC8B,kBAAkB;KACvB9B,MAAM7G,YAAY;KAClB6G,MAAM3G,eAAe;KACrByI,iBAAiBC,YACf,IAAIhK,aAAa;MACfc,QAAQkI,QAAQlI;MAChBE,UAAUgI,QAAQhI;MAClBD,SAASiI,QAAQjI;MACjB,GAAIiI,QAAQ/H,iBAAiBU,KAAAA,IACzB,EAAEV,cAAc+H,QAAQ/H,aAAa,IACrC,CAAC;KACP,CAAC,CACH;KACA8I,iBAAiBV,MAAM;IACzB;IAEA,IAAIL,QAAQxD,UAAU,KAAKK,iBAAiBmD,QAAQxD,QAAQ;GAC9D;EACF;CACF;AACF"}
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","ToolCallEntry","argsText","hasResult","controller","argsComplete","isArgsTextComplete","JSON","parse","parseArgsText","undefined","isEquivalentCompleteArgsText","previous","next","previousValue","nextValue","ToolInvocationTracker","_getTools","Record","_callbacks","Callbacks","_entries","Map","_skipExecuteStreamIds","Set","_humanInput","resolve","reject","reason","_executing","_settledResolvers","Array","_statuses","_ac","AbortController","_pendingRestore","_lastSnapshot","Snapshot","_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","messages","isRunning","isLoading","restoreFromLoading","previousIsRunning","_processMessages","reset","abort","finally","Promise","forEach","Error","size","push","resume","handlers","get","delete","_setStatus","getStatuses","ReadonlyMap","tools","Object","fromEntries","entries","map","name","tool","execute","wrappedTool","args","context","Parameters","NonNullable","has","set","add","_deleteStatus","resolvers","splice","meta","entry","_invokeOnResult","command","onResult","_invokeOnStatusesChange","onStatusesChange","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","ExecutionStatus","statuses"],"sources":["../../../src/runtimes/tool-invocations/ToolInvocationTracker.ts"],"sourcesContent":["declare const process: { env: { NODE_ENV?: string } };\n\nimport {\n createAssistantStreamController,\n type ToolCallStreamController,\n ToolResponse,\n unstable_toolResultStream,\n type Tool,\n type ToolModelContentPart,\n} 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\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 *\n * @deprecated Internal — for framework bindings; not a public API. May change without notice.\n */\nexport class ToolInvocationTracker {\n private readonly _getTools: () => Record<string, Tool> | undefined;\n private readonly _callbacks: ToolInvocationTracker.Callbacks;\n\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: ToolInvocationTracker.Snapshot | null = null;\n private _isRunning = false;\n\n private _controller!: ReturnType<typeof createAssistantStreamController>[1];\n\n /**\n * Set when the assistant-stream pipeline has died (errored out via\n * `.pipeTo(...).catch(...)`). The next `setState` re-initializes the\n * pipeline and demotes 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: ToolInvocationTracker.Callbacks,\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: ToolInvocationTracker.Snapshot): 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\nexport namespace ToolInvocationTracker {\n export type ExecutionStatus = ToolExecutionStatus;\n\n export type Snapshot = {\n readonly messages: readonly ThreadMessage[];\n /** Whether the producing runtime is currently streaming new output. */\n readonly isRunning: boolean;\n /**\n * Whether the producing runtime is still loading historical state.\n * When `true`, every snapshot is treated as historical (no `streamCall` /\n * `execute` fires). When `false`, processing resumes as live.\n */\n readonly isLoading?: boolean;\n };\n\n export type Callbacks = {\n /**\n * Invoked when a client-side `execute()` returns a result and the runtime\n * needs to feed it back into the conversation.\n */\n onResult: (command: AddToolResultCommand) => void;\n /**\n * Invoked whenever the per-tool-call status map changes (executing /\n * interrupt / cleared). The callback receives a fresh map; mutating the\n * argument is not supported.\n */\n onStatusesChange: (\n statuses: ReadonlyMap<string, ToolExecutionStatus>,\n ) => void;\n };\n}\n"],"mappings":";;;;AAsDA,MAAM4B,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,kBAAkBJ,KAAAA,KAAaK,cAAcL,KAAAA,GAAW,OAAO;CACnE,OAAOrB,iBAAiByB,eAAeC,SAAS;AAClD;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAaC,wBAAb,MAAmC;CACjC;CACA;CAEA,2BAA4B,IAAIM,IAA2B;;;;;;;;;;;CAW3D,wCAAyC,IAAIE,IAAY;CACzD,8BAA+B,IAAIF,IAMjC;;CAEF,6BAA8B,IAAIE,IAAY;CAC9C,oBAAwD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AesG,MAAM7G,YACpB;MACrB,IAAI4H,QAAQxD,UAAU,KAAKK,iBAAiBmD,QAAQxD,QAAQ;MAC5D;KACF;KACA,KAAKlD,SAASmE,OAAOuC,QAAQpI,UAAU;KACvCqH,QAAQtG,KAAAA;IACV;IAEA,IAAI,CAACsG,OACHA,QAAQ,KAAKU,kBACXK,QAAQpI,YACRoI,QAAQnI,UACRmI,QAAQlI,WAAWa,KAAAA,CACrB;IAGF,KAAKoH,iBAAiBd,OAAOe,OAAO;IAEpC,IAAIA,QAAQlI,WAAWa,KAAAA,KAAa,CAACsG,MAAM7G,WAAW;KAIpD,MAAM,EAAEC,YAAY0I,qBAAqB9B;KACzC,IAAI,CAAC8B,kBAAkB;KACvB9B,MAAM7G,YAAY;KAClB6G,MAAM3G,eAAe;KACrByI,iBAAiBC,YACf,IAAIhK,aAAa;MACfc,QAAQkI,QAAQlI;MAChBE,UAAUgI,QAAQhI;MAClBD,SAASiI,QAAQjI;MACjB,GAAIiI,QAAQ/H,iBAAiBU,KAAAA,IACzB,EAAEV,cAAc+H,QAAQ/H,aAAa,IACrC,CAAC;KACP,CAAC,CACH;KACA8I,iBAAiBV,MAAM;IACzB;IAEA,IAAIL,QAAQxD,UAAU,KAAKK,iBAAiBmD,QAAQxD,QAAQ;GAC9D;EACF;CACF;AACF"}
@@ -35,10 +35,12 @@ var BaseSubscribable = class {
35
35
  } catch (error) {
36
36
  errors.push(error);
37
37
  }
38
- if (errors.length > 0) if (errors.length === 1) throw errors[0];
39
- else {
40
- for (const error of errors) console.error(error);
41
- throw new AggregateError(errors);
38
+ if (errors.length > 0) {
39
+ if (errors.length === 1) throw errors[0];
40
+ else {
41
+ for (const error of errors) console.error(error);
42
+ throw new AggregateError(errors);
43
+ }
42
44
  }
43
45
  }
44
46
  };
@@ -1 +1 @@
1
- {"version":3,"file":"subscribable.js","names":["Unsubscribe","notifyEventListeners","SKIP_UPDATE","Symbol","Subscribable","subscribe","callback","SubscribableWithState","path","TPath","getState","TState","NestedSubscribable","EventSubscribable","event","TEvent","binding","unstable_on","payload","shallowEqual","objA","T","objB","undefined","keysA","Object","keys","length","key","valueA","valueB","is","BaseSubscribable","_subscribers","Set","add","delete","waitForUpdate","Promise","resolve","unsubscribe","_notifySubscribers","errors","error","push","console","AggregateError","BaseSubject","_subscriptions","_connection","isConnected","_connect","notifySubscribers","errorContext","_updateConnection","size","ShallowMemoizeSubject","constructor","state","Error","_previousState","_syncState","LazyMemoizeSubject","_previousStateDirty","newState","NestedSubscriptionSubject","outerSubscribe","lastState","innerUnsubscribe","onRuntimeUpdate","outerUnsubscribe","EventSubscriptionSubject","config"],"sources":["../../src/subscribable/subscribable.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\nimport { notifyEventListeners } from \"../utils/notify-event-listeners\";\n\nexport const SKIP_UPDATE = Symbol(\"skip-update\");\nexport type SKIP_UPDATE = typeof SKIP_UPDATE;\n\nexport type Subscribable = {\n subscribe: (callback: () => void) => Unsubscribe;\n};\n\nexport type SubscribableWithState<TState, TPath> = Subscribable & {\n path: TPath;\n getState: () => TState;\n};\n\nexport type NestedSubscribable<\n TState extends Subscribable | undefined,\n TPath,\n> = SubscribableWithState<TState, TPath>;\n\nexport type EventSubscribable<TEvent extends string> = {\n event: TEvent;\n binding: SubscribableWithState<\n | {\n unstable_on: (\n event: TEvent,\n callback: (payload?: unknown) => void,\n ) => Unsubscribe;\n }\n | undefined,\n unknown\n >;\n};\n\nfunction shallowEqual<T extends object>(\n objA: T | undefined,\n objB: T | undefined,\n) {\n if (objA === undefined && objB === undefined) return true;\n if (objA === undefined) return false;\n if (objB === undefined) return false;\n\n const keysA = Object.keys(objA);\n if (keysA.length !== Object.keys(objB).length) return false;\n\n for (const key of keysA) {\n const valueA = objA[key as keyof T];\n const valueB = objB[key as keyof T];\n if (!Object.is(valueA, valueB)) return false;\n }\n\n return true;\n}\n\nexport class BaseSubscribable {\n private _subscribers = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n public waitForUpdate() {\n return new Promise<void>((resolve) => {\n const unsubscribe = this.subscribe(() => {\n unsubscribe();\n resolve();\n });\n });\n }\n\n protected _notifySubscribers() {\n const errors = [];\n for (const callback of this._subscribers) {\n try {\n callback();\n } catch (error) {\n errors.push(error);\n }\n }\n\n if (errors.length > 0) {\n if (errors.length === 1) {\n throw errors[0];\n } else {\n for (const error of errors) {\n console.error(error);\n }\n throw new AggregateError(errors);\n }\n }\n }\n}\n\n// lazy connect/disconnect: only opens upstream subscription while it has subscribers\nexport abstract class BaseSubject {\n private _subscriptions = new Set<(payload?: unknown) => void>();\n private _connection: Unsubscribe | undefined;\n\n protected get isConnected() {\n return !!this._connection;\n }\n\n protected abstract _connect(): Unsubscribe;\n\n protected notifySubscribers(payload?: unknown, errorContext?: string) {\n if (errorContext) {\n notifyEventListeners(this._subscriptions, payload, errorContext);\n return;\n }\n\n for (const callback of this._subscriptions) callback(payload);\n }\n\n private _updateConnection() {\n if (this._subscriptions.size > 0) {\n if (this._connection) return;\n this._connection = this._connect();\n } else {\n this._connection?.();\n this._connection = undefined;\n }\n }\n\n public subscribe(callback: (payload?: unknown) => void) {\n this._subscriptions.add(callback);\n this._updateConnection();\n\n return () => {\n this._subscriptions.delete(callback);\n this._updateConnection();\n };\n }\n}\n\nexport class ShallowMemoizeSubject<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>;\n\n constructor(binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>) {\n super();\n this.binding = binding;\n const state = binding.getState();\n if (state === SKIP_UPDATE)\n throw new Error(\"Entry not available in the store\");\n this._previousState = state;\n }\n\n private _previousState: TState;\n public getState = () => {\n if (!this.isConnected) this._syncState();\n return this._previousState;\n };\n\n private _syncState() {\n const state = this.binding.getState();\n if (state === SKIP_UPDATE) return false;\n if (shallowEqual(state, this._previousState)) return false;\n this._previousState = state;\n return true;\n }\n\n protected _connect() {\n const callback = () => {\n if (this._syncState()) {\n this.notifySubscribers();\n }\n };\n\n return this.binding.subscribe(callback);\n }\n}\n\nexport class LazyMemoizeSubject<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>;\n\n constructor(binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>) {\n super();\n this.binding = binding;\n }\n\n private _previousStateDirty = true;\n private _previousState: TState | undefined;\n public getState = () => {\n if (!this.isConnected || this._previousStateDirty) {\n const newState = this.binding.getState();\n if (newState !== SKIP_UPDATE) {\n this._previousState = newState;\n }\n this._previousStateDirty = false;\n }\n if (this._previousState === undefined)\n throw new Error(\"Entry not available in the store\");\n return this._previousState;\n };\n\n protected _connect() {\n const callback = () => {\n this._previousStateDirty = true;\n this.notifySubscribers();\n };\n\n return this.binding.subscribe(callback);\n }\n}\n\nexport class NestedSubscriptionSubject<\n TState extends Subscribable | undefined,\n TPath,\n>\n extends BaseSubject\n implements\n SubscribableWithState<TState, TPath>,\n NestedSubscribable<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n private binding: NestedSubscribable<TState, TPath>;\n\n constructor(binding: NestedSubscribable<TState, TPath>) {\n super();\n this.binding = binding;\n }\n\n public getState() {\n return this.binding.getState();\n }\n\n public outerSubscribe(callback: () => void) {\n return this.binding.subscribe(callback);\n }\n\n protected _connect(): Unsubscribe {\n const callback = () => {\n this.notifySubscribers();\n };\n\n let lastState = this.binding.getState();\n let innerUnsubscribe = lastState?.subscribe(callback);\n const onRuntimeUpdate = () => {\n const newState = this.binding.getState();\n if (newState === lastState) return;\n lastState = newState;\n\n innerUnsubscribe?.();\n innerUnsubscribe = newState?.subscribe(callback);\n\n callback();\n };\n\n const outerUnsubscribe = this.outerSubscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n\nexport class EventSubscriptionSubject<\n TEvent extends string,\n> extends BaseSubject {\n private config: EventSubscribable<TEvent>;\n\n constructor(config: EventSubscribable<TEvent>) {\n super();\n this.config = config;\n }\n\n public getState() {\n return this.config.binding.getState();\n }\n\n public outerSubscribe(callback: () => void) {\n return this.config.binding.subscribe(callback);\n }\n\n protected _connect(): Unsubscribe {\n const errorContext = `Runtime event \"${this.config.event}\"`;\n const callback = (payload?: unknown) => {\n this.notifySubscribers(payload, errorContext);\n };\n\n let lastState = this.config.binding.getState();\n let innerUnsubscribe = lastState?.unstable_on(this.config.event, callback);\n const onRuntimeUpdate = () => {\n const newState = this.config.binding.getState();\n if (newState === lastState) return;\n lastState = newState;\n\n innerUnsubscribe?.();\n innerUnsubscribe = newState?.unstable_on(this.config.event, callback);\n };\n\n const outerUnsubscribe = this.outerSubscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n"],"mappings":";;AAGA,MAAaE,cAAcC,OAAO,aAAa;AA+B/C,SAASgB,aACPC,MACAE,MACA;CACA,IAAIF,SAASG,KAAAA,KAAaD,SAASC,KAAAA,GAAW,OAAO;CACrD,IAAIH,SAASG,KAAAA,GAAW,OAAO;CAC/B,IAAID,SAASC,KAAAA,GAAW,OAAO;CAE/B,MAAMC,QAAQC,OAAOC,KAAKN,IAAI;CAC9B,IAAII,MAAMG,WAAWF,OAAOC,KAAKJ,IAAI,CAAC,CAACK,QAAQ,OAAO;CAEtD,KAAK,MAAMC,OAAOJ,OAAO;EACvB,MAAMK,SAAST,KAAKQ;EACpB,MAAME,SAASR,KAAKM;EACpB,IAAI,CAACH,OAAOM,GAAGF,QAAQC,MAAM,GAAG,OAAO;CACzC;CAEA,OAAO;AACT;AAEA,IAAaE,mBAAb,MAA8B;CAC5B,+BAAuB,IAAIE,IAAgB;CAE3C,UAAiB5B,UAAmC;EAClD,KAAK2B,aAAa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M+D,wBAAwB;GAC5B,MAAML,WAAW,KAAKQ,OAAOxD,QAAQN,SAAS;GAC9C,IAAIsD,aAAaG,WAAW;GAC5BA,YAAYH;GAEZI,mBAAmB;GACnBA,mBAAmBJ,UAAU/C,YAAY,KAAKuD,OAAO1D,OAAOR,QAAQ;EACtE;EAEA,MAAMgE,mBAAmB,KAAKJ,eAAeG,eAAe;EAC5D,aAAa;GACXC,mBAAmB;GACnBF,mBAAmB;EACrB;CACF;AACF"}
1
+ {"version":3,"file":"subscribable.js","names":["Unsubscribe","notifyEventListeners","SKIP_UPDATE","Symbol","Subscribable","subscribe","callback","SubscribableWithState","path","TPath","getState","TState","NestedSubscribable","EventSubscribable","event","TEvent","binding","unstable_on","payload","shallowEqual","objA","T","objB","undefined","keysA","Object","keys","length","key","valueA","valueB","is","BaseSubscribable","_subscribers","Set","add","delete","waitForUpdate","Promise","resolve","unsubscribe","_notifySubscribers","errors","error","push","console","AggregateError","BaseSubject","_subscriptions","_connection","isConnected","_connect","notifySubscribers","errorContext","_updateConnection","size","ShallowMemoizeSubject","constructor","state","Error","_previousState","_syncState","LazyMemoizeSubject","_previousStateDirty","newState","NestedSubscriptionSubject","outerSubscribe","lastState","innerUnsubscribe","onRuntimeUpdate","outerUnsubscribe","EventSubscriptionSubject","config"],"sources":["../../src/subscribable/subscribable.ts"],"sourcesContent":["import type { Unsubscribe } from \"../types/unsubscribe\";\nimport { notifyEventListeners } from \"../utils/notify-event-listeners\";\n\nexport const SKIP_UPDATE = Symbol(\"skip-update\");\nexport type SKIP_UPDATE = typeof SKIP_UPDATE;\n\nexport type Subscribable = {\n subscribe: (callback: () => void) => Unsubscribe;\n};\n\nexport type SubscribableWithState<TState, TPath> = Subscribable & {\n path: TPath;\n getState: () => TState;\n};\n\nexport type NestedSubscribable<\n TState extends Subscribable | undefined,\n TPath,\n> = SubscribableWithState<TState, TPath>;\n\nexport type EventSubscribable<TEvent extends string> = {\n event: TEvent;\n binding: SubscribableWithState<\n | {\n unstable_on: (\n event: TEvent,\n callback: (payload?: unknown) => void,\n ) => Unsubscribe;\n }\n | undefined,\n unknown\n >;\n};\n\nfunction shallowEqual<T extends object>(\n objA: T | undefined,\n objB: T | undefined,\n) {\n if (objA === undefined && objB === undefined) return true;\n if (objA === undefined) return false;\n if (objB === undefined) return false;\n\n const keysA = Object.keys(objA);\n if (keysA.length !== Object.keys(objB).length) return false;\n\n for (const key of keysA) {\n const valueA = objA[key as keyof T];\n const valueB = objB[key as keyof T];\n if (!Object.is(valueA, valueB)) return false;\n }\n\n return true;\n}\n\nexport class BaseSubscribable {\n private _subscribers = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n public waitForUpdate() {\n return new Promise<void>((resolve) => {\n const unsubscribe = this.subscribe(() => {\n unsubscribe();\n resolve();\n });\n });\n }\n\n protected _notifySubscribers() {\n const errors = [];\n for (const callback of this._subscribers) {\n try {\n callback();\n } catch (error) {\n errors.push(error);\n }\n }\n\n if (errors.length > 0) {\n if (errors.length === 1) {\n throw errors[0];\n } else {\n for (const error of errors) {\n console.error(error);\n }\n throw new AggregateError(errors);\n }\n }\n }\n}\n\n// lazy connect/disconnect: only opens upstream subscription while it has subscribers\nexport abstract class BaseSubject {\n private _subscriptions = new Set<(payload?: unknown) => void>();\n private _connection: Unsubscribe | undefined;\n\n protected get isConnected() {\n return !!this._connection;\n }\n\n protected abstract _connect(): Unsubscribe;\n\n protected notifySubscribers(payload?: unknown, errorContext?: string) {\n if (errorContext) {\n notifyEventListeners(this._subscriptions, payload, errorContext);\n return;\n }\n\n for (const callback of this._subscriptions) callback(payload);\n }\n\n private _updateConnection() {\n if (this._subscriptions.size > 0) {\n if (this._connection) return;\n this._connection = this._connect();\n } else {\n this._connection?.();\n this._connection = undefined;\n }\n }\n\n public subscribe(callback: (payload?: unknown) => void) {\n this._subscriptions.add(callback);\n this._updateConnection();\n\n return () => {\n this._subscriptions.delete(callback);\n this._updateConnection();\n };\n }\n}\n\nexport class ShallowMemoizeSubject<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>;\n\n constructor(binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>) {\n super();\n this.binding = binding;\n const state = binding.getState();\n if (state === SKIP_UPDATE)\n throw new Error(\"Entry not available in the store\");\n this._previousState = state;\n }\n\n private _previousState: TState;\n public getState = () => {\n if (!this.isConnected) this._syncState();\n return this._previousState;\n };\n\n private _syncState() {\n const state = this.binding.getState();\n if (state === SKIP_UPDATE) return false;\n if (shallowEqual(state, this._previousState)) return false;\n this._previousState = state;\n return true;\n }\n\n protected _connect() {\n const callback = () => {\n if (this._syncState()) {\n this.notifySubscribers();\n }\n };\n\n return this.binding.subscribe(callback);\n }\n}\n\nexport class LazyMemoizeSubject<TState extends object, TPath>\n extends BaseSubject\n implements SubscribableWithState<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n private binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>;\n\n constructor(binding: SubscribableWithState<TState | SKIP_UPDATE, TPath>) {\n super();\n this.binding = binding;\n }\n\n private _previousStateDirty = true;\n private _previousState: TState | undefined;\n public getState = () => {\n if (!this.isConnected || this._previousStateDirty) {\n const newState = this.binding.getState();\n if (newState !== SKIP_UPDATE) {\n this._previousState = newState;\n }\n this._previousStateDirty = false;\n }\n if (this._previousState === undefined)\n throw new Error(\"Entry not available in the store\");\n return this._previousState;\n };\n\n protected _connect() {\n const callback = () => {\n this._previousStateDirty = true;\n this.notifySubscribers();\n };\n\n return this.binding.subscribe(callback);\n }\n}\n\nexport class NestedSubscriptionSubject<\n TState extends Subscribable | undefined,\n TPath,\n>\n extends BaseSubject\n implements\n SubscribableWithState<TState, TPath>,\n NestedSubscribable<TState, TPath>\n{\n public get path() {\n return this.binding.path;\n }\n\n private binding: NestedSubscribable<TState, TPath>;\n\n constructor(binding: NestedSubscribable<TState, TPath>) {\n super();\n this.binding = binding;\n }\n\n public getState() {\n return this.binding.getState();\n }\n\n public outerSubscribe(callback: () => void) {\n return this.binding.subscribe(callback);\n }\n\n protected _connect(): Unsubscribe {\n const callback = () => {\n this.notifySubscribers();\n };\n\n let lastState = this.binding.getState();\n let innerUnsubscribe = lastState?.subscribe(callback);\n const onRuntimeUpdate = () => {\n const newState = this.binding.getState();\n if (newState === lastState) return;\n lastState = newState;\n\n innerUnsubscribe?.();\n innerUnsubscribe = newState?.subscribe(callback);\n\n callback();\n };\n\n const outerUnsubscribe = this.outerSubscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n\nexport class EventSubscriptionSubject<\n TEvent extends string,\n> extends BaseSubject {\n private config: EventSubscribable<TEvent>;\n\n constructor(config: EventSubscribable<TEvent>) {\n super();\n this.config = config;\n }\n\n public getState() {\n return this.config.binding.getState();\n }\n\n public outerSubscribe(callback: () => void) {\n return this.config.binding.subscribe(callback);\n }\n\n protected _connect(): Unsubscribe {\n const errorContext = `Runtime event \"${this.config.event}\"`;\n const callback = (payload?: unknown) => {\n this.notifySubscribers(payload, errorContext);\n };\n\n let lastState = this.config.binding.getState();\n let innerUnsubscribe = lastState?.unstable_on(this.config.event, callback);\n const onRuntimeUpdate = () => {\n const newState = this.config.binding.getState();\n if (newState === lastState) return;\n lastState = newState;\n\n innerUnsubscribe?.();\n innerUnsubscribe = newState?.unstable_on(this.config.event, callback);\n };\n\n const outerUnsubscribe = this.outerSubscribe(onRuntimeUpdate);\n return () => {\n outerUnsubscribe?.();\n innerUnsubscribe?.();\n };\n }\n}\n"],"mappings":";;AAGA,MAAaE,cAAcC,OAAO,aAAa;AA+B/C,SAASgB,aACPC,MACAE,MACA;CACA,IAAIF,SAASG,KAAAA,KAAaD,SAASC,KAAAA,GAAW,OAAO;CACrD,IAAIH,SAASG,KAAAA,GAAW,OAAO;CAC/B,IAAID,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