/* esm.sh - @assistant-ui/core@0.3.31/dist/runtime/base/base-thread-runtime-core */
import{notifyEventListeners as v}from"../../utils/notify-event-listeners.mjs";import{getThreadMessageText as b}from"../../utils/text.mjs";import{gateInteractableComposerMetadata as y}from"../../model-context/interactable-composer-metadata.mjs";import{BaseSubscribable as V,notifySubscribers as m}from"../../subscribable/subscribable.mjs";import{ExportedMessageRepository as S,MessageRepository as w}from"../utils/message-repository.mjs";import{captureThreadRuntimeDisposal as C,captureThreadRuntimeGeneration as x}from"../utils/thread-runtime-lifecycle.mjs";import{DefaultThreadComposerRuntimeCore as A}from"./default-thread-composer-runtime-core.mjs";import{DefaultEditComposerRuntimeCore as k}from"./default-edit-composer-runtime-core.mjs";import{generateId as l}from"../../utils/id.mjs";import{notifyEventListeners as _}from"../../utils/notify-event-listeners.mjs";import{getThreadMessageText as M}from"../../utils/text.mjs";import{notifySubscribers as p}from"../../subscribable/subscribable.mjs";import{MessageNotSentError as g}from"../../types/error.mjs";var f=class{voiceMessages=[];voiceGeneration=0;_cachedMergedMessages=null;_cachedVoiceGeneration=-1;_cachedMergedBase=null;host;constructor(e){this.host=e}markMessagesDirty(){this.voiceGeneration++,this._cachedMergedMessages=null}dropMessage(e,t){let s=this.voiceMessages.findIndex(i=>i.id===e);s!==-1&&(this.voiceMessages.splice(s,1),this.host.markVoiceMessagesDirty(),t&&this.host.notify())}getMessages(){if(this.voiceMessages.length===0)return this.host.getBaseMessages();let e=this.host.getBaseMessages();if(this._cachedVoiceGeneration!==this.voiceGeneration||this._cachedMergedBase!==e){let t=new Set(e.map(s=>s.id));this._cachedMergedMessages=[...e,...this.voiceMessages.filter(s=>!t.has(s.id))],this._cachedVoiceGeneration=this.voiceGeneration,this._cachedMergedBase=e}return this._cachedMergedMessages}replaceAssistantMessage(e,t){this._currentAssistantMsg===e&&(this._currentAssistantMsg=t)}isVoiceMessage(e){return e!==null&&this.voiceMessages.some(t=>t.id===e)}_voiceSession;_voiceUnsubs=[];voice;_voiceVolume=0;_voiceVolumeSubscribers=new Set;getVoiceVolume=()=>this._voiceVolume;subscribeVoiceVolume=e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e));_toVoiceSessionState(e,t,s){return{status:t,isMuted:e.isMuted,mode:s,canSendText:t.type==="running"&&e.sendText!==void 0}}isRunActive(){if(this.host.isRunning())return!0;let e=this.host.getBaseMessages().at(-1);return e?.role==="assistant"&&(e.status.type==="running"||e.status.type==="requires-action")}getVoiceCommitBarrier(){if(!this.host.isLoading())return;let e=this.host.captureGeneration();return(async()=>{for(;this.host.isLoading()&&!e.aborted;)await new Promise(t=>{let s=()=>{i(),e.removeEventListener("abort",s),t()},i=this.host.subscribe(s);e.addEventListener("abort",s)})})()}connectVoice(){let e=this.host.adapter();if(!e)throw new Error("Voice adapter not configured");if(this.host.isRunActive())throw new Error("Cannot start a voice session while a run is in progress or paused on a pending tool action");let t=this._voiceSession!==void 0;try{this._disconnectVoice(!1)}catch(o){console.error("[assistant-ui] Voice cleanup threw before reconnect",o)}if(this._voiceSession!==void 0)return;let s;try{s=e.connect({})}catch(o){throw t&&this._voiceSession===void 0&&this.host.onDisconnected(),o}if(s.status.type==="ended"){try{s.disconnect()}finally{t&&this._voiceSession===void 0&&this.host.onDisconnected()}return}this._voiceSession=s;let i=[];this._voiceUnsubs=i;let r=()=>{if(this._voiceSession===s&&this._voiceUnsubs===i)return!1;try{p(i.splice(0))}catch(o){console.error("[assistant-ui] Detached voice setup cleanup threw",o)}return!0};try{let o="listening";if(this.voice=this._toVoiceSessionState(s,s.status,o),this._voiceVolume=0,this.host.notify(),r()||(i.push(s.onStatusChange(n=>{if(this._voiceSession===s)if(n.type==="ended"){this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;try{p([()=>this._finishVoiceAssistantMessage(!1),()=>{this._voiceSession===void 0&&this.host.onDisconnected()},()=>_(this._voiceVolumeSubscribers,void 0,"Voice volume"),()=>this.host.notify()])}finally{r()}}else this.voice=this._toVoiceSessionState(s,n,o),this.host.notify()})),r())||(i.push(s.onModeChange(n=>{this._voiceSession===s&&(o=n,this.voice&&(this.voice={...this.voice,mode:n},this.host.notify()))})),r())||(i.push(s.onVolumeChange(n=>{this._voiceSession===s&&(this._voiceVolume=n,_(this._voiceVolumeSubscribers,void 0,"Voice volume"))})),r()))return;i.push(s.onTranscript(n=>{this._voiceSession===s&&this._handleVoiceTranscript(n)})),r()||this.host.onConnected()}catch(o){if(this._voiceSession===s&&this._voiceUnsubs===i){try{this._disconnectVoice(!1)}catch(n){console.error("[assistant-ui] Voice rollback cleanup threw",n)}t&&this._voiceSession===void 0&&this.host.onDisconnected()}else r();throw o}}_currentAssistantMsg=null;_observeVoiceCommit(e){new Promise(t=>t(e())).catch(t=>{console.error("[assistant-ui] Voice message commit failed",t)})}_handleVoiceTranscript(e){let t=this._voiceSession;if(this.host.ensureInitialized(),this._voiceSession===t)if(e.role==="user"){if(this._finishVoiceAssistantMessage(),this._voiceSession!==t)return;this._currentAssistantMsg=null,e.isFinal&&this._observeVoiceCommit(()=>this._commitVoiceUserMessage({id:l(),role:"user",content:[{type:"text",text:e.text}],metadata:{modality:"voice",custom:{}},createdAt:new Date,attachments:[]}))}else{let s=e.isFinal?{type:"complete",reason:"stop"}:{type:"running"};if(!this._currentAssistantMsg)this._currentAssistantMsg={id:l(),role:"assistant",content:[{type:"text",text:e.text}],metadata:{unstable_state:this.host.state(),unstable_annotations:[],unstable_data:[],steps:[],modality:"voice",custom:{}},status:s,createdAt:new Date},this.voiceMessages.push(this._currentAssistantMsg);else{let i=this.voiceMessages.indexOf(this._currentAssistantMsg);if(i===-1)return;let r={...this._currentAssistantMsg,content:[{type:"text",text:e.text}],status:s};this.voiceMessages[i]=r,this._currentAssistantMsg=r}if(e.isFinal){let i=this._currentAssistantMsg;this._observeVoiceCommit(()=>this.host.commitVoiceMessage(i)),this._currentAssistantMsg=null}this.host.markVoiceMessagesDirty(),this.host.notify()}}_commitVoiceUserMessage(e){this.voiceMessages.push(e);try{return this.host.commitVoiceMessage(e)}finally{this.host.markVoiceMessagesDirty(),this.host.notify()}}async appendToVoiceSession(e){let t=this._voiceSession;if(!this.voice?.canSendText||!t?.sendText)throw new Error("Cannot send a text message while a voice session is connected");let s=e.content.filter(o=>o.type==="text");if(e.role!=="user"||e.sourceId!=null||e.parentId!==this.host.resolveAppendParent(this.host.messages().at(-1)?.id??null)||e.attachments?.length||s.length!==e.content.length||!s.some(o=>o.text.trim()))throw new Error("Only a plain text user message can be sent while a voice session is connected");let i=this.host.enrichAppendMetadata(e);this.host.ensureInitialized();let r=this.host.captureGeneration();try{await t.sendText(M(e))}catch(o){if(r.aborted)return;let n=new g;throw n.cause=o,n}if(!r.aborted){if(this._voiceSession!==t)throw new g("The voice session ended before the typed message was recorded");if(this._finishVoiceAssistantMessage(!1),this._voiceSession!==t)throw new g("The voice session ended before the typed message was recorded");this._currentAssistantMsg=null,await this._commitVoiceUserMessage({id:l(),role:"user",content:s,metadata:{custom:{...i.metadata?.custom}},createdAt:e.createdAt,attachments:[]})}}_finishVoiceAssistantMessage(e=!0){let t=this.voiceMessages.at(-1);if(t?.role==="assistant"&&t.status.type==="running"){let s=this.voiceMessages.length-1;this.voiceMessages[s]={...t,status:{type:"complete",reason:"stop"}},this._observeVoiceCommit(()=>this.host.commitVoiceMessage(this.voiceMessages[s])),this._currentAssistantMsg=null,this.host.markVoiceMessagesDirty(),e&&this.host.notify()}}disconnectVoice(){this._disconnectVoice(!0)}_disconnectVoice(e){this._finishVoiceAssistantMessage(!1),this._currentAssistantMsg=null;let t=this._voiceUnsubs.splice(0);this._voiceUnsubs=[];let s=this._voiceSession;this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;let i=this.host.stopSpeakingForVoiceMessage();this.voiceMessages=[],this.host.markVoiceMessagesDirty();try{p([...t,...i?[i]:[],...s?[()=>s.disconnect()]:[],()=>_(this._voiceVolumeSubscribers,void 0,"Voice volume"),()=>this.host.notify()])}finally{e&&s&&this._voiceSession===void 0&&this.host.onDisconnected()}}muteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this.host.notify()}unmuteVoice(){if(!this._voiceSession)throw new Error("No active voice session");this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this.host.notify()}};var j=class extends V{_isInitialized=!1;repository=new w;_voiceController=new f({adapter:()=>this.adapters?.voice,isRunning:()=>this.isRunning===!0,isRunActive:()=>this._isRunActive(),isLoading:()=>this.isLoading,getBaseMessages:()=>this._getBaseMessages(),messages:()=>this.messages,state:()=>this.state,notify:()=>this._notifySubscribers(),subscribe:e=>this.subscribe(e),captureGeneration:()=>x(this),ensureInitialized:()=>this.ensureInitialized(),commitVoiceMessage:e=>this._commitVoiceMessage(e),markVoiceMessagesDirty:()=>this._markVoiceMessagesDirty(),onConnected:()=>this._onVoiceConnected(),onDisconnected:()=>this._onVoiceDisconnected(),enrichAppendMetadata:e=>this.enrichAppendMetadata(e),resolveAppendParent:e=>this._resolveAppendParent(e),stopSpeakingForVoiceMessage:()=>this.speech&&this._isVoiceMessage(this.speech.messageId)?this._stopSpeaking:void 0});get _voiceMessages(){return this._voiceController.voiceMessages}set _voiceMessages(e){this._voiceController.voiceMessages=e}get _voiceGeneration(){return this._voiceController.voiceGeneration}set _voiceGeneration(e){this._voiceController.voiceGeneration=e}_markVoiceMessagesDirty(){this._voiceController.markMessagesDirty()}_getBaseMessages(){return this.repository.getMessages()}_commitVoiceMessage(e){}_onMessageMetadataChanged(e,t){}_dropVoiceMessage(e,t){this._voiceController.dropMessage(e,t)}get messages(){return this._voiceController.getMessages()}get state(){let e;for(let t of this.messages)t.role==="assistant"&&(e=t);return e?.metadata.unstable_state??null}composer=new A(this);_contextProvider;constructor(e){super(),this._contextProvider=e,C(this).addEventListener("abort",()=>{this.composer.__internal_dispose();for(let t of this._editComposers.values())t.__internal_dispose()})}getModelContext(){return this._contextProvider.getModelContext()}enrichAppendMetadata(e,t=e.parentId){if(e.role!=="user")return e;let s=this.messages,i=t===null?-1:s.findIndex(o=>o.id===t),r=y(this.getModelContext().unstable_composerMetadata,s.slice(0,i+1));return r?{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,...r}}}:e}_editComposers=new Map;getEditComposer(e){return this._editComposers.get(e)}__internal_getEditComposers(){return this._editComposers.values()}_isVoiceMessage(e){return this._voiceController.isVoiceMessage(e)}_resolveAppendParent(e){return this._isVoiceMessage(e)?this._getBaseMessages().at(-1)?.id??null:e}beginEdit(e){if(this.voice)throw new Error("Cannot edit a message while a voice session is connected");if(this._isVoiceMessage(e))throw new Error("Voice transcript messages cannot be edited");if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new k(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{let t=this.repository.getMessages(),s=this._voiceMessages.findIndex(i=>i.id===e);return s!==-1?{parentId:s>0?this._voiceMessages[s-1].id:t.at(-1)?.id??null,message:this._voiceMessages[s],index:t.length+s}:void 0}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifyEventSubscribers(e,t){let s=this._eventSubscribers.get(e);s&&v(s,t,`Thread runtime "${e}"`)}_notifyToolApprovalAnswered(e,t,s,i){this._notifyEventSubscribers("toolApprovalAnswered",{messageId:e,toolCallId:t,toolName:s,approved:i})}submitFeedback({messageId:e,type:t,comment:s}){let i=this.adapters?.feedback,r=this.getMessageById(e);if(!r)throw new Error(`Message not found: ${e}`);let{message:o,parentId:n}=r,u=s?.trim(),c={type:t,...u?{comment:u}:void 0};if(i?.submit({message:o,...c}),o.role==="assistant"){let h={...o,metadata:{...o.metadata,submittedFeedback:c}},a=this._voiceMessages.findIndex(d=>d.id===e);a===-1?(this.repository.addOrUpdateMessage(n,h),this._onMessageMetadataChanged(o,h)):(this._voiceMessages[a]=h,this._voiceController.replaceAssistantMessage(o,h),this._markVoiceMessagesDirty())}this._notifySubscribers()}_stopSpeaking;_replacingSpeech=!1;speech;speak(e){let t=this.adapters?.speech;if(!t)throw new Error("Speech adapter not configured");let s=this.getMessageById(e);if(!s)throw new Error(`Message not found: ${e}`);let{message:i}=s;if(this._replacingSpeech)return;let r=this._stopSpeaking,o;try{this._replacingSpeech=!0;try{r?.()}finally{this._replacingSpeech=!1}o=t.speak(b(i))}catch(a){if(r&&!this._stopSpeaking)try{this._notifySubscribers()}catch(d){console.error("[assistant-ui] Speech rollback notification threw",d)}throw a}let n,u=()=>{this._stopSpeaking=void 0,this.speech=void 0;let a=n;n=void 0,a?.()},c=()=>{if(this._stopSpeaking===c)try{u()}finally{o.cancel()}},h=()=>{this._stopSpeaking===c&&(o.status.type==="ended"?m([u,()=>this._notifySubscribers()]):(this.speech={messageId:e,status:o.status},this._notifySubscribers()))};this._stopSpeaking=c;try{if(n=o.subscribe(h),this._stopSpeaking!==c){n();return}h()}catch(a){if(this._stopSpeaking===c)try{m([c,()=>this._notifySubscribers()])}catch(d){console.error("[assistant-ui] Speech rollback cleanup threw",d)}throw a}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");m([this._stopSpeaking,()=>this._notifySubscribers()])}get voice(){return this._voiceController.voice}set voice(e){this._voiceController.voice=e}getVoiceVolume=()=>this._voiceController.getVoiceVolume();subscribeVoiceVolume=e=>this._voiceController.subscribeVoiceVolume(e);_onVoiceConnected(){}_onVoiceDisconnected(){}_isRunActive(){return this._voiceController.isRunActive()}_getVoiceCommitBarrier(){return this._voiceController.getVoiceCommitBarrier()}connectVoice(){this._voiceController.connectVoice()}async _appendToVoiceSession(e){return this._voiceController.appendToVoiceSession(e)}disconnectVoice(){this._voiceController.disconnectVoice()}muteVoice(){this._voiceController.muteVoice()}unmuteVoice(){this._voiceController.unmuteVoice()}ensureInitialized(){return this._isInitialized?!1:(this._isInitialized=!0,this._notifyEventSubscribers("initialize",{}),!0)}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(S.fromArray(e??[]))}_eventSubscribers=new Map;unstable_on(e,t){let s=t;if(e==="modelContextUpdate")return this._contextProvider.subscribe?.(()=>v([s],{},`Thread runtime "${e}"`))??(()=>{});let i=this._eventSubscribers.get(e);return i||(i=new Set,this._eventSubscribers.set(e,i)),i.add(s),e==="initialize"&&this._isInitialized&&queueMicrotask(()=>{i.has(s)&&v([s],{},`Thread runtime "${e}"`)}),()=>{this._eventSubscribers.get(e)?.delete(s)}}};export{j as BaseThreadRuntimeCore};
//# sourceMappingURL=base-thread-runtime-core.mjs.map