/* esm.sh - @assistant-ui/core@0.3.31/dist/runtimes/external-store/external-store-thread-runtime-core */
import{generateId as j}from"../../utils/id.mjs";import{getThreadMessageText as k}from"../../utils/text.mjs";import{fromThreadMessageLike as W}from"../../runtime/utils/thread-message-like.mjs";import{FALLBACK_ID_PREFIX as H,bindExternalStoreMessage as A,dedupeMessagesById as $,getExternalStoreMessages as Y}from"../../runtime/utils/external-store-message.mjs";import{getContentAutoStatus as F,isAutoStatus as G}from"../../runtime/utils/auto-status.mjs";import{ExportedMessageRepository as X,MessageRepository as K}from"../../runtime/utils/message-repository.mjs";import{EMPTY_QUEUE_ITEMS as q}from"../../runtime/queue/queue-item.mjs";import{__internal_bindNextDispatchTransform as J,__internal_getDispatchTransform as P}from"../../runtime/queue/message-queue.mjs";import{ThreadMessageConverter as O}from"./thread-message-converter.mjs";import{shallowArrayEqual as E}from"../../runtime/utils/external-message-conversion.mjs";import{RunLeases as D}from"../../utils/run-lease.mjs";import{walkToolCallTree as z}from"../../runtime/utils/tool-call-tree.mjs";import{captureThreadRuntimeDisposal as B,captureThreadRuntimeGeneration as S}from"../../runtime/utils/thread-runtime-lifecycle.mjs";import{getThreadRuntimeCoreIsRunning as Z}from"../../runtime/api/thread-runtime.mjs";import{BaseThreadRuntimeCore as ee}from"../../runtime/base/base-thread-runtime-core.mjs";import{LoadEarlier as te}from"../../runtime/utils/load-earlier.mjs";import{NO_TOOL_EXECUTIONS as se,ToolInvocationTracker as ie}from"../tool-invocations/ToolInvocationTracker.mjs";import{shallowEqual as U}from"../../../../../../store@0.3.22/X-ZEBhc3Npc3RhbnQtdWkvdGFwQDAuOS4yNCxyZWFjdEAxOS4zLjE/es2022/client.mjs";var oe=Object.freeze([]),V=new WeakMap,Q=(e,t)=>e?.type===t?.type&&e?.comment===t?.comment,N=new WeakMap,C=(e,t)=>{Promise.resolve(t).catch(s=>{console.error(`[ExternalStoreThreadRuntimeCore] ${e} callback rejected`,s)})},ne=(e,t)=>e&&t[t.length-1]?.role!=="assistant",be=class extends ee{_capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,delete:!1,reload:!1,refetchThread:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1,answerToolCall:!1};get capabilities(){return this._capabilities}_messages;isDisabled;isSendDisabled;get isLoading(){return this._store.isLoading??!1}_pendingResume;_clearPendingResume(e){!e||this._pendingResume!==e||(this._pendingResume=void 0,this._notifySubscribers())}get canResume(){return!!this._store.canResume&&!!this._store.onResume&&!this._pendingResume&&!this.isDisabled&&!Z(this)&&!this.isLoading&&!this.voice}get hasEarlier(){return this._store.hasEarlier===!0&&this._store.onLoadEarlier!==void 0}_loadEarlier=new te;get isLoadingEarlier(){return this._loadEarlier.isLoading}loadEarlier(){let e=this._store.onLoadEarlier;return this._loadEarlier.load(this.hasEarlier?e:void 0,t=>{console.error("[ExternalStoreThreadRuntimeCore] onLoadEarlier callback rejected",t)},()=>this._notifySubscribers())}get isRunning(){return this._hasExecutingTools(this._store)?!0:this._store.isRunning}_getBaseMessages(){return this._messages}get state(){return this._store.state??super.state}get adapters(){return this._store.adapters}get unstable_refetchThread(){if(this._store.onRefetchThread)return()=>this._store.onRefetchThread()}suggestions=[];extras=void 0;_converter=new O;_createdAtById=new Map;_submittedFeedback=new Map;_pendingDeleteEvictions=new Map;_pendingDeleteWindows=new Set;_openDeleteWindow(e){let t=this.repository.getMessages(),s=t.findIndex(i=>i.id===e)+1,o={prefix:new Set(t.slice(0,s).map(i=>i.id)),suffix:new Set(t.slice(s).map(i=>i.id))};if(o.suffix.size===0)return o;this._pendingDeleteWindows.add(o);for(let[i,l]of this._pendingDeleteEvictions)o.prefix.has(i)||(l.calls.size>0?l.reloaded=!0:this._pendingDeleteEvictions.delete(i));return o}_closeDeleteWindows(e){for(let t of this._pendingDeleteWindows)[...t.suffix].every(s=>!e.has(s))&&this._pendingDeleteWindows.delete(t)}_optimistic=null;_storeMessages=[];_importedMessageIds;_runStartLeases=new D;_runCancellationLeases=new D;_cancelRunResyncLeases=new D;_cancelledToolTurn=null;_cancelledRunIds=new Set;_pendingCancelResyncs=new Set;_movedLeaf;_store;_getInitializePromise;__internal_setGetInitializePromise(e){this._getInitializePromise=e}_queueDispatchTransform=e=>{let t=this._transformedQueue&&P(this._transformedQueue);if(t&&B(this).aborted&&t!==this._queueDispatchTransform)return t(e);let s=t?void 0:V.get(e),o=s&&!B(s).aborted?s:this;o._pendingDeleteWindows.clear(),o._settleCancelResyncs();let i=o.messages.at(-1)?.id??null;return o.enrichAppendMetadata({...e,parentId:i},i)};_transformedQueue;_toolInvocations=null;_toolStatuses=new Map;_effectiveIsRunning=!1;_inTrackerUpdate=!1;_pendingRunningRefresh=!1;_onMessageMetadataChanged(e,t){if(this._storeMessages=this._storeMessages.map(l=>l.id===t.id?t:l),t.id.startsWith("__external_store_fallback_"))return;let s=this._submittedFeedback.get(t.id),o=s&&Q(e.metadata.submittedFeedback,s.feedback)?s.external:e.metadata.submittedFeedback,i=t.metadata.submittedFeedback;i&&this._submittedFeedback.set(t.id,{feedback:i,external:o,source:s?.message===e?s.source:e,message:t})}_applySubmittedFeedback(e){if(this._submittedFeedback.size===0)return e;for(let t of this._submittedFeedback.keys())try{this.repository.getMessage(t)}catch{this._submittedFeedback.delete(t)}return e.map(t=>{let s=this._submittedFeedback.get(t.id);if(!s)return t;if(t.role!=="assistant"||!Q(t.metadata.submittedFeedback,s.external))return this._submittedFeedback.delete(t.id),t;if(s.source===t)return s.message;let o={...t,metadata:{...t.metadata,submittedFeedback:s.feedback}};return s.source=t,s.message=o,o})}_runTrackerUpdate(e){this._inTrackerUpdate=!0;try{e()}finally{this._inTrackerUpdate=!1}this._pendingRunningRefresh&&(this._pendingRunningRefresh=!1,this._refreshEffectiveIsRunning())}_refreshEffectiveIsRunning(){this._effectiveIsRunning!==this._getEffectiveIsRunning(this._store)&&this._updateStoreSnapshot(this._store,!1)}_hasExecutingTools(e){if(e.unstable_enableToolInvocations!==!0||this._toolInvocations===null)return!1;for(let t of this._toolStatuses.values())if(t.type==="executing")return!0;return!1}_getEffectiveIsRunning(e){return(e.isRunning??!1)||this._hasExecutingTools(e)}beginEdit(e){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(e)}constructor(e,t){super(e),this.__internal_setAdapter(t)}__internal_setAdapter(e){this._store!==e&&this._updateStoreSnapshot(e)}_evictPlaceholder(){if(this._optimistic){try{this.repository.getMessage(this._optimistic.id)}catch{return}this.repository.deleteMessage(this._optimistic.id)}}_updateStoreSnapshot(e,t=!0,s=!1){let o=this._effectiveIsRunning;this.isDisabled=e.isDisabled??!1,this.isSendDisabled=e.isSendDisabled??!1;let i=this._store;this._store=e;let l=this._getEffectiveIsRunning(e),c=e.unstable_messageRepositoryInstance,h=c!==void 0&&c!==this.repository;if(h){this.repository=c,this._createdAtById.clear(),this._cancelledToolTurn=null,this._cancelledRunIds.clear(),this._pendingResume=void 0,this._pendingDeleteEvictions.clear(),this._pendingDeleteWindows.clear(),this._submittedFeedback.clear(),this._movedLeaf=void 0;let d=this.repository.getMessages(),u=d.at(-1);this._optimistic=u?.metadata.isOptimistic?{id:u.id,parentId:d.at(-2)?.id??null}:null}i?.queue!==e.queue&&(this._transformedQueue=void 0,e.queue?.__internal_setDispatchTransform?.(this._queueDispatchTransform),e.queue?.__internal_setDispatchTransform&&(this._transformedQueue=e.queue)),this.extras!==e.extras&&(this.extras=e.extras);let _=e.suggestions??oe;U(this.suggestions,_)||(this.suggestions=_);let w={switchToBranch:this._store.setMessages!==void 0,switchBranchDuringRun:!1,edit:this._store.onEdit!==void 0,delete:this._store.onDelete!==void 0||this._store.setMessages!==void 0,reload:this._store.onReload!==void 0,refetchThread:this._store.onRefetchThread!==void 0,cancel:this._store.onCancel!==void 0,speech:this._store.adapters?.speech!==void 0,dictation:this._store.adapters?.dictation!==void 0,voice:this._store.adapters?.voice!==void 0,unstable_copy:this._store.unstable_capabilities?.copy!==!1,attachments:!!this._store.adapters?.attachments,feedback:!!this._store.adapters?.feedback,queue:this._store.queue!==void 0,answerToolCall:this._store.onAddToolResult!==void 0||this._store.onResumeToolCall!==void 0||this._store.onRespondToToolApproval!==void 0||this._store.unstable_enableToolInvocations===!0};U(this._capabilities,w)||(this._capabilities=w);let n,p=!1,b=!1;if(e.messageRepository){if(this._importedMessageIds=void 0,!s&&i&&!h&&i.isRunning===e.isRunning&&i.messageRepository===e.messageRepository&&o===l){t&&this._pendingDeleteWindows.size>0&&this._closeDeleteWindows(new Set(e.messageRepository.messages.map(({message:g})=>g.id))),this._notifySubscribers();return}let d=e.messageRepository.messages;t&&this._pendingDeleteWindows.size>0&&this._closeDeleteWindows(new Set(d.map(({message:g})=>g.id)));let u=e.messageRepository.headId??d.at(-1)?.message.id??null;if(this._evictPlaceholder(),i&&!s&&!h&&i.messageRepository===e.messageRepository)this.repository.import({headId:u,messages:[]}),n=this.repository.getMessages();else{let g=new Set(d.map(({message:a})=>a.id)),r=this._applySubmittedFeedback(d.map(({message:a})=>a));for(let a=0;a<d.length;a++)this.repository.addOrUpdateMessage(d[a].parentId,r[a]);for(let{message:a}of this.repository.export().messages)g.has(a.id)||this.repository.deleteMessage(a.id);this._pendingDeleteEvictions.clear(),this.repository.import({headId:u,messages:[]}),n=this.repository.getMessages()}}else if(e.messages){if(i){if(i.convertMessage!==e.convertMessage)this._converter=new O;else if(!s&&!h&&i.isRunning===e.isRunning&&i.messages===e.messages&&o===l){t&&this._pendingDeleteWindows.size>0&&this._closeDeleteWindows(new Set(this._storeMessages.map(r=>r.id))),this._notifySubscribers();return}}n=e.convertMessage?this._converter.convertMessages(e.messages,(r,a,f)=>{if(!e.convertMessage)return a;let T=f===(e.messages?.length??0)-1,I=`${H}${f}`;if(r&&(r.role!=="assistant"||!G(r.status)||r.status===F(r.content,T,l))){if(r.id.startsWith("__external_store_fallback_")&&r.id!==I){let v={...r,id:I};return A(v,a),v}return r}let m=e.convertMessage(a,f);if(m.createdAt==null&&m.id!=null){let v=this._createdAtById.get(m.id)??new Date;this._createdAtById.set(m.id,v),m={...m,createdAt:v}}let R=W(m,I,F(m.content,T,l));return A(R,a),R}):e.messages,n=$(n,r=>{console.warn(`ExternalStoreThreadRuntimeCore: duplicate message id "${r}" in the provided messages array; keeping the last occurrence.`)}),n=this._applySubmittedFeedback(n);let d=this._importedMessageIds;p=d!==void 0&&E(d,n.map(r=>r.id)),p||(b=d!==void 0,this._importedMessageIds=void 0);let u=new Set(n.map(r=>r.id)),g=new Map;for(let r=1;r<n.length;r++){let a=n[r].id,f=n[r-1].id,T;try{T=this.repository.getMessage(a).parentId}catch{continue}if(T===f)continue;let I=this.repository.getMessages(a),m=I.findIndex(R=>R.id===f);if(m!==-1)for(let R=m+1;R<I.length-1;R++){let v=I[R];u.has(v.id)||g.set(v.id,v)}}for(let r=0;r<n.length;r++){let a=n[r],f=n[r-1];this.repository.addOrUpdateMessage(f?.id??null,a)}for(let[r,a]of g)this._evictDeletedMessage(r,a,!1);if(this._pendingDeleteEvictions.size>0&&i?.messages!==e.messages||t&&this._pendingDeleteWindows.size>0){let r=new Set(n.map(a=>a.id));if(t&&this._closeDeleteWindows(r),i?.messages!==e.messages){for(let[a,f]of this._pendingDeleteEvictions)if(!f.reloaded){if(r.has(a)){f.calls.size===0&&this._pendingDeleteEvictions.delete(a);continue}this._pendingDeleteEvictions.delete(a);try{this.repository.getMessage(a)}catch{continue}this.repository.deleteMessage(a)}}}}else throw new Error("ExternalStoreAdapter must provide either 'messages' or 'messageRepository'");this._storeMessages=n,n.length>0&&this.ensureInitialized();let y=this._movedLeaf;if(y)if(y.generation.aborted||!y.resyncLease.isCurrent()||this.composer.text!==y.draft.text)this._movedLeaf=void 0;else{let d=n.findIndex(u=>u.id===y.id);d!==-1&&(k(n[d])!==y.draft.text?this._movedLeaf=void 0:d<n.length-1&&(this.composer.retractDraft(y.draft),this._movedLeaf=void 0))}if(this._effectiveIsRunning=l,o!==l)if(l){let d=this._cancelledToolTurn;if(d?.lease.isCurrent()){let u=n.at(-1);u?.role==="assistant"&&d.messageIds.has(u.id)?this._cancelledToolTurn=null:(u?.role==="assistant"?n.at(-2)?.id??null:u?.id??null)===d.parentId&&(d.parentOpen=!1)}this._notifyEventSubscribers("runStart",{})}else this._notifyEventSubscribers("runEnd",{});let M=null;if(ne(l,n)){let d=n.at(-1)?.id??null;b&&this.repository.resetHead(d),this._optimistic?.parentId!==d&&(this._optimistic={id:j(),parentId:d}),M=this._optimistic.id,this.repository.addOrUpdateMessage(d,W({role:"assistant",content:[],metadata:{isOptimistic:!0}},M,{type:"running"}))}M===null&&(this._optimistic=null);let x=M??n.at(-1)?.id??null;e.messageRepository||p?this.repository.import({headId:x,messages:[]}):this.repository.resetHead(x);let L=this.repository.getMessages();if((!this._messages||!E(this._messages,L))&&(this._messages=L),this._voiceMessages.length>0){let d=new Set(this._messages.map(g=>g.id)),u=this._voiceMessages.filter(g=>!d.has(g.id));u.length!==this._voiceMessages.length&&(this._voiceMessages=u,this._markVoiceMessagesDirty())}t&&(h&&this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._runTrackerUpdate(()=>this._driveToolInvocations())),this._notifySubscribers()}_driveToolInvocations(){if(!this._store.unstable_enableToolInvocations){this._toolInvocations&&(this._toolInvocations.reset(),this._toolInvocations=null,this._toolStatuses=new Map,this._store.setToolStatuses?.({}));return}let e=N.get(this.repository);if(e||(e=this._createToolInvocations(),N.set(this.repository,e)),this._toolInvocations=e.tracker,e.host!==this){e.host._toolInvocations===e.tracker&&(e.host._toolInvocations=null),e.host=this;let s=e.tracker.getStatuses();(s.size>0||this._toolStatuses.size>0)&&this._applyToolStatuses(s)}let t=this._getDiscardedToolCallIds();this._toolInvocations.setState({messages:this._messages,isRunning:this._getEffectiveIsRunning(this._store),...t&&{discardedToolCallIds:t},...this._store.isLoading!==void 0&&{isLoading:this._store.isLoading}})}_getDiscardedToolCallIds(){let e=this._cancelledToolTurn;if(!e&&this._cancelledRunIds.size===0)return;let t=new Set;for(let s=0;s<this._messages.length;s++){let o=this._messages[s];if(o.role!=="assistant"||o.metadata.isOptimistic)continue;let i=o.metadata.runId;if(i===void 0||!this._cancelledRunIds.has(i)){if(!e)continue;if(!e.messageIds.has(o.id)){if(!e.parentOpen||(this._messages[s-1]?.id??null)!==e.parentId)continue;e.messageIds.add(o.id)}}for(let{part:l}of z([o]))t.add(l.toolCallId)}return t}_createToolInvocations(){let e={host:this,tracker:new ie(()=>e.host.getModelContext().tools,{onResult:t=>e.host._dispatchToolResult(t),onStatusesChange:t=>e.host._applyToolStatuses(t)},t=>e.host._store.unstable_isClientToolCall?.(t))};return e}_dispatchToolResult(e){try{let t=this._findMessageIdForToolCall(e.toolCallId);if(t===void 0)return;C("onAddToolResult",this._store.onAddToolResult?.({messageId:t,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError,...e.artifact!==void 0&&{artifact:e.artifact},...e.modelContent!==void 0&&{modelContent:e.modelContent}}))}catch(t){console.error("[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed",t)}}_applyToolStatuses(e){let t=this._hasExecutingTools(this._store);this._toolStatuses=e;try{this._store.setToolStatuses?.(Object.fromEntries(e))}finally{t!==this._hasExecutingTools(this._store)&&(this._inTrackerUpdate?this._pendingRunningRefresh=!0:this._updateStoreSnapshot(this._store))}}_toolCallToMessageId=new Map;_messagesForToolCallIndex=null;_findMessageIdForToolCall(e){if(this._messagesForToolCallIndex!==this._messages){this._toolCallToMessageId.clear();for(let{part:t,messageId:s}of z(this._messages))this._toolCallToMessageId.set(t.toolCallId,s);this._messagesForToolCallIndex=this._messages}return this._toolCallToMessageId.get(e)}switchToBranch(e){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");if(this._getEffectiveIsRunning(this._store))return;let t=this._store.unstable_onBranchChange,s=this._pendingResume,o=t||s?this.repository.canonicalHeadId:null;this.repository.switchToBranch(e),this._pendingDeleteWindows.clear();for(let[i,l]of this._pendingDeleteEvictions)l.calls.size>0?l.reloaded=!0:this._pendingDeleteEvictions.delete(i);this.updateMessages(this.repository.getMessages()),s&&this.repository.canonicalHeadId!==o&&this._clearPendingResume(s),t&&this._notifyBranchChange(o,t)}_notifyBranchChange(e,t){let s=this.repository.canonicalHeadId;s!==e&&t({headId:s,visibleMessageIds:this.repository.getMessages().map(o=>o.id)})}async append(e){let t={...e,parentId:this._resolveAppendParent(e.parentId)};if(this.voice)return this._pendingDeleteWindows.clear(),this._appendToVoiceSession(t);if(this._isVoiceMessage(t.sourceId))throw new Error("Voice transcript messages cannot be edited");let s=t.sourceId!=null||t.parentId!==(this._getBaseMessages().at(-1)?.id??null),o=!s&&this._store.queue&&this._store.queue===this._transformedQueue?void 0:this.enrichAppendMetadata(t),i=S(this);this.ensureInitialized();let l=this._getInitializePromise?.();if(!s&&this._store.queue&&(l&&await l,i.aborted))return;let c=s?void 0:this._store.queue;if((!c||c!==this._transformedQueue)&&(t=o??this.enrichAppendMetadata(t)),c){c===this._transformedQueue&&(P(c)||V.set(t,this),c.__internal_setDispatchTransform?.(this._queueDispatchTransform),J(c)),t.steer??this._getEffectiveIsRunning(this._store)?c.steer(t):c.enqueue(t);return}if(l?.catch(()=>{}),t.startRun??t.role==="user"){let h=this._toolInvocations?.abort({discardPending:!0});h&&h!==se&&await h}if(!i.aborted)if(s||this._pendingDeleteWindows.clear(),this._settleCancelResyncs(),s){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");let h=this._openDeleteWindow(t.parentId);try{await this._store.onEdit(t)}catch(_){throw this._pendingDeleteWindows.delete(h),_}}else await this._store.onNew(t)}_commitVoiceMessage(e){let t=S(this);if(t.aborted){this._dropVoiceMessage(e.id,!1);return}let s=this._getVoiceCommitBarrier();if(!s){this._store.onVoiceTranscript?.(e);return}let o=this.repository;return s.then(()=>{if(t.aborted||this.repository!==o){this._dropVoiceMessage(e.id,!0);return}this._store.onVoiceTranscript?.(e)})}async deleteMessage(e){if(this._store.onDelete){let s=this.repository.getMessages().find(c=>c.id===e),o=Symbol(),i=this._pendingDeleteEvictions.get(e);if(s){let c=!1;for(let h of this._pendingDeleteWindows)if(!h.prefix.has(e)){c=!0;break}(!i||e.startsWith("__external_store_fallback_")&&i.message!==s)&&(i={calls:new Set,reloaded:c,message:s}),c&&(i.reloaded=!0),i.calls.add(o),this._pendingDeleteEvictions.set(e,i)}let l=!1;try{await this._store.onDelete(e),l=!0}finally{i&&this._pendingDeleteEvictions.get(e)===i&&i.calls.delete(o)&&(i.reloaded&&l?(i.reloaded=!1,this._storeMessages.some(c=>c.id===e)||(this._pendingDeleteEvictions.delete(e),this._evictDeletedMessage(e,i.message))):i.reloaded&&i.calls.size===0&&this._pendingDeleteEvictions.delete(e))}return}if(!this._store.setMessages)throw new Error("Runtime does not support deleting messages.");this._getEffectiveIsRunning(this._store)&&await this._toolInvocations?.abort();let t=this.repository.getMessages();if(t.findIndex(s=>s.id===e)===-1)throw new Error("Message not found.");this._pendingDeleteEvictions.clear(),this.updateMessages(t.filter(s=>s.id!==e)),this._evictDeletedMessage(e)}_evictDeletedMessage(e,t,s=!0){if(!(e.startsWith("__external_store_fallback_")&&!t)){try{let o=this.repository.getMessage(e).message;if(e.startsWith("__external_store_fallback_")&&o!==t)return}catch{return}this.repository.deleteMessage(e),s&&this._publishRepositoryMessages()}}_publishRepositoryMessages(){let e=this.repository.getMessages();E(this._messages,e)||(this._messages=e),this._notifySubscribers()}getQueueItems(){return this._store?.queue?.items??q}getSteerQueueItems(){return this._store?.queue?.steerItems??q}moveQueueItem(e,t){this._store?.queue?.move(e,t)}removeQueueItem(e){this._store?.queue?.remove(e)}_restoreMovedLeafForRun(e){let t=this._movedLeaf;t?.id===e&&t.resyncLease.isCurrent()&&!t.generation.aborted&&this._storeMessages.some(s=>s.id===t.id)&&(this._cancelRunResyncLeases.invalidate(),this._movedLeaf=void 0,this.composer.retractDraft(t.draft),this._updateStoreSnapshot(this._store,!1,!0))}async startRun(e){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");if(this.voice)throw new Error("Cannot start a run while a voice session is connected");if(this._isVoiceMessage(e.sourceId))throw new Error("Voice transcript messages cannot be reloaded");this._restoreMovedLeafForRun(e.parentId),this._runStartLeases.begin(),this._cancelledToolTurn?.parentId===e.parentId&&(this._cancelledToolTurn.parentOpen=!1);let t=this._openDeleteWindow(e.parentId),s=this._runCancellationLeases.current();try{if(await this._toolInvocations?.abort({discardPending:!0}),!s.isCurrent()){this._pendingDeleteWindows.delete(t);return}await this._store.onReload(e.parentId,e)}catch(o){throw this._pendingDeleteWindows.delete(t),o}}async resumeRun(e){if(!this._store.onResume)throw new Error("Runtime does not support resuming runs.");if(this.voice)throw new Error("Cannot start a run while a voice session is connected");if(this._isVoiceMessage(e.sourceId))throw new Error("Voice transcript messages cannot be reloaded");let t=this._store;if(this._pendingResume)return this._pendingResume;let s=async()=>{this._pendingDeleteWindows.clear(),this._restoreMovedLeafForRun(e.parentId),this._runStartLeases.begin(),this._cancelledToolTurn=null,await t.onResume(e)};if(t.canResume!==!0)return s();let o,i=new Promise((l,c)=>{o=()=>{try{l(s())}catch(h){c(h)}}}).finally(()=>{this._clearPendingResume(i)});return this._pendingResume=i,this._notifySubscribers(),o(),i}exportExternalState(){if(!this._store.onExportExternalState)throw new Error("Runtime does not support exporting external states.");return this._store.onExportExternalState()}importExternalState(e){if(!this._store.onLoadExternalState)throw new Error("Runtime does not support importing external states.");this._pendingDeleteWindows.clear(),this._cancelRunResyncLeases.invalidate(),this._cancelledToolTurn=null,this._cancelledRunIds.clear();let t=this._pendingResume;this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._store.onLoadExternalState(e),this._clearPendingResume(t)}unstable_notifySessionReset(){this._cancelRunResyncLeases.invalidate(),this._cancelledToolTurn=null,this._cancelledRunIds.clear(),this._clearPendingResume(this._pendingResume),this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._store.queue?.__internal_notifyCancelled?.()}cancelRun(){if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._pendingDeleteWindows.clear();let e=this._getEffectiveIsRunning(this._store);this._runCancellationLeases.invalidate();let t=S(this),s=this._cancelRunResyncLeases.current();if(this._store.activeRunId!==void 0&&this._cancelledRunIds.add(this._store.activeRunId),e){let n=this._storeMessages.filter(b=>!b.metadata.isOptimistic),p=n.at(-1);this._cancelledToolTurn={messageIds:new Set(p?.role==="assistant"?[p.id]:[]),parentId:p?.role==="assistant"?n.at(-2)?.id??null:p?.id??null,parentOpen:!0,lease:this._runStartLeases.current()}}this._toolInvocations?.abort({discardPending:!0}),this._store.queue?.__internal_notifyCancelled?.(),C("onCancel",this._store.onCancel()),this.dropEmptyOptimisticHead();let o=this.repository.getMessages(),i=o[o.length-1],l=i?.id??null,c=this._runStartLeases.current(),h=e&&this._store.setMessages!==void 0&&i?.role==="user"&&i.id===o.at(-1)?.id&&i.content.every(n=>n.type==="text")?i:void 0,_;if(h){let n={text:k(h),attachments:h.attachments,quote:h.metadata.custom.quote};this.composer.restoreDraft(n)&&(this.repository.deleteMessage(h.id),_={id:h.id,draft:n,resyncLease:s,generation:t},this._movedLeaf=_)}this._publishRepositoryMessages();let w=()=>{if(t.aborted||!s.isCurrent())return;if(this._getEffectiveIsRunning(this._store)&&(!c.isCurrent()||(this.repository.getMessages().at(-2)?.id??null)!==l)||this.dropEmptyOptimisticHead(),_){let p=this.repository.getMessages();this._movedLeaf===_&&p.at(-1)?.id===_.id&&this.composer.text===_.draft.text&&this.repository.deleteMessage(_.id)}this._publishRepositoryMessages();let n=this._messages.filter(p=>p.id!==this._optimistic?.id);E(n,this._storeMessages)||this.updateMessages(n)};this._pendingCancelResyncs.add(w),setTimeout(()=>{this._pendingCancelResyncs.delete(w),w()},0)}_settleCancelResyncs(){for(let e of this._pendingCancelResyncs)e()}dropEmptyOptimisticHead(){let e=this.repository.getMessages().at(-1);e&&e.metadata.isOptimistic&&e.content.length===0&&this.repository.deleteMessage(e.id)}addToolResult(e){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");C("onAddToolResult",this._store.onAddToolResult(e))}resumeToolCall(e){if(!(this._toolInvocations?.resume(e.toolCallId,e.payload)??!1)){if(this._store.onResumeToolCall){this._store.onResumeToolCall(e);return}throw new Error(`Tool call ${e.toolCallId} is not waiting for resume.`)}}respondToToolApproval(e){if(!this._store.onRespondToToolApproval)throw new Error("Runtime does not support tool approvals.");let t=this.messages.findLast(o=>o.role==="assistant"&&o.content.some(i=>i.type==="tool-call"&&i.approval?.id===e.approvalId)),s=t?.content.find(o=>o.type==="tool-call"&&o.approval?.id===e.approvalId);try{return Promise.resolve(this._store.onRespondToToolApproval(e)).then(()=>{t&&s?.type==="tool-call"&&this._notifyToolApprovalAnswered(t.id,s.toolCallId,s.toolName,e.approved)})}catch(o){return Promise.reject(o)}}async unstable_recordToolInteraction(e){if(!this._store.unstable_onRecordToolInteraction)throw new Error("Runtime does not support recording tool interactions.");await this._store.unstable_onRecordToolInteraction(e)}reset(e){let t=this._pendingResume;this._pendingDeleteWindows.clear(),this._cancelRunResyncLeases.invalidate(),this._cancelledToolTurn=null,this._cancelledRunIds.clear(),this._submittedFeedback.clear(),this._importedMessageIds=void 0;let s=new K;s.import(X.fromArray(e??[])),this.updateMessages(s.getMessages()),this._clearPendingResume(t)}import(e){if(!this._store.onImport)throw new Error("Runtime does not support importing messages.");let t=this._pendingResume;this._pendingDeleteWindows.clear(),this._cancelRunResyncLeases.invalidate(),this._cancelledToolTurn=null,this._cancelledRunIds.clear(),this._submittedFeedback.clear(),super.import(e),this._clearPendingResume(t);let s=this.repository.getMessages();this._importedMessageIds=s.map(o=>o.id),this._store.onImport(s)}updateMessages=e=>{this._storeMessages=e,this._store.convertMessage!==void 0?this._store.setMessages?.(e.flatMap(Y)):this._store.setMessages?.(e)}};export{be as ExternalStoreThreadRuntimeCore,ne as hasUpcomingMessage};
//# sourceMappingURL=external-store-thread-runtime-core.mjs.map