/* esm.sh - @assistant-ui/core@0.3.31/dist/runtime/base/base-composer-runtime-core */
import{generateId as S}from"../../utils/id.mjs";import{fileMatchesAccept as y}from"../../adapters/attachment.mjs";import{notifyEventListeners as T}from"../../utils/notify-event-listeners.mjs";import{BaseSubscribable as v}from"../../subscribable/subscribable.mjs";import{isMessageNotSentError as A}from"../../types/error.mjs";import{EMPTY_QUEUE_ITEMS as x}from"../queue/queue-item.mjs";import{isAttachmentComplete as m,isCreateAttachment as D}from"../../types/attachment.mjs";import{AttachmentAddOperations as w,drainAttachmentAdd as C}from"../utils/attachment-add-operations.mjs";import{AttachmentSendOperations as E}from"../utils/attachment-send-operations.mjs";import{matchInTransit as I,retainInTransit as q}from"../utils/composer-submission.mjs";var b=class{_host;constructor(t){this._host=t}rebase(t){if(!this._dictation)return;this._dictationBaseText=t,this._currentInterimText="";let{status:s,inputDisabled:i}=this._dictation;this._dictation=i?{status:s,inputDisabled:i}:{status:s}}cancel(){if(!this._dictationSession)return;let t=this._activeDictationSessionId;try{this._dictationSession.cancel()}catch(s){console.error("[assistant-ui] Dictation session cancel threw",s)}finally{this._cleanupDictation({sessionId:t})}}_dictation;_dictationSession;_stoppingDictationSession;_dictationUnsubscribes=[];_dictationBaseText="";_currentInterimText="";_dictationSessionIdCounter=0;_activeDictationSessionId;_isCleaningDictation=!1;get dictation(){return this._dictation}_isActiveSession(t,s){return this._activeDictationSessionId===t&&this._dictationSession===s}startDictation(){let t=this._host.getAdapter();if(!t)throw new Error("Dictation adapter not configured");let s=this._dictationSession!==void 0;if(this._dictationSession){let r=this._dictationSession;this._cleanupDictation({notify:!1}),this._stopDictationSession(r)}let i=t.disableInputDuringDictation??!1;this._dictationBaseText=this._host.getText(),this._currentInterimText="";let e;try{e=t.listen()}catch(r){if(s)try{this._host.notify()}catch(h){console.error("[assistant-ui] Dictation replacement rollback notification threw",h)}throw r}this._dictationSession=e;let n=++this._dictationSessionIdCounter;this._activeDictationSessionId=n,this._dictation={status:e.status,inputDisabled:i};try{this._host.notify()}catch(r){console.error("[assistant-ui] Dictation start notification threw",r)}if(!this._isActiveSession(n,e))return;let a=[],o=()=>{for(let r of a.splice(0))try{r()}catch(h){console.error("[assistant-ui] Dictation cleanup threw",h)}},c=r=>(a.push(r),this._isActiveSession(n,e)?!0:(o(),!1));try{if(!c(e.onSpeech(h=>{if(!this._isActiveSession(n,e))return;let d=h.isFinal!==!1,u=this._dictationBaseText&&!this._dictationBaseText.endsWith(" ")&&h.transcript?" ":"";if(d){if(this._dictationBaseText=this._dictationBaseText+u+h.transcript,this._currentInterimText="",this._host.setText(this._dictationBaseText),this._dictation){let{transcript:p,..._}=this._dictation;this._dictation=_}this._host.notify()}else this._currentInterimText=u+h.transcript,this._host.setText(this._dictationBaseText+this._currentInterimText),this._dictation&&(this._dictation={...this._dictation,transcript:h.transcript}),this._host.notify()}))||!c(e.onSpeechStart(()=>{this._isActiveSession(n,e)&&(this._dictation={status:{type:"running"},inputDisabled:i,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._host.notify())}))||!c(e.onSpeechEnd(()=>{this._cleanupDictation({sessionId:n})})))return;let r=setInterval(()=>{this._isActiveSession(n,e)&&e.status.type==="ended"&&this._cleanupDictation({sessionId:n})},100);if(!c(()=>clearInterval(r)))return;this._dictationUnsubscribes.push(...a.splice(0))}catch(r){if(o(),this._isActiveSession(n,e))try{e.cancel()}catch(h){console.error("[assistant-ui] Dictation session cancel threw",h)}finally{this._cleanupDictation({sessionId:n})}throw r}}stopDictation(){if(!this._dictationSession)return;let t=this._dictationSession;if(this._stoppingDictationSession===t)return;this._stoppingDictationSession=t;let s=this._activeDictationSessionId,i=()=>this._cleanupDictation({sessionId:s});this._stopDictationSession(t,i)}_stopDictationSession(t,s=()=>{}){let i;try{i=t.stop()}catch(e){console.error("[assistant-ui] Dictation session stop threw",e),s();return}i.then(s,e=>{console.error("[assistant-ui] Dictation session stop rejected",e),s()})}_cleanupDictation(t){if(t?.sessionId!==void 0&&t.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)return;this._isCleaningDictation=!0;let s=i=>{try{i()}catch(e){console.error("[assistant-ui] Dictation cleanup threw",e)}};try{let i=this._dictationUnsubscribes;this._dictationUnsubscribes=[],this._dictationSession=void 0,this._stoppingDictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText="",this._currentInterimText="";for(let e of i)s(e);t?.notify!==!1&&s(()=>this._host.notify())}finally{this._isCleaningDictation=!1}}};var z=class extends v{isEditing=!0;enrichWithComposerMetadata(t,s){return s?{...t,metadata:{...t.metadata,custom:{...t.metadata?.custom,...s}}}:t}get attachmentAccept(){return this.getAttachmentAdapter()?.accept??"*"}_attachments=[];get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.sendableAttachments.length}get sendableAttachments(){return this.attachments.filter(t=>!this._attachmentSends.isRemoved(t))}_text="";_dictationSessionController=new b({getAdapter:()=>this.getDictationAdapter(),getText:()=>this._text,setText:t=>this._writeText(t,"user"),notify:()=>this._notifySubscribers()});get text(){return this._text}_role="user";get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}_quote=void 0;get quote(){return this._quote}setQuote(t){this._quote!==t&&(this._quote=t,this._notifySubscribers())}setText(t,s){this._text!==t&&(this._writeText(t,s?.origin??"external"),this._rebaseDictation(t),this._notifySubscribers())}_pendingTextChanges=[];_isFlushingTextChanges=!1;_notifyDepth=0;_writeText(t,s){this._text!==t&&(this._text=t,this._pendingTextChanges.push({text:t,origin:s}))}_notifySubscribers(){this._notifyDepth++;try{super._notifySubscribers()}finally{--this._notifyDepth===0&&this._flushTextChanges()}}_flushTextChanges(){if(!this._isFlushingTextChanges){this._isFlushingTextChanges=!0;for(let t=this._pendingTextChanges.shift();t;t=this._pendingTextChanges.shift())this._notifyEventSubscribers("textChange",t);this._isFlushingTextChanges=!1}}_rebaseDictation(t){this._dictationSessionController.rebase(t)}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_submission;_submissionSend;_inTransit=[];_inTransitSubmissions=[];_sendGeneration=0;_draftEpoch=0;_attachmentAddOperations=new w;_attachmentSends=new E;get submission(){return this._submission}get inTransit(){return this._inTransitSubmissions}get isSubmitting(){return this._submission!==void 0}get detachesDraftOnSend(){return!0}threadMessageIds(t){}settleInTransit(){if(this._inTransit.length===0)return;let t=I(this._inTransit,s=>this.threadMessageIds(s.submission.role));t.landed.size!==0&&(this._setInTransit(q(this._inTransit,t)),this._notifySubscribers())}_setInTransit(t){this._inTransit=t,this._inTransitSubmissions=t.map(s=>s.submission)}_leaveTransit(t){let s=this._inTransit.filter(i=>i.submission!==t);return s.length===this._inTransit.length?!1:(this._setInTransit(s),!0)}_cancelAttachmentAdd(t){this._attachmentAddOperations.cancel(t)}_cancelAllAttachmentAdds(){this._attachmentAddOperations.cancelAll()}_emptyTextAndAttachments(){this._attachments=[],this._writeText("","reset"),this._rebaseDictation(""),this._notifySubscribers()}_draftUploadsToRemove(){return this._attachments.filter(t=>!m(t)&&this._attachmentSends.shouldRemoveOnClear(t))}async _onClearAttachments(t){let s=this.getAttachmentAdapter();s&&await Promise.all(t.map(i=>(this._attachmentSends.beginRemoval(i),this._attachmentSends.remove(i,s))))}async reset(){this._cancelAllAttachmentAdds(),this._draftEpoch++,this._sendGeneration++;let t=this._discardSubmission();if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0&&this._quote===void 0){await t;return}this._role="user",this._runConfig={},this._quote=void 0;let s=this._onClearAttachments(this._draftUploadsToRemove());this._emptyTextAndAttachments(),await Promise.all([s,t])}async clearAttachments(){this._draftEpoch++,this._attachmentAddOperations.cancelAll(this.detachesDraftOnSend?new Set(this._submission?.attachments.map(i=>i.id)):void 0);let t=this._draftUploadsToRemove();if(this.isSubmitting)for(let i of this._attachments)this._attachmentSends.beginRemoval(i);let s=this._onClearAttachments(t);this.setAttachments([]),await s}async send(t){if(!this.canSend||this.isSubmitting)return;this._dictationSessionController.cancel();let s=this.sendableAttachments;if(!this.text.trim()&&s.length===0)return;let i={id:S(),role:this.role,text:this.text,quote:this._quote,attachments:s},e={options:t,runConfig:this.runConfig},n=s.filter(m),a=n.length===s.length;if(a||(this._submission=i,this._submissionSend={...e,controller:new AbortController}),this.detachesDraftOnSend){let c=new Set(s);this._attachments=this._attachments.filter(r=>!c.has(r)),this._writeText("","send"),this._rebaseDictation(""),this._quote=void 0}let o=++this._sendGeneration;if(this._notifySubscribers(),a){this._dispatch(o,i,n,e,!1);return}await this._prepareSubmission(o)}async _prepareSubmission(t){let s=this.getAttachmentAdapter(),i=(this._submission?.attachments??[]).flatMap(d=>{let u=this._attachmentAddOperations.whenSendable(d.id);return u?[u]:[]});if(i.length>0&&(await Promise.all(i),t!==this._sendGeneration))return;let e=this._submission,n=this._submissionSend;if(!e||!n)return;let a=e.attachments.filter(d=>!this._attachmentSends.isRemoved(d));for(let d of a)this._cancelAttachmentAdd(d.id);let o=await Promise.allSettled(a.map(d=>this._attachmentSends.send(d,s,n.controller.signal)));if(t!==this._sendGeneration)return;let c=o.find(d=>d.status==="rejected");if(c){this._returnSubmissionToDraft(a,o,c.reason);return}let r=o.flatMap((d,u)=>this._attachmentSends.isRemoved(a[u])||d.status==="rejected"?[]:[d.value]),h=this._submission??e;if(!h.text.trim()&&r.length===0){this._endSubmission(),this._returnToDraft(h);return}this._dispatch(t,h,r,n,!0)}_dispatch(t,s,i,e,n){let a={createdAt:new Date,role:s.role,content:s.text?[{type:"text",text:s.text}]:[],attachments:i,runConfig:e.runConfig,metadata:{custom:{...s.quote?{quote:s.quote}:{}}}},o={...s,attachments:i},c=new Map(s.attachments.filter(_=>!this._attachmentSends.isRemoved(_)).map((_,l)=>[_,i[l]])),r={...s,attachments:s.attachments.map(_=>c.get(_)??_)},h=this.queue.length;if(n){if(this._submission=void 0,this._submissionSend=void 0,!this.detachesDraftOnSend){let l=new Map(s.attachments.map((f,g)=>[f.id,r.attachments[g]]));this._attachments=this._attachments.map(f=>l.get(f.id)??f)}let _=this.threadMessageIds(s.role);_&&this._setInTransit([...this._inTransit,{submission:o,known:new Set(_)}])}let d=this.cleanupOwner,u=d._draftEpoch,p;try{p=this.handleSend(a,e.options)}catch(_){console.error("[assistant-ui] Failed to send the message",_),this._leaveTransit(o),t===this._sendGeneration?this._returnToDraft(r):this._notifySubscribers();return}if(p&&p.catch(_=>{let l=this._leaveTransit(o);t===this._sendGeneration&&A(_)?this._returnToDraft(r):l&&this._notifySubscribers()}),n)for(let _ of s.attachments)m(_)||this._attachmentSends.dispatchRemoval(_,()=>{this._retrySubmittedRemoval(_,d,u)});this._notifyEventSubscribers("send",{chars:s.text.length,attachments:i.length}),n&&(this.queue.length>h&&this._leaveTransit(o),this._notifySubscribers(),this.settleInTransit())}_returnSubmissionToDraft(t,s,i){let e=this._submission;if(!e)return;let n=this._attachmentSends.reconcileFailures(e.attachments,t,s);this._endSubmission(),this._returnToDraft({...e,attachments:n}),console.error("[assistant-ui] Failed to send attachments",i)}_endSubmission(){this._sendGeneration++,this._submission=void 0,this._submissionSend=void 0}__internal_dispose(){this._cancelAllAttachmentAdds(),this._submission&&(this._submissionSend?.controller.abort(),this._endSubmission(),this._notifySubscribers())}cancelSubmission(){let t=this._submission;t&&(this._submissionSend?.controller.abort(),this._endSubmission(),this._returnToDraft(t))}_returnToDraft(t){if(this.detachesDraftOnSend){let s=t.attachments.flatMap(e=>{let n=this._attachmentSends.restoreUnsent(e);return n?[n]:[]});this._attachments=[...s,...this._attachments];let i=[t.text,this._text].filter(Boolean).join(`
`);this._writeText(i,"return"),this._rebaseDictation(i),this._quote=this._quote??t.quote}else{let s=new Map(t.attachments.flatMap(i=>{let e=this._attachmentSends.restoreUnsent(i);return e?[[i.id,e]]:[]}));this._attachments=this._attachments.flatMap(i=>{let e=this._attachmentSends.restoreUnsent(i);return e?[s.get(i.id)??e]:[]})}this._notifySubscribers()}async _discardSubmission(){let t=this._submission;if(!t)return;this._submissionSend?.controller.abort(),this._endSubmission(),this._notifySubscribers();let s=this.getAttachmentAdapter();if(!s)return;let i=new Set(this._attachments.map(e=>e.id));await Promise.all(t.attachments.filter(e=>!m(e)&&!i.has(e.id)&&!this._attachmentSends.isRemovalPending(e)).map(async e=>s.remove(e)))}restoreDraft(t){return this._text.trim()||this._quote!==void 0||this._attachments.length>0?!1:(this._writeText(t.text,"return"),this._rebaseDictation(t.text),this._quote=t.quote,this._attachments=t.attachments??[],this._notifySubscribers(),!0)}retractDraft(t){let s=t.attachments!==void 0?this._attachments===t.attachments:this._attachments.length===0;this._text!==t.text||this._quote!==t.quote||!s||(this._writeText("","send"),this._rebaseDictation(""),this._quote=void 0,this._attachments=[],this._notifySubscribers())}cancel(){this.isSubmitting&&!this.detachesDraftOnSend&&(this._submissionSend?.controller.abort(),this._endSubmission(),this._notifySubscribers()),this.handleCancel()}get queue(){return x}moveQueueItem(t,s){}removeQueueItem(t){}async addAttachment(t){if(D(t)){let a=this.getAttachmentAdapter();if(a&&!y({name:t.name,type:t.contentType??""},a.accept)){let c=`File type ${t.contentType||"unknown"} is not accepted. Accepted types: ${a.accept}`,r=new Error(c);throw this._safeEmitAttachmentAddError("not-accepted",c,void 0,r,t.contentType),r}let o={id:t.id??S(),type:t.type??"document",name:t.name,contentType:t.contentType,content:t.content,status:{type:"complete"}};this._attachments=[...this._attachments,o],this._notifySubscribers(),this._notifyEventSubscribers("attachmentAdd",{...o.contentType?{contentType:o.contentType}:void 0});return}let s=this.getAttachmentAdapter();if(!s){let a="Attachments are not supported",o=new Error(a);throw this._safeEmitAttachmentAddError("no-adapter",a,void 0,o,t.type),o}if(!y({name:t.name,type:t.type},s.accept)){let a=`File type ${t.type||"unknown"} is not accepted. Accepted types: ${s.accept}`,o=new Error(a);throw this._safeEmitAttachmentAddError("not-accepted",a,void 0,o,t.type),o}let i=this._attachmentAddOperations.start(),e=a=>{if(!this._attachmentAddOperations.accept(i,a))return!1;let o=this._submission,c=o?.attachments.some(h=>h.id===a.id)??!1;o&&c&&(this._submission={...o,attachments:o.attachments.map(h=>h.id===a.id?this._attachmentSends.transfer(h,a):h)});let r=this._attachments.findIndex(h=>h.id===a.id);return r!==-1?this._attachments=[...this._attachments.slice(0,r),a,...this._attachments.slice(r+1)]:c||(this._attachments=[...this._attachments,a]),this._notifySubscribers(),!0},n;try{await C(s.add({file:t}),a=>(n=a,e(a)))}catch(a){if(this._attachmentAddOperations.isCancelled(i))return;throw n&&e({...n,status:{type:"incomplete",reason:"error",message:a instanceof Error?a.message:String(a)}}),this._safeEmitAttachmentAddError("adapter-error",a instanceof Error?a.message:String(a),n?.id,a instanceof Error?a:void 0,n?.contentType||t.type),a}finally{this._attachmentAddOperations.finish(i)}this._attachmentAddOperations.isCancelled(i)||(n?.status.type==="incomplete"&&n.status.reason==="error"?this._safeEmitAttachmentAddError("adapter-error",n.status.message??"Attachment upload did not complete successfully.",n.id,void 0,n.contentType||t.type):this._notifyEventSubscribers("attachmentAdd",{...n?.contentType?{contentType:n.contentType}:t.type?{contentType:t.type}:void 0}))}_safeEmitAttachmentAddError(t,s,i,e,n){try{this._notifyEventSubscribers("attachmentAddError",{reason:t,message:s,...i!==void 0&&{attachmentId:i},...e!==void 0&&{error:e},...n?{contentType:n}:void 0})}catch(a){console.error("[assistant-ui] attachmentAddError subscriber threw:",a)}}async removeAttachment(t){let s=this._attachments.find(n=>n.id===t)??this._submission?.attachments.find(n=>n.id===t);if(!s)throw new Error("Attachment not found");let i=this.getAttachmentAdapter();if(!m(s)&&!i)throw new Error("Attachments are not supported");if(!this._attachmentSends.beginRemoval(s))return;this._cancelAttachmentAdd(t),this._notifySubscribers(),await this._attachmentSends.remove(s,i,(n,a)=>{let o=r=>this._attachmentSends.transfer(r,{...r,status:{type:"incomplete",reason:"error",message:a}}),c=this._submission;c&&(this._submission={...c,attachments:c.attachments.map(r=>!m(r)&&this._attachmentSends.isSameRemoval(r,s)?o(r):r)}),this._attachments.some(r=>this._attachmentSends.isSameRemoval(r,s))&&(this._attachments=this._attachments.map(r=>!m(r)&&this._attachmentSends.isSameRemoval(r,s)?o(r):r),this._submission||(this._attachments=this._attachments.map(r=>this._attachmentSends.isSameRemoval(r,s)?this._attachmentSends.restore(r):r))),this._notifySubscribers()});let e=this._submission;e&&(this._submission={...e,attachments:e.attachments.filter(n=>!this._attachmentSends.isSameRemoval(n,s))}),this._attachments.some(n=>this._attachmentSends.isSameRemoval(n,s))&&(this._attachments=this._attachments.filter(n=>!this._attachmentSends.isSameRemoval(n,s))),this._notifySubscribers()}get cleanupOwner(){return this}_adoptCleanupFailure(t,s,i){this._draftEpoch===i&&(this._attachments.some(e=>e.id===s.id)||(this._attachmentSends.adoptFrom(t,s),this._attachments=[s,...this._attachments],this._notifySubscribers()))}async _retrySubmittedRemoval(t,s,i){this._attachmentSends.beginRemoval(t),await this._attachmentSends.remove(t,this.getAttachmentAdapter(),(e,n)=>{console.error("[assistant-ui] Failed to remove sent attachment",e);let a=this._attachmentSends.transfer(t,{...t,status:{type:"incomplete",reason:"error",message:n}});s._adoptCleanupFailure(this._attachmentSends,a,i)}).catch(()=>{})}get dictation(){return this._dictationSessionController.dictation}startDictation(){this._dictationSessionController.startDictation()}stopDictation(){this._dictationSessionController.stopDictation()}_eventSubscribers=new Map;_notifyEventSubscribers(t,s){let i=this._eventSubscribers.get(t);i&&T(i,s,`Composer runtime "${t}"`)}unstable_on(t,s){let i=s,e=this._eventSubscribers.get(t);return e||(e=new Set,this._eventSubscribers.set(t,e)),e.add(i),()=>{this._eventSubscribers.get(t)?.delete(i)}}};export{z as BaseComposerRuntimeCore};
//# sourceMappingURL=base-composer-runtime-core.mjs.map