@assistant-ui/core 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/internal.d.ts +1 -2
- package/dist/internal.js +1 -2
- package/dist/react/AssistantProvider.d.ts +1 -1
- package/dist/react/AssistantProvider.d.ts.map +1 -1
- package/dist/react/AssistantProvider.js +35 -9
- package/dist/react/AssistantProvider.js.map +1 -1
- package/dist/react/AssistantRuntimeProvider.d.ts +1 -1
- package/dist/react/AssistantRuntimeProvider.js +1 -1
- package/dist/react/RuntimeAdapter.js +2 -2
- package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js +17 -33
- package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
- package/dist/react/client/DataRenderers.js +1 -1
- package/dist/react/client/Interactables.js +1 -1
- package/dist/react/client/Tools.js +2 -2
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.js +2 -1
- package/dist/react/interactables-legacy/Interactables.js +1 -1
- package/dist/react/interactables-legacy/useAssistantInteractable.js +1 -1
- package/dist/react/interactables-legacy/useInteractableState.js +2 -2
- package/dist/react/model-context/useAssistantContext.js +1 -1
- package/dist/react/model-context/useAssistantDataUI.js +2 -2
- package/dist/react/model-context/useAssistantInstructions.js +2 -2
- package/dist/react/model-context/useAssistantTool.js +2 -2
- package/dist/react/model-context/useAssistantToolUI.js +2 -2
- package/dist/react/model-context/useAuiToolOverrides.js +1 -1
- package/dist/react/model-context/useInlineRender.js +1 -1
- package/dist/react/model-context/useInteractable.d.ts.map +1 -1
- package/dist/react/model-context/useInteractable.js +3 -5
- package/dist/react/model-context/useInteractable.js.map +1 -1
- package/dist/react/model-context/useInteractableState.js +2 -2
- package/dist/react/model-context/useInteractableVersions.js +2 -2
- package/dist/react/model-context/useToolArgsStatus.js +2 -2
- package/dist/react/primitive-hooks/useActionBarCopy.js +2 -2
- package/dist/react/primitive-hooks/useActionBarEdit.js +2 -2
- package/dist/react/primitive-hooks/useActionBarFeedback.js +2 -2
- package/dist/react/primitive-hooks/useActionBarReload.js +2 -2
- package/dist/react/primitive-hooks/useActionBarSpeak.js +2 -2
- package/dist/react/primitive-hooks/useActionBarStopSpeaking.js +2 -2
- package/dist/react/primitive-hooks/useBranchPickerNext.js +2 -2
- package/dist/react/primitive-hooks/useBranchPickerPrevious.js +2 -2
- package/dist/react/primitive-hooks/useComposerAddAttachment.js +2 -2
- package/dist/react/primitive-hooks/useComposerCancel.js +2 -2
- package/dist/react/primitive-hooks/useComposerDictate.js +2 -2
- package/dist/react/primitive-hooks/useComposerSend.js +2 -2
- package/dist/react/primitive-hooks/useEditComposerCancel.js +2 -2
- package/dist/react/primitive-hooks/useEditComposerSend.js +2 -2
- package/dist/react/primitive-hooks/useMessageBranching.js +2 -2
- package/dist/react/primitive-hooks/useMessageReload.js +2 -2
- package/dist/react/primitive-hooks/useSuggestionTrigger.js +2 -2
- package/dist/react/primitive-hooks/useThreadListItemArchive.js +2 -2
- package/dist/react/primitive-hooks/useThreadListItemDelete.js +2 -2
- package/dist/react/primitive-hooks/useThreadListItemTrigger.js +2 -2
- package/dist/react/primitive-hooks/useThreadListItemUnarchive.js +2 -2
- package/dist/react/primitive-hooks/useThreadListLoadMore.js +2 -2
- package/dist/react/primitive-hooks/useThreadListNew.js +2 -2
- package/dist/react/primitive-hooks/useThreadMessageIds.js +1 -1
- package/dist/react/primitive-hooks/useVoice.js +2 -2
- package/dist/react/primitives/chainOfThought/ChainOfThoughtParts.js +2 -2
- package/dist/react/primitives/composer/ComposerAttachments.js +2 -2
- package/dist/react/primitives/composer/ComposerIf.js +1 -1
- package/dist/react/primitives/composer/ComposerQueue.js +1 -1
- package/dist/react/primitives/generativeUI/GenerativeUI.js +2 -2
- package/dist/react/primitives/message/MessageAttachments.js +2 -2
- package/dist/react/primitives/message/MessageGroupedParts.js +1 -1
- package/dist/react/primitives/message/MessageParts.js +2 -2
- package/dist/react/primitives/message/MessageQuote.js +2 -2
- package/dist/react/primitives/part/PartMessages.js +2 -2
- package/dist/react/primitives/thread/ThreadMessages.js +2 -2
- package/dist/react/primitives/thread/ThreadSuggestions.js +2 -2
- package/dist/react/primitives/threadList/ThreadListItems.js +2 -2
- package/dist/react/primitives/threadListItem/ThreadListItemTitle.js +1 -1
- package/dist/react/providers/AttachmentByIndexProvider.js +1 -1
- package/dist/react/providers/ChainOfThoughtByIndicesProvider.js +1 -1
- package/dist/react/providers/ChainOfThoughtPartByIndexProvider.js +1 -1
- package/dist/react/providers/MessageByIdProvider.js +1 -1
- package/dist/react/providers/MessageByIndexProvider.js +1 -1
- package/dist/react/providers/PartByIndexProvider.js +1 -1
- package/dist/react/providers/QueueItemByIndexProvider.js +1 -1
- package/dist/react/providers/ReadonlyThreadProvider.js +2 -2
- package/dist/react/providers/SuggestionByIndexProvider.js +1 -1
- package/dist/react/providers/TextMessagePartProvider.js +2 -2
- package/dist/react/providers/ThreadListItemByIndexProvider.js +1 -1
- package/dist/react/providers/ThreadListItemRuntimeProvider.js +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +14 -13
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +3 -0
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +22 -12
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/RuntimeAdapterProvider.js +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +9 -23
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/external-message-converter.js +1 -1
- package/dist/react/runtimes/useExternalStoreRuntime.js +1 -1
- package/dist/react/runtimes/useExternalStoreSharedOptions.js +1 -1
- package/dist/react/runtimes/useLocalRuntime.js +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js +7 -13
- package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
- package/dist/react/utils/useJSONEqual.js +1 -1
- package/dist/runtime/utils/thread-message-like.js +2 -2
- package/dist/runtime/utils/thread-message-like.js.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +4 -3
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/remote-thread-list/types.d.ts +5 -4
- package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
- package/dist/store/clients/chain-of-thought-client.js +1 -1
- package/dist/store/clients/model-context-client.js +1 -1
- package/dist/store/clients/no-op-composer-client.js +1 -1
- package/dist/store/clients/suggestions.js +2 -2
- package/dist/store/clients/thread-message-client.js +2 -2
- package/dist/store/runtime-clients/composer-runtime-client.js +2 -2
- package/dist/store/runtime-clients/message-runtime-client.js +2 -2
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js +2 -2
- package/dist/store/runtime-clients/thread-list-runtime-client.js +2 -2
- package/dist/store/runtime-clients/thread-runtime-client.js +2 -2
- package/dist/store/scopes/thread.d.ts +1 -1
- package/dist/store/scopes/thread.d.ts.map +1 -1
- package/dist/utils/data-url.js +2 -2
- package/dist/utils/data-url.js.map +1 -1
- package/package.json +4 -4
- package/src/internal.ts +0 -7
- package/src/react/AssistantProvider.tsx +28 -15
- package/src/react/AssistantRuntimeProvider.test.tsx +101 -0
- package/src/react/adapters/LocalStorageThreadListAdapter.tsx +28 -7
- package/src/react/index.ts +4 -0
- package/src/react/model-context/useInteractable.ts +2 -6
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +16 -13
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +53 -10
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +7 -5
- package/src/react/runtimes/useRemoteThreadListRuntime.ts +9 -15
- package/src/runtime/utils/thread-message-like.ts +2 -2
- package/src/runtimes/local/local-thread-runtime-core.test.ts +38 -0
- package/src/runtimes/local/local-thread-runtime-core.ts +6 -3
- package/src/runtimes/remote-thread-list/types.ts +5 -4
- package/src/store/scopes/thread.ts +1 -1
- package/src/tests/remote-thread-list-reactive-threadId.test.ts +0 -92
- package/src/tests/thread-message-like.test.ts +15 -0
- package/src/tests/useRemoteThreadListRuntime-controlled.test.tsx +293 -0
- package/src/utils/data-url.test.ts +26 -2
- package/src/utils/data-url.ts +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_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","_runAppend","finally","notifyIdle","subscribe","_notifySubscribers","adapter","clear","_loadPromise","__internal_load","promise","load","repo","repository","import","messages","length","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","at","willRun","role","enqueue","steer","getQueueItems","items","steerQueueItem","queueItemId","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","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","addToolResult","toolCallId","result","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig } from \"../../types/message\";\nimport { toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n\n 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 void this._runAppend(message)\n .finally(() => {\n this._queueRunInFlight = false;\n this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue.adapter.clear(\"cancel-run\");\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n this._queue.adapter.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n if (this._queue && !isTail) this._queue.adapter.clear(\"edit\");\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string): void {\n this._queue?.adapter.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private async _runAppend(message: AppendMessage): Promise<void> {\n this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n // 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 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 // queue-driven runs release from the driver settle handler; a direct\n // run (regenerate, resume) releases here\n if (!this._queueRunInFlight) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n 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 this.abortController = new AbortController();\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state !== undefined\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n 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 = this.abortController.signal;\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: abortSignal.aborted\n ? { type: \"incomplete\", reason: \"cancelled\" }\n : { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n if (e instanceof AbortError) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"error\",\n error: toAssistantError(e),\n },\n });\n\n throw e;\n }\n } finally {\n this.abortController = null;\n\n 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 this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (!c.result) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } 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":";;;;;;;;;AAmCA,IAAMwB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUhB,sBAEV;CACE,eAA+B;EAC7BkB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAE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oD,WAAWuG,WAAW5L,QAAQwB,EAAE;EAC1D,KAAK6D,WAAW0B,mBAAmB9E,UAAUjC,OAAO;EACpD,KAAK6E,mBAAmB;EAExB,IACE,KAAKQ,WAAWQ,WAAW7F,QAAQwB,MACnCjD,eAAeyB,SAAS,KAAKqC,SAASwG,uBAAuB,GAE7D,KAAKN,SAAStG,UAAUjC,SAAS,KAAK2C,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKZ,sBAAsBC,UAAUjC,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","EMPTY_QUEUE_ITEMS","QueueItemState","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_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","_runAppend","finally","notifyIdle","subscribe","_notifySubscribers","adapter","clear","_loadPromise","__internal_load","promise","load","repo","repository","import","messages","length","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","at","willRun","role","enqueue","steer","getQueueItems","items","steerQueueItem","queueItemId","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","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","addToolResult","toolCallId","result","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig } from \"../../types/message\";\nimport { toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n\n 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 void this._runAppend(message)\n .finally(() => {\n this._queueRunInFlight = false;\n this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue.adapter.clear(\"cancel-run\");\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n }\n\n private _loadPromise: Promise<void> | undefined;\n public __internal_load() {\n if (this._loadPromise) return this._loadPromise;\n\n const promise = this.adapters.history?.load() ?? Promise.resolve(null);\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n this._queue.adapter.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n if (this._queue && !isTail) this._queue.adapter.clear(\"edit\");\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string): void {\n this._queue?.adapter.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private async _runAppend(message: AppendMessage): Promise<void> {\n this.ensureInitialized();\n\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n await this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n });\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n // 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 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 // queue-driven runs release from the driver settle handler; a direct\n // run (regenerate, resume) releases here\n if (!this._queueRunInFlight) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n 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 this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n this._queue?.adapter.clear(\"cancel-run\");\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (!c.result) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } 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":";;;;;;;;;AAmCA,IAAMwB,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUhB,sBAEV;CACE,eAA+B;EAC7BkB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAE5B,iCAAyB,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AAWuG,WAAW5L,QAAQwB,EAAE;EAC1D,KAAK6D,WAAW0B,mBAAmB9E,UAAUjC,OAAO;EACpD,KAAK6E,mBAAmB;EAExB,IACE,KAAKQ,WAAWQ,WAAW7F,QAAQwB,MACnCjD,eAAeyB,SAAS,KAAKqC,SAASwG,uBAAuB,GAE7D,KAAKN,SAAStG,UAAUjC,SAAS,KAAK2C,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKZ,sBAAsBC,UAAUjC,OAAO;CAEhD;AACF"}
|
|
@@ -62,10 +62,11 @@ type RemoteThreadListOptions = {
|
|
|
62
62
|
*/
|
|
63
63
|
threadId?: string | undefined;
|
|
64
64
|
/**
|
|
65
|
-
* Called whenever the active thread's canonical (remote)
|
|
66
|
-
* value can be treated as a managed/controlled variable (e.g.
|
|
67
|
-
* URL query param).
|
|
68
|
-
*
|
|
65
|
+
* Called whenever the runtime changes the active thread's canonical (remote)
|
|
66
|
+
* ID, so the value can be treated as a managed/controlled variable (e.g.
|
|
67
|
+
* synced to a URL query param). Changes initiated by the controlled
|
|
68
|
+
* `threadId` option are not echoed back. Together these options form the
|
|
69
|
+
* controlled pattern: `threadId` in, `onThreadIdChange` out.
|
|
69
70
|
*
|
|
70
71
|
* Only the settled remote ID is emitted: while a freshly created thread is
|
|
71
72
|
* still optimistic (no remote ID yet) the value is `undefined`, and the real
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/types.ts"],"mappings":";;;;;KAKY;EACV;EACA;;KAGU;WACD;WACA;WACA;WACA;WACA,gBAAgB;WAChB,SAAS;;KAGR;EACV,SAAS;EACT;;KAGU;EACV;;KAGU;EACV,KAAK,SAAS,8BAA8B,QAAQ;EAEpD,OAAO,kBAAkB,mBAAmB;EAC5C,cACE,kBACA,QAAQ,sCACP;EACH,QAAQ,mBAAmB;EAC3B,UAAU,mBAAmB;EAC7B,OAAO,mBAAmB;EAC1B,WAAW,mBAAmB,QAAQ;EACtC,cACE,kBACA,4BAA4B,kBAC3B,QAAQ;EACX,MAAM,mBAAmB,QAAQ;;;;;;;;;;;EAYjC,oBAAoB,cAAc;;KAGxB;EACV,mBAAmB;EACnB,SAAS;;;;;;;;EAST;;;;;;EAOA
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/runtimes/remote-thread-list/types.ts"],"mappings":";;;;;KAKY;EACV;EACA;;KAGU;WACD;WACA;WACA;WACA;WACA,gBAAgB;WAChB,SAAS;;KAGR;EACV,SAAS;EACT;;KAGU;EACV;;KAGU;EACV,KAAK,SAAS,8BAA8B,QAAQ;EAEpD,OAAO,kBAAkB,mBAAmB;EAC5C,cACE,kBACA,QAAQ,sCACP;EACH,QAAQ,mBAAmB;EAC3B,UAAU,mBAAmB;EAC7B,OAAO,mBAAmB;EAC1B,WAAW,mBAAmB,QAAQ;EACtC,cACE,kBACA,4BAA4B,kBAC3B,QAAQ;EACX,MAAM,mBAAmB,QAAQ;;;;;;;;;;;EAYjC,oBAAoB,cAAc;;KAGxB;EACV,mBAAmB;EACnB,SAAS;;;;;;;;EAST;;;;;;EAOA;;;;;;;;;;;;;EAcA,qBAAqB;;;;;;EAOrB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { useState } from "@assistant-ui/tap/react-shim";
|
|
2
1
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
2
|
+
import { useState } from "@assistant-ui/tap/react-shim";
|
|
3
3
|
import { resource } from "@assistant-ui/tap";
|
|
4
4
|
//#region src/store/clients/chain-of-thought-client.ts
|
|
5
5
|
const COMPLETE_STATUS = Object.freeze({ type: "complete" });
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CompositeContextProvider } from "../../utils/composite-context-provider.js";
|
|
2
|
-
import { useEffect, useState } from "@assistant-ui/tap/react-shim";
|
|
3
2
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
3
|
+
import { useEffect, useState } from "@assistant-ui/tap/react-shim";
|
|
4
4
|
import { resource } from "@assistant-ui/tap";
|
|
5
5
|
//#region src/store/clients/model-context-client.ts
|
|
6
6
|
const EMPTY_TOOL_NAMES = [];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import "@assistant-ui/tap/react-shim";
|
|
2
1
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
2
|
+
import "@assistant-ui/tap/react-shim";
|
|
3
3
|
import { resource } from "@assistant-ui/tap";
|
|
4
4
|
//#region src/store/clients/no-op-composer-client.ts
|
|
5
5
|
const useNoOpComposerClient = (t0) => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { useClientLookup } from "@assistant-ui/store";
|
|
2
|
-
import { useState } from "@assistant-ui/tap/react-shim";
|
|
3
1
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
2
|
+
import { useState } from "@assistant-ui/tap/react-shim";
|
|
3
|
+
import { useClientLookup } from "@assistant-ui/store";
|
|
4
4
|
import { resource, withKey } from "@assistant-ui/tap";
|
|
5
5
|
//#region src/store/clients/suggestions.ts
|
|
6
6
|
const useSuggestionClient = (state) => {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { getThreadMessageText } from "../../utils/text.js";
|
|
2
2
|
import { NoOpComposerClient } from "./no-op-composer-client.js";
|
|
3
|
-
import { useClientLookup } from "@assistant-ui/store";
|
|
4
|
-
import { useState } from "@assistant-ui/tap/react-shim";
|
|
5
3
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
4
|
+
import { useState } from "@assistant-ui/tap/react-shim";
|
|
5
|
+
import { useClientLookup } from "@assistant-ui/store";
|
|
6
6
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
7
7
|
//#region src/store/clients/thread-message-client.ts
|
|
8
8
|
const useThreadMessagePartClient = (t0) => {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { useSubscribable } from "./useSubscribable.js";
|
|
2
2
|
import { AttachmentRuntimeClient } from "./attachment-runtime-client.js";
|
|
3
|
-
import { useAssistantEmit, useClientLookup } from "@assistant-ui/store";
|
|
4
|
-
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
5
3
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
4
|
+
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
5
|
+
import { useAssistantEmit, useClientLookup } from "@assistant-ui/store";
|
|
6
6
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
7
7
|
//#region src/store/runtime-clients/composer-runtime-client.ts
|
|
8
8
|
const useComposerAttachmentClientByIndex = (t0) => {
|
|
@@ -3,9 +3,9 @@ import { AttachmentRuntimeClient } from "./attachment-runtime-client.js";
|
|
|
3
3
|
import { MessagePartClient } from "./message-part-runtime-client.js";
|
|
4
4
|
import { ComposerClient } from "./composer-runtime-client.js";
|
|
5
5
|
import { liveRef } from "./liveRef.js";
|
|
6
|
-
import { useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
7
|
-
import { useState } from "@assistant-ui/tap/react-shim";
|
|
8
6
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
7
|
+
import { useState } from "@assistant-ui/tap/react-shim";
|
|
8
|
+
import { useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
9
9
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
10
10
|
//#region src/store/runtime-clients/message-runtime-client.ts
|
|
11
11
|
const useMessageAttachmentClientByIndex = (t0) => {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useSubscribable } from "./useSubscribable.js";
|
|
2
|
-
import { useAssistantEmit } from "@assistant-ui/store";
|
|
3
|
-
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
4
2
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
3
|
+
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
4
|
+
import { useAssistantEmit } from "@assistant-ui/store";
|
|
5
5
|
import { resource } from "@assistant-ui/tap";
|
|
6
6
|
//#region src/store/runtime-clients/thread-list-item-runtime-client.ts
|
|
7
7
|
const useThreadListItemClient = (t0) => {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { useSubscribable } from "./useSubscribable.js";
|
|
2
2
|
import { ThreadClient } from "./thread-runtime-client.js";
|
|
3
3
|
import { ThreadListItemClient } from "./thread-list-item-runtime-client.js";
|
|
4
|
-
import { useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
5
|
-
import "@assistant-ui/tap/react-shim";
|
|
6
4
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
5
|
+
import "@assistant-ui/tap/react-shim";
|
|
6
|
+
import { useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
7
7
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
8
8
|
//#region src/store/runtime-clients/thread-list-runtime-client.ts
|
|
9
9
|
const useThreadListItemClientById = (t0) => {
|
|
@@ -2,9 +2,9 @@ import { useSubscribable } from "./useSubscribable.js";
|
|
|
2
2
|
import { ComposerClient } from "./composer-runtime-client.js";
|
|
3
3
|
import { liveRef } from "./liveRef.js";
|
|
4
4
|
import { MessageClient } from "./message-runtime-client.js";
|
|
5
|
-
import { useAssistantEmit, useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
6
|
-
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
7
5
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
6
|
+
import { useEffect } from "@assistant-ui/tap/react-shim";
|
|
7
|
+
import { useAssistantEmit, useClientLookup, useClientResource } from "@assistant-ui/store";
|
|
8
8
|
import { resource, useResource, withKey } from "@assistant-ui/tap";
|
|
9
9
|
//#region src/store/runtime-clients/thread-runtime-client.ts
|
|
10
10
|
const useMessageClientById = (t0) => {
|
|
@@ -97,7 +97,7 @@ type ThreadMethods = {
|
|
|
97
97
|
* @param initialMessages - Optional array of initial messages to populate the thread
|
|
98
98
|
*/
|
|
99
99
|
reset(initialMessages?: readonly ThreadMessageLike[]): void;
|
|
100
|
-
importExternalState
|
|
100
|
+
importExternalState(state: unknown): void;
|
|
101
101
|
message(selector: {
|
|
102
102
|
id: string;
|
|
103
103
|
} | {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread.d.ts","names":[],"sources":["../../../src/store/scopes/thread.ts"],"mappings":";;;;;;;;;;KAoBY;;;;WAID;;;;WAIA;;;;WAIA;;;;WAIA;;;;WAIA,cAAc;;;;WAId,mBAAmB;;;;;WAKnB,OAAO;;;;WAIP,sBAAsB;;;;WAItB;;WAEA,QAAQ;WACR,OAAO;WACP,UAAU;;KAGT;;;;EAIV,YAAY;;;;EAIZ,YAAY;;;;;;;;;;;;;;;;;EAiBZ,OAAO,SAAS;EAChB,cAAc,2BAA2B;;;;;EAKzC,SAAS,QAAQ;;;;;EAKjB,UAAU,QAAQ;EAClB;EACA,mBAAmB;EACnB,UAAU;EACV,OAAO,YAAY;;;;;EAKnB,MAAM,2BAA2B;EACjC,
|
|
1
|
+
{"version":3,"file":"thread.d.ts","names":[],"sources":["../../../src/store/scopes/thread.ts"],"mappings":";;;;;;;;;;KAoBY;;;;WAID;;;;WAIA;;;;WAIA;;;;WAIA;;;;WAIA,cAAc;;;;WAId,mBAAmB;;;;;WAKnB,OAAO;;;;WAIP,sBAAsB;;;;WAItB;;WAEA,QAAQ;WACR,OAAO;WACP,UAAU;;KAGT;;;;EAIV,YAAY;;;;EAIZ,YAAY;;;;;;;;;;;;;;;;;EAiBZ,OAAO,SAAS;EAChB,cAAc,2BAA2B;;;;;EAKzC,SAAS,QAAQ;;;;;EAKjB,UAAU,QAAQ;EAClB;EACA,mBAAmB;EACnB,UAAU;EACV,OAAO,YAAY;;;;;EAKnB,MAAM,2BAA2B;EACjC,oBAAoB;EACpB,QAAQ;IAAY;;IAAiB;MAAkB;;EAEvD;EACA;EACA;EACA;EACA,qBAAqB,uBAAuB;EAC5C;EACA;EACA,0BAA0B;;KAGhB;EACV;EACA;IAAS;;;KAGC;;;;;EAKV;IAAqB;;;;;;EAKrB;IAAmB;;;;;;;EAMnB;IAAuB;;;;;;EAKvB;IAA+B;;;KAGrB;EACV,SAAS;EACT,MAAM;EACN,QAAQ"}
|
package/dist/utils/data-url.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
//#region src/utils/data-url.ts
|
|
2
2
|
const httpUrlPattern = /^https?:\/\//i;
|
|
3
3
|
function parseDataUrl(value) {
|
|
4
|
-
const match = value.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(
|
|
4
|
+
const match = value.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(.*)$/i);
|
|
5
5
|
if (!match) return null;
|
|
6
6
|
return {
|
|
7
|
-
mimeType: match[1],
|
|
7
|
+
mimeType: match[1].toLowerCase(),
|
|
8
8
|
data: match[2]
|
|
9
9
|
};
|
|
10
10
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-url.js","names":["httpUrlPattern","parseDataUrl","value","mimeType","data","match"],"sources":["../../src/utils/data-url.ts"],"sourcesContent":["export const httpUrlPattern = /^https?:\\/\\//i;\n\nexport function parseDataUrl(\n value: string,\n): { mimeType: string; data: string } | null {\n const match = value.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(
|
|
1
|
+
{"version":3,"file":"data-url.js","names":["httpUrlPattern","parseDataUrl","value","mimeType","data","match","toLowerCase"],"sources":["../../src/utils/data-url.ts"],"sourcesContent":["export const httpUrlPattern = /^https?:\\/\\//i;\n\nexport function parseDataUrl(\n value: string,\n): { mimeType: string; data: string } | null {\n const match = value.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(.*)$/i);\n if (!match) return null;\n return { mimeType: match[1]!.toLowerCase(), data: match[2]! };\n}\n"],"mappings":";AAAA,MAAaA,iBAAiB;AAE9B,SAAgBC,aACdC,OAC2C;CAC3C,MAAMG,QAAQH,MAAMG,MAAM,0CAA0C;CACpE,IAAI,CAACA,OAAO,OAAO;CACnB,OAAO;EAAEF,UAAUE,MAAM,EAAE,CAAEC,YAAY;EAAGF,MAAMC,MAAM;CAAI;AAC9D"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Framework-agnostic core runtime for assistant-ui",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"assistant",
|
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
],
|
|
60
60
|
"sideEffects": false,
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"assistant-stream": "^0.3.
|
|
62
|
+
"assistant-stream": "^0.3.31",
|
|
63
63
|
"nanoid": "^6.0.0"
|
|
64
64
|
},
|
|
65
65
|
"optionalDevDependencies": {
|
|
@@ -95,8 +95,8 @@
|
|
|
95
95
|
"react-dom": "^19.2.8",
|
|
96
96
|
"vitest": "^4.1.10",
|
|
97
97
|
"zustand": "^5.0.14",
|
|
98
|
-
"@assistant-ui/store": "0.3.
|
|
99
|
-
"@assistant-ui/tap": "0.9.
|
|
98
|
+
"@assistant-ui/store": "0.3.2",
|
|
99
|
+
"@assistant-ui/tap": "0.9.8",
|
|
100
100
|
"@assistant-ui/vite": "0.0.11",
|
|
101
101
|
"@assistant-ui/x-buildutils": "0.0.20",
|
|
102
102
|
"assistant-cloud": "0.1.37"
|
package/src/internal.ts
CHANGED
|
@@ -58,12 +58,5 @@ export { isJSONValue, isRecord } from "./utils/json/is-json";
|
|
|
58
58
|
// outbound part conversion lives in one place.
|
|
59
59
|
export { httpUrlPattern, parseDataUrl } from "./utils/data-url";
|
|
60
60
|
|
|
61
|
-
// Runtime extras helper for external-store adapters. Internal because the
|
|
62
|
-
// tap-native runtime path replaces the `thread.extras` side-channel it wraps.
|
|
63
|
-
export {
|
|
64
|
-
createRuntimeExtras,
|
|
65
|
-
type RuntimeExtras,
|
|
66
|
-
} from "./react/runtimes/createRuntimeExtras";
|
|
67
|
-
|
|
68
61
|
export * from "./runtime/internal";
|
|
69
62
|
export * from "./runtimes/internal";
|
|
@@ -19,24 +19,37 @@ export type AssistantProviderBaseProps = PropsWithChildren<{
|
|
|
19
19
|
aui?: AssistantClient | null;
|
|
20
20
|
}>;
|
|
21
21
|
|
|
22
|
+
const AssistantProviderInner: FC<
|
|
23
|
+
PropsWithChildren<{ runtime: AssistantRuntime }>
|
|
24
|
+
> = ({ runtime, children }) => {
|
|
25
|
+
// The runtime has a stable identity but mutates in place: its options are
|
|
26
|
+
// pushed in by an unconditional effect inside <RenderComponent />, so that
|
|
27
|
+
// element must be re-created every commit for React to re-render it and
|
|
28
|
+
// re-run the effect. React Compiler caches <RenderComponent /> on the
|
|
29
|
+
// stable RenderComponent type, which silences the effect and stops option
|
|
30
|
+
// changes (e.g. unstable_enableMessageQueue) from reaching the runtime.
|
|
31
|
+
"use no memo";
|
|
32
|
+
const aui = useAui({ threads: RuntimeAdapter(runtime) });
|
|
33
|
+
const RenderComponent = getRenderComponent(runtime);
|
|
34
|
+
return (
|
|
35
|
+
<AuiProvider value={aui}>
|
|
36
|
+
{RenderComponent && <RenderComponent />}
|
|
37
|
+
{children}
|
|
38
|
+
</AuiProvider>
|
|
39
|
+
);
|
|
40
|
+
};
|
|
41
|
+
|
|
22
42
|
export const AssistantProviderBase: FC<AssistantProviderBaseProps> = memo(
|
|
23
|
-
({ runtime, aui
|
|
24
|
-
// The runtime has a stable identity but mutates in place: its options are
|
|
25
|
-
// pushed in by an unconditional effect inside <RenderComponent />, so that
|
|
26
|
-
// element must be re-created every commit for React to re-render it and
|
|
27
|
-
// re-run the effect. React Compiler caches <RenderComponent /> on the
|
|
28
|
-
// stable RenderComponent type, which silences the effect and stops option
|
|
29
|
-
// changes (e.g. unstable_enableMessageQueue) from reaching the runtime.
|
|
30
|
-
"use no memo";
|
|
31
|
-
const aui = useAui({ threads: RuntimeAdapter(runtime) }, { parent });
|
|
32
|
-
const RenderComponent = getRenderComponent(runtime);
|
|
43
|
+
({ runtime, aui = null, children }) => {
|
|
33
44
|
const inner = (
|
|
34
|
-
<
|
|
35
|
-
{RenderComponent && <RenderComponent />}
|
|
45
|
+
<AssistantProviderInner runtime={runtime}>
|
|
36
46
|
{children}
|
|
37
|
-
</
|
|
47
|
+
</AssistantProviderInner>
|
|
48
|
+
);
|
|
49
|
+
return aui ? (
|
|
50
|
+
<AuiProvider value={aui}>{inner}</AuiProvider>
|
|
51
|
+
) : (
|
|
52
|
+
<AuiProvider value={null}>{inner}</AuiProvider>
|
|
38
53
|
);
|
|
39
|
-
if (!parent) return inner;
|
|
40
|
-
return <AuiProvider value={parent}>{inner}</AuiProvider>;
|
|
41
54
|
},
|
|
42
55
|
);
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
|
|
3
|
+
import type { ReactNode } from "react";
|
|
4
|
+
import { useEffect } from "react";
|
|
5
|
+
import { cleanup, render } from "@testing-library/react";
|
|
6
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
7
|
+
import { resource } from "@assistant-ui/tap";
|
|
8
|
+
import { AuiProvider, useAui, type AssistantClient } from "@assistant-ui/store";
|
|
9
|
+
import type { ChatModelAdapter } from "../runtime/utils/chat-model-adapter";
|
|
10
|
+
import { AssistantRuntimeProvider } from "./AssistantRuntimeProvider";
|
|
11
|
+
import { useLocalRuntime } from "./runtimes/useLocalRuntime";
|
|
12
|
+
|
|
13
|
+
type AnyClient = Record<string, any>;
|
|
14
|
+
|
|
15
|
+
const chatModel: ChatModelAdapter = {
|
|
16
|
+
run: async () => ({ content: [] }),
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const makeCounterClient = (log?: string[]) => {
|
|
20
|
+
const useCounterClient = () => {
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
log?.push("parent tap effect");
|
|
23
|
+
}, []);
|
|
24
|
+
return { getState: () => ({ count: 0 }) };
|
|
25
|
+
};
|
|
26
|
+
return resource(useCounterClient);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
afterEach(() => {
|
|
30
|
+
cleanup();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("AssistantRuntimeProvider aui composition", () => {
|
|
34
|
+
it("isolates from ambient context by default", () => {
|
|
35
|
+
let aui!: AnyClient;
|
|
36
|
+
const Consumer = () => {
|
|
37
|
+
aui = useAui();
|
|
38
|
+
return null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const Ambient = ({ children }: { children: ReactNode }) => {
|
|
42
|
+
const ambient = useAui({
|
|
43
|
+
parentScope: makeCounterClient()(),
|
|
44
|
+
} as unknown as useAui.Props);
|
|
45
|
+
return <AuiProvider value={ambient}>{children}</AuiProvider>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const App = () => {
|
|
49
|
+
const runtime = useLocalRuntime(chatModel);
|
|
50
|
+
return (
|
|
51
|
+
<AssistantRuntimeProvider runtime={runtime}>
|
|
52
|
+
<Consumer />
|
|
53
|
+
</AssistantRuntimeProvider>
|
|
54
|
+
);
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
render(
|
|
58
|
+
<Ambient>
|
|
59
|
+
<App />
|
|
60
|
+
</Ambient>,
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
expect(aui.threads).toBeDefined();
|
|
64
|
+
expect(() => aui.parentScope.getState()).toThrow(
|
|
65
|
+
/The current scope does not have a "parentScope" property/,
|
|
66
|
+
);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("inherits a prop-passed parent and mounts its effects", () => {
|
|
70
|
+
const log: string[] = [];
|
|
71
|
+
let aui!: AnyClient;
|
|
72
|
+
const Consumer = () => {
|
|
73
|
+
aui = useAui();
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
log.push("consumer effect");
|
|
76
|
+
}, []);
|
|
77
|
+
return null;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const App = ({ parent }: { parent: AssistantClient }) => {
|
|
81
|
+
const runtime = useLocalRuntime(chatModel);
|
|
82
|
+
return (
|
|
83
|
+
<AssistantRuntimeProvider runtime={runtime} aui={parent}>
|
|
84
|
+
<Consumer />
|
|
85
|
+
</AssistantRuntimeProvider>
|
|
86
|
+
);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const Root = () => {
|
|
90
|
+
const parent = useAui({
|
|
91
|
+
parentScope: makeCounterClient(log)(),
|
|
92
|
+
} as unknown as useAui.Props);
|
|
93
|
+
return <App parent={parent} />;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
render(<Root />);
|
|
97
|
+
|
|
98
|
+
expect(aui.parentScope.getState()).toEqual({ count: 0 });
|
|
99
|
+
expect(log).toEqual(["parent tap effect", "consumer effect"]);
|
|
100
|
+
});
|
|
101
|
+
});
|