/* esm.sh - @assistant-ui/core@0.3.31/dist/runtimes/local/local-thread-runtime-core */
import{generateId as x}from"../../utils/id.mjs";import{consumeSuggestionResult as z}from"../../adapters/suggestion.mjs";import{MessageNotSentError as D,toAssistantError as k}from"../../types/error.mjs";import{appendToolInteraction as O}from"../../runtime/utils/tool-interactions.mjs";import{fromThreadMessageLike as Q}from"../../runtime/utils/thread-message-like.mjs";import{getAutoStatus as U}from"../../runtime/utils/auto-status.mjs";import{withoutOrphanedMessages as V}from"../../runtime/utils/message-repository.mjs";import{EMPTY_QUEUE_ITEMS as F}from"../../runtime/queue/queue-item.mjs";import{createMessageQueue as N}from"../../runtime/queue/message-queue.mjs";import{captureThreadRuntimeGeneration as E,invalidateThreadRuntime as j,supersedeThreadRuntime as Y}from"../../runtime/utils/thread-runtime-lifecycle.mjs";import{BaseThreadRuntimeCore as J}from"../../runtime/base/base-thread-runtime-core.mjs";import{shouldContinue as S}from"./should-continue.mjs";var B=class extends Error{name="AbortError";detach;constructor(t,e){super(e),this.detach=t}},K=t=>t.role!=="assistant"||t.status.type!=="requires-action"||t.status.reason!=="interrupt"||t.content.some(e=>e.type==="tool-call"&&e.result===void 0&&e.interrupt!=null)?t:{...t,status:U(!1,!1,!1,t.content.some(e=>e.type==="tool-call"&&e.result===void 0))},P=t=>{let e=!1,r=t.content.map(s=>s.type!=="tool-call"||s.approval===void 0||s.approval.approved!==void 0||s.approval.resolution!==void 0?s:(e=!0,{...s,approval:{...s.approval,resolution:"cancelled"}})),i=t.status.type==="running"||t.status.type==="requires-action";return!e&&!i?t:{...t,content:r,status:i?{type:"incomplete",reason:"cancelled"}:t.status}},A=t=>{let e=new Set(t.messages.map(r=>r.parentId));return{...t,messages:t.messages.map(r=>({...r,message:r.message.role==="assistant"&&e.has(r.message.id)?P(r.message):K(r.message)}))}},G=t=>{if(t.role!=="assistant")return t;let e=!1,r=t.content.map(i=>{if(i.type!=="tool-call")return i;let s=i.messages?.map(G),o=s?.some((a,h)=>a!==i.messages?.[h]);if(i.unstable_interactions===void 0&&o!==!0)return i;e=!0;let{unstable_interactions:n,...u}=i;return o?{...u,messages:s}:u});return e?{...t,content:r}:t},ut=class extends J{capabilities={switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,delete:!1,reload:!0,refetchThread:!1,cancel:!0,unstable_copy:!0,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1,answerToolCall:!0};abortController=null;_queue=null;_queueRunInFlight=null;_activeRun=null;_queueBusy=!1;_queueCancelReserved=!1;_messageReplacements=new WeakMap;_historyWrites=new Map;_unwrittenSeedMessages=new Set;_runStarted=!1;async _writeHistory(t,e,r){let i=this._loadGeneration;try{await r()}catch(s){throw console.error("[assistant-ui] local thread history write failed:",s),i===this._loadGeneration&&this._notifyEventSubscribers("historyWriteError",{operation:t,messageIds:e,message:s instanceof Error?s.message:String(s),error:s}),s}}_deletedMessages=new Map;_chainHistoryWrite(t,e){let r=this._loadGeneration,i=()=>r===this._loadGeneration?e():Promise.resolve(),s=this._deletedMessages.get(t);if(s)return s.suppressed?.push(i),Promise.resolve();let o=this._unwrittenSeedMessages.has(t);if(o&&!this._runStarted)return Promise.resolve();let n=this._options.adapters.history;if(n&&this._unwrittenSeedMessages.size>0){let l=this.repository.export().messages.filter(p=>this._unwrittenSeedMessages.has(p.message.id));this._unwrittenSeedMessages.clear();let _;for(let p of l){let f=this._chainHistoryWrite(p.message.id,()=>this._writeHistory("append",[p.message.id],()=>n.append(p)));p.message.id===t?_=f:f.catch(()=>{})}if(o)return _??Promise.resolve()}let u=this._historyWrites.get(t),a;if(u)a=u.then(i,i);else try{a=Promise.resolve(i())}catch(l){a=Promise.reject(l)}let h=a.then(()=>{},()=>{});return this._historyWrites.set(t,h),h.then(()=>{this._historyWrites.get(t)===h&&this._historyWrites.delete(t)}),a}_persistMessageUpdate(t){let e=this._options.adapters.history;if(!e)return;let r;try{r=this.repository.getMessage(t)}catch{return}let{parentId:i,message:s}=r;s.role!=="assistant"||s.status.type==="running"||this._unwrittenMessages.has(s.id)&&!e.update&&s.status.type==="requires-action"||this._persistSettled(i,s)?.catch(()=>{})}_roundtripsInFlight=new Map;_followedDuringRun=new Set;_unwrittenMessages=new Set;_persistSettled(t,e){let r=this._options.adapters.history;if(!r)return;let i=this._unwrittenMessages.delete(e.id)||this._unwrittenSeedMessages.has(e.id)?"append":"update",s=i==="append"?r.append:r.update;if(!s)return;let o={parentId:t,message:e,runConfig:this._lastRunConfig};return this._chainHistoryWrite(e.id,()=>this._writeHistory(i,[e.id],()=>s.call(r,o)))}_cancelPause(t){if(t===null)return;let e;try{e=this.repository.getMessage(t)}catch{return}if(e.message.role!=="assistant")return;if(this._roundtripsInFlight.has(t)){this._followedDuringRun.add(t);let i=P(e.message),s=this._options.adapters.history;if(s&&!s.update&&this._roundtripsInFlight.get(t)?.resumedFromPause&&!this._unwrittenMessages.has(t)){let o={parentId:e.parentId,message:i,runConfig:this._lastRunConfig};return this._chainHistoryWrite(t,()=>this._writeHistory("append",[t],()=>s.append(o)))}return this._persistSettled(e.parentId,i)}let r=P(e.message);if(r!==e.message)return this.repository.addOrUpdateMessage(e.parentId,r),this._persistSettled(e.parentId,r)}_resumeIfReady(t){let e=this.getMessageById(t);return e?.message.role!=="assistant"||this.repository.hasChildren(t)||this._followedDuringRun.has(t)||!S(e.message,this._options.unstable_humanToolNames)?!1:(this._runLoop(e.parentId,e.message,this._lastRunConfig).catch(()=>{}),!0)}isDisabled=!1;isSendDisabled=!1;get isRunning(){return this._activeRun?.isRunning||this._roundtripsInFlight.size>0?!0:void 0}_isLoading=!1;get isLoading(){return this._isLoading}_suggestions=[];_suggestionsController=null;get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}constructor(t,e,r){if(super(t),this.__internal_setOptions(e),r){this.repository.import(A(r));for(let{message:i}of r.messages)this._unwrittenSeedMessages.add(i.id)}}_options;_historyScopeInitialized=!1;_historyScopeId;_lastRunConfig={};_getThreadId;__internal_setGetThreadId(t){this._getThreadId=t}_getInitializePromise;_pendingInitialization;__internal_setGetInitializePromise(t){this._getInitializePromise=t}get extras(){}__internal_setOptions(t){if(this._options===t)return;let e=this._options?.adapters.history,r=this._options?.adapters.suggestion,i=t.adapters.history,s=i!==void 0&&this._historyScopeInitialized&&this._historyScopeId!==i.scopeId;i&&(this._historyScopeInitialized=!0,this._historyScopeId=i.scopeId);let o=this._loadRequested&&s;if(o&&(this._loadGeneration++,this._historyWrites.clear(),this._deletedMessages.clear(),this._roundtripsInFlight.clear(),this._followedDuringRun.clear(),this._unwrittenMessages.clear(),this._unwrittenSeedMessages.clear(),this._queue?.clear(),this.cancelRun(),Y(this),this._queue=null,this._queueRunInFlight=null,this._activeRun=null,this._appendsBeforeRun=0,this.composer.reset().catch(v=>{console.error("[assistant-ui] Composer reset threw after the history scope changed",v)}),this._suggestions=[],this._lastRunConfig={},this.repository.clear(),this._loadPromise=void 0,this._isLoading=!1),this._options=t,!t.adapters.voice&&this.voice)try{this.disconnectVoice()}catch(v){console.error("[assistant-ui] Voice cleanup threw after the adapter changed",v)}let n=o,u=t.adapters.suggestion;u?(!r||r.key!==u.key)&&(this._suggestionsController?.abort(),this._suggestionsController=null,this._suggestions.length>0&&(this._suggestions=[],n=!0),this._generateSuggestions()):(this._suggestionsController?.abort(),this._suggestionsController=null,this._suggestions.length>0&&(this._suggestions=[],n=!0));let a=t.adapters?.speech!==void 0;this.capabilities.speech!==a&&(this.capabilities.speech=a,n=!0);let h=t.adapters?.dictation!==void 0;this.capabilities.dictation!==h&&(this.capabilities.dictation=h,n=!0);let l=t.adapters?.voice!==void 0;this.capabilities.voice!==l&&(this.capabilities.voice=l,n=!0);let _=t.adapters?.attachments!==void 0;this.capabilities.attachments!==_&&(this.capabilities.attachments=_,n=!0);let p=t.adapters?.feedback!==void 0;this.capabilities.feedback!==p&&(this.capabilities.feedback=p,n=!0);let f=t.adapters?.history?.delete!==void 0;this.capabilities.delete!==f&&(this.capabilities.delete=f,n=!0);let I=t.unstable_enableMessageQueue===!0;I&&!this._queue?(this._queue=N({run:v=>{let T={};this._queueRunInFlight=T,this._runAppend({...v,parentId:this._resolveAppendParent(this.messages.at(-1)?.id??null)}).finally(()=>{this._queueRunInFlight===T&&(this._queueRunInFlight=null)}).catch(()=>{})}}),this.voice&&this._queue.hold(),this._queueBusy=!1,this._queueCancelReserved=!1,this._syncQueue(),this._queue.subscribe(()=>this._notifySubscribers())):!I&&this._queue&&(this._queue=null),this.capabilities.queue!==I&&(this.capabilities.queue=I,n=!0),n&&this._notifySubscribers(),this._loadRequested&&!this._loadPromise&&i&&(s||!e&&this.messages.length===0)&&this.__internal_load().catch(v=>{console.error("[assistant-ui] local thread history load failed:",v)})}_loadPromise;_loadGeneration=0;_loadImports=0;_loadRequested=!1;__internal_load(){if(this._loadRequested=!0,this._loadPromise)return this._loadPromise;if(!this.adapters.history)return Promise.resolve();this._isLoading=!0;let t=this.adapters.history,e=t.scopeId,r=this._loadGeneration,i=!1,o=(async()=>{let n;try{n=await t.load()}catch(p){if(r!==this._loadGeneration)return;let f=this.adapters.history;if(f&&f.scopeId!==e)return;throw i=!0,p}if(r!==this._loadGeneration)return;let u=this.adapters.history;if(u&&u.scopeId!==e||!n)return;let{repository:a,droppedIds:h}=V(n);if(h.length>0&&console.warn("[assistant-ui] Skipped history messages with missing parents:",h),n.headId!=null&&!n.messages.some(p=>p.message.id===n.headId)&&console.warn("[assistant-ui] History head is not among the loaded messages:",n.headId),(a.messages.length>0||this._unwrittenSeedMessages.size===0)&&(this._unwrittenSeedMessages.clear(),this._loadImports++,this.repository.clear(),this.repository.import(A(a))),a.messages.length>0&&this.ensureInitialized(),this._notifySubscribers(),r!==this._loadGeneration)return;let l=this.adapters.history;if(!l||l.scopeId!==e)return;let _=l.resume?.bind(l);n.unstable_resume&&_&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},_).catch(()=>{})})().finally(()=>{r!==this._loadGeneration||this._loadPromise!==o||(this._isLoading=!1,i&&!this.adapters.history&&(this._loadPromise=void 0),this._notifySubscribers())});return this._loadPromise=o,this._notifySubscribers(),o}_getHistoryLoadBarrier(t){if(!this._isLoading||!this._loadPromise)return;let e=this._loadPromise;return new Promise(r=>{let i=()=>{t.removeEventListener("abort",i),r()};if(t.aborted){i();return}t.addEventListener("abort",i,{once:!0}),e.then(i,i)})}async append(t){if(t={...t,parentId:this._resolveAppendParent(t.parentId)},this.voice)return this._appendToVoiceSession(t);if(this._isVoiceMessage(t.sourceId))throw new Error("Voice transcript messages cannot be edited");let e=t.parentId===(this.messages.at(-1)?.id??null),r=t.startRun??t.role==="user";if(this._queue&&r&&e){t.steer??this._queueRunInFlight!==null?this._queue.adapter.steer(t):this._queue.adapter.enqueue(t);return}return this._queue&&!e&&(this._options.unstable_queueClearOnRewind??!0)&&this._queue.clear(),this._runAppend(t)}_commitVoiceMessage(t){let e=E(this),r=s=>{if(e.aborted){this._dropVoiceMessage(t.id,s);return}let o=this.repository.headId;this.repository.addOrUpdateMessage(o,t);let n=this._cancelPause(o);this.repository.resetHead(t.id);let u=this._options.adapters.history,a=u?this._chainHistoryWrite(t.id,()=>this._writeHistory("append",[t.id],()=>u.append({parentId:o,message:t}))):void 0;return a?.catch(()=>{}),this._dropVoiceMessage(t.id,!1),s&&this._notifySubscribers(),n?Promise.all([n,a]).then(()=>{}):a},i=this._getVoiceCommitBarrier();return i?i.then(()=>r(!0)):r(!1)}_onVoiceConnected(){this._queue?.hold()}_onVoiceDisconnected(){this._queue?.release()}getQueueItems(){return this._queue?.adapter.items??F}getSteerQueueItems(){return this._queue?.adapter.steerItems??F}moveQueueItem(t,e){this._queue?.adapter.move(t,e)}removeQueueItem(t){this._queue?.adapter.remove(t)}_rollbackAppend(t){try{if(this.repository.getMessage(t.id).message!==t)return;this.repository.deleteMessage(t.id)}catch{return}this._notifySubscribers()}_pendingAppends=0;_isRunActive(){return this._pendingAppends>0||super._isRunActive()}_appendsBeforeRun=0;_isQueueBusy(){return this._appendsBeforeRun>0||this._activeRun!==null}_syncQueue(){let t=this._queue;if(!t)return;let e=this._isQueueBusy();e&&!this._queueBusy?(this._queueBusy=!0,t.notifyBusy()):!e&&this._queueBusy&&queueMicrotask(()=>{this._queue!==t||!this._queueBusy||this._isQueueBusy()||(this._queueBusy=!1,this._queueCancelReserved=!1,t.notifyIdle())})}async _runAppend(t){let e=this._loadGeneration;this._pendingAppends+=1,this._appendsBeforeRun+=1;let r=!0,i=()=>{r&&(r=!1,e===this._loadGeneration&&(this._appendsBeforeRun-=1))};this._syncQueue();try{await this._runAppendInner(t,i)}finally{this._pendingAppends-=1,i(),this._syncQueue()}}async _runAppendInner(t,e){let r=E(this),i=this._getHistoryLoadBarrier(r);if(i){let l=t.parentId===(this.messages.at(-1)?.id??null);if(await i,r.aborted)return;l&&(t={...t,parentId:this._resolveAppendParent(this.messages.at(-1)?.id??null)})}let s=this.enrichAppendMetadata(t);this.ensureInitialized();let o=Q(s,x(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(s.parentId,o),this._notifySubscribers();try{let l=this._getInitializePromise?.();l&&await l}catch(l){if(this._rollbackAppend(o),r.aborted)return;s.parentId!==null&&this._resumeIfReady(s.parentId);let _=new D;throw _.cause=l,_}if(r.aborted){this._rollbackAppend(o);return}let n=this._cancelPause(s.parentId),u=this._options.adapters.history,a=u?this._chainHistoryWrite(o.id,()=>this._writeHistory("append",[o.id],()=>u.append({parentId:s.parentId,message:o,...s.runConfig!==void 0&&{runConfig:s.runConfig}}))):void 0,h=n?Promise.all([n,a]).then(()=>{}):a;if(h?.catch(()=>{}),s.startRun??s.role==="user"){e();let[l,_]=await Promise.allSettled([this.startRun({parentId:o.id,sourceId:s.sourceId,runConfig:s.runConfig??{}}),h]);if(l.status==="rejected")throw l.reason;if(_.status==="rejected")throw _.reason}else this.repository.switchToBranch(o.id),this._notifySubscribers(),await h}async deleteMessage(t){let e=this._loadGeneration,r=this._options.adapters.history;if(!r?.delete)throw new Error("Runtime does not support deleting messages.");let i=this.repository.getMessages(),s=i.findIndex(p=>p.id===t);if(s===-1)throw new Error("Message not found.");if(this._unwrittenSeedMessages.delete(t)){this._deletedMessages.set(t,{suppressed:null}),this.repository.deleteMessage(t),this._notifySubscribers();return}let o=this._deletedMessages.get(t);if(o?.suppressed&&o.deletion)return o.deletion;let n=r.delete.bind(r),u=p=>this._writeHistory("delete",p.map(f=>f.message.id),()=>n(p)),a=i[s],h=[{parentId:i[s-1]?.id??null,message:a}],l=this._historyWrites.get(t),_={suppressed:[]};return this._deletedMessages.set(t,_),_.deletion=(async()=>{try{await u(h)}catch(p){let f=_.suppressed??[];if(_.suppressed=null,this._deletedMessages.get(t)===_){this._deletedMessages.delete(t);for(let I of f)this._chainHistoryWrite(t,I).catch(()=>{})}throw p}_.suppressed=null,e===this._loadGeneration&&(l?.then(()=>this._deletedMessages.get(t)===_?u(h):void 0).catch(()=>{}),this.repository.deleteMessage(t),this._notifySubscribers())})(),_.deletion}resumeRun({stream:t,...e}){if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(e,t)}exportExternalState(){throw new Error("Runtime does not support exporting external states.")}import(t){this._roundtripsInFlight.clear(),this._followedDuringRun.clear(),this._unwrittenMessages.clear(),this._unwrittenSeedMessages.clear(),this._deletedMessages.clear(),super.import(A(t))}importExternalState(){throw new Error("Runtime does not support importing external states.")}unstable_notifySessionReset(){throw new Error("Runtime does not support resetting sessions.")}async startRun({parentId:t,sourceId:e,runConfig:r},i){if(this.voice)throw new Error("Cannot start a run while a voice session is connected");if(this._isVoiceMessage(e))throw new Error("Voice transcript messages cannot be reloaded");let s=this._cancelPause(t),o=x(),n={id:o,role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._unwrittenMessages.add(o);let u=this._runLoop(t,n,r,i);if(!s)return u;let[a,h]=await Promise.allSettled([u,s]);if(a.status==="rejected")throw a.reason;if(h.status==="rejected")throw h.reason}async _runLoop(t,e,r,i){let s=this._loadGeneration,o=E(this);if(this.ensureInitialized()){let l=this._getInitializePromise?.();if(l){this._pendingInitialization=l;let _=()=>{this._pendingInitialization===l&&(this._pendingInitialization=void 0)};l.then(_,_)}}let n=this._pendingInitialization;if(n){let l=this.getMessageById(e.id)!==void 0;if(await n.catch(()=>{}),o.aborted||s!==this._loadGeneration||l&&!this.getMessageById(e.id))return}let u=this._getHistoryLoadBarrier(o);if(u){let l=this._loadImports;if(await u,o.aborted||s!==this._loadGeneration||this._loadImports!==l)return}if(this.voice)throw new Error("Cannot start a run while a voice session is connected");this._runStarted=!0,this._notifyEventSubscribers("runStart",{});let a={resumedFromPause:e.status.type==="requires-action",isRunning:!0};this._activeRun=a;let h=!1;try{this._queueCancelReserved&&this._queue&&(this._queueCancelReserved=!1,this._queue.notifyBusy(),this._queue.notifyIdle()),this._syncQueue(),this._suggestions=[],this._suggestionsController?.abort(),this._suggestionsController=null,this._notifySubscribers();do{if(e=await this.performRoundtrip(t,e,r,a,i),i=void 0,this._activeRun!==a)break;let l=this._messageReplacements.get(e);for(;l;)e=l.message,l=this._messageReplacements.get(e);if(this.getMessageById(e.id)?.message!==e)break}while(S(e,this._options.unstable_humanToolNames)&&!this.repository.hasChildren(e.id))}finally{let l=this.isRunning;a.isRunning=!1,s===this._loadGeneration&&this._notifyEventSubscribers("runEnd",{}),h=s===this._loadGeneration&&this._activeRun===a,h&&(this._activeRun=null),s===this._loadGeneration&&this._syncQueue(),l!==this.isRunning&&this._notifySubscribers()}h&&!o.aborted&&e.status?.type!=="requires-action"&&this._generateSuggestions()}_generateSuggestions(){let t=this.adapters.suggestion,e=this.messages.at(-1);if(!t||this._activeRun||e?.role!=="assistant"||e.status.type!=="complete"&&e.status.type!=="incomplete")return;this._suggestionsController?.abort();let r=new AbortController;this._suggestionsController=r;let{signal:i}=r;(async()=>{try{let s=t.generate({messages:this.messages,signal:i});await z(s,{signal:i,onUpdate:o=>{this._suggestionsController===r&&(this._suggestions=o,this._notifySubscribers())}})}catch{}})()}async performRoundtrip(t,e,r,i,s){let o=this._loadGeneration,n=(t?this.repository.getMessages(t):[]).map(c=>G(c.role==="assistant"&&(c.status.type==="running"||this._roundtripsInFlight.has(c.id))?P(c):c));this.abortController?.abort();let u=new AbortController;this.abortController=u;let a=e.content,h=e.metadata?.unstable_annotations,l=e.metadata?.unstable_data,_=e.metadata?.steps,p=e.metadata?.custom,f=new Set,I=!0;try{this.repository.getMessage(e.id)}catch{I=!1}let v=()=>{if(o!==this._loadGeneration)return!1;if(!I)return this._activeRun===i;try{let c=e,m=this._messageReplacements.get(c);for(;m;)m.toolCallId!==void 0&&f.add(m.toolCallId),c=m.message,m=this._messageReplacements.get(c);return this.repository.getMessage(e.id).message!==c?!1:(e=c,!0)}catch{return!1}},T=c=>{let m=new Map;for(let d of e.content)d.type==="tool-call"&&d.unstable_interactions!==void 0&&m.set(d.toolCallId,d.unstable_interactions);let R=c.map(d=>{if(d.type!=="tool-call"||d.unstable_interactions!==void 0)return d;let g=m.get(d.toolCallId);return g===void 0?d:{...d,unstable_interactions:g}});if(f.size===0)return R;let w=new Map;for(let d of e.content){if(d.type!=="tool-call"||!f.has(d.toolCallId))continue;let g=w.get(d.toolCallId)??[];g.push(d),w.set(d.toolCallId,g)}let M=new Map;return R.map(d=>{if(d.type!=="tool-call")return d;let g=M.get(d.toolCallId)??0;if(M.set(d.toolCallId,g+1),d.result!==void 0&&d.isPreliminary!==!0)return d;let y=w.get(d.toolCallId)?.[g];if(!y||y.result===void 0||y.isPreliminary===!0)return d;let{isPreliminary:H,artifact:b,modelContent:q,...L}=d;return{...L,result:y.result,isError:y.isError,...y.artifact!==void 0&&{artifact:y.artifact},...y.modelContent!==void 0&&{modelContent:y.modelContent}}})},C=c=>{if(!v())return;let m=c.metadata?.steps,R=m?[..._??[],...m]:void 0,w=c.metadata?.unstable_annotations,M=c.metadata?.unstable_data,d=w?[...h??[],...w]:void 0,g=M?[...l??[],...M]:void 0,y=c.content?T([...a,...c.content]):void 0;e={...e,...y?{content:y}:void 0,status:c.status??e.status,...c.metadata?{metadata:{...e.metadata,...c.metadata.unstable_state!==void 0?{unstable_state:c.metadata.unstable_state}:void 0,...d?{unstable_annotations:d}:void 0,...g?{unstable_data:g}:void 0,...R?{steps:R}:void 0,...c.metadata?.timing?{timing:c.metadata.timing}:void 0,...c.metadata?.custom?{custom:{...p??{},...c.metadata.custom}}:void 0}}:void 0},this.repository.addOrUpdateMessage(t,e),I=!0,this._notifySubscribers()},W=this._options.maxSteps??2;this._roundtripsInFlight.set(e.id,{controller:u,resumedFromPause:i.resumedFromPause});try{if((e.metadata?.steps?.length??0)>=W)return C({status:{type:"incomplete",reason:"tool-calls"}}),e;let c=!I;C({status:{type:"running"}}),c&&(this.repository.switchToBranch(e.id),this._notifySubscribers()),this._lastRunConfig=r??{};let{unstable_composerMetadata:m,...R}=this.getModelContext();s=s??this.adapters.chatModel.run.bind(this.adapters.chatModel);let w=u.signal,M=()=>w.aborted&&(e.status.type==="running"||e.status.type==="requires-action"&&(this._activeRun!==i||S(e,this._options.unstable_humanToolNames))),d=this._getThreadId?.(),g=s({messages:n,runConfig:this._lastRunConfig,abortSignal:w,context:R,unstable_assistantMessageId:e.id,unstable_threadId:d,unstable_parentId:t,unstable_getMessage(){return v(),G(e)}});if(Symbol.asyncIterator in g)for await(let y of g){if(w.aborted){M()&&C({status:{type:"incomplete",reason:"cancelled"}});break}C(y)}else C(await g);M()?C({status:{type:"incomplete",reason:"cancelled"}}):e.status.type==="running"&&C({status:{type:"complete",reason:"unknown"}})}catch(c){if(c instanceof B)C({status:{type:"incomplete",reason:"cancelled"}});else if(c instanceof Error&&c.name==="AbortError")C({status:{type:"incomplete",reason:"cancelled"}});else throw C({status:{type:"incomplete",reason:"error",error:k(c)}}),c}finally{let c=this.isRunning;this.abortController===u&&(this.abortController=null);let m=this._roundtripsInFlight.get(e.id)?.controller===u;m&&this._roundtripsInFlight.delete(e.id);let R=this._options.adapters.history,w=v(),M=!1,d,g=m&&this._followedDuringRun.delete(e.id);if(g){let b=this.getMessageById(e.id);if(b?.message.role==="assistant"){let q=P(b.message);q!==b.message&&(this.repository.addOrUpdateMessage(b.parentId,q),M=!0,w?e=q:d=this._persistSettled(b.parentId,q))}}if(m&&!w&&!d){let b=this.getMessageById(e.id);b?.message.role==="assistant"&&(b.message.status.type==="complete"||b.message.status.type==="incomplete")&&this._unwrittenMessages.has(e.id)&&(d=this._persistSettled(b.parentId,b.message))}let y=e.status.type==="complete"||e.status.type==="incomplete",H=e.status.type==="requires-action"&&!S(e,this._options.unstable_humanToolNames);if(w&&(y||H&&R?.update))if(y&&i.resumedFromPause&&!g&&!this._unwrittenMessages.has(e.id)&&R&&!R.update){let b={parentId:t,message:e,runConfig:this._lastRunConfig};d=this._chainHistoryWrite(e.id,()=>this._writeHistory("append",[e.id],()=>R.append(b)))}else d=this._persistSettled(t,e);i.isRunning=S(e,this._options.unstable_humanToolNames)&&!this.repository.hasChildren(e.id),(M||c!==this.isRunning)&&this._notifySubscribers(),d&&await d}return e}detach(){j(this),this._queue=null;let t=new B(!0);this.abortController?.abort(t),this.abortController=null,this._suggestionsController?.abort(),this._suggestionsController=null}cancelRun(){this._queue&&(this._options.unstable_queueClearOnCancel??!0?this._queue.clear():(this._queue.notifyCancelled(),this._queueBusy&&(this._queueCancelReserved=!0)));let t=new B(!1);this.abortController?.abort(t),this.abortController=null,this._suggestionsController?.abort(),this._suggestionsController=null}_onMessageMetadataChanged(t,e){this._messageReplacements.set(t,{message:e}),this._persistMessageUpdate(e.id)}addToolResult({messageId:t,toolCallId:e,result:r,isError:i,artifact:s,modelContent:o}){if(this.voice)throw new Error("Cannot add a tool result while a voice session is connected");let n=this.repository.getMessage(t),{parentId:u}=n,{message:a}=n;if(a.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let h=!1,l=!1,_=a.content.map(f=>{if(f.type!=="tool-call"||f.toolCallId!==e)return f;l=!0,(f.result===void 0||f.isPreliminary===!0)&&(h=!0);let{isPreliminary:I,...v}=f;return{...v,result:r,isError:i,...s!==void 0&&{artifact:s},...o!==void 0&&{modelContent:o}}});if(!l)throw new Error("Tried to add tool result to non-existing tool call");let p=a;a={...a,content:_},p.status.type==="running"&&this._messageReplacements.set(p,{message:a,toolCallId:e}),this.repository.addOrUpdateMessage(u,a),this._notifySubscribers(),h&&(this._resumeIfReady(t)||this._persistMessageUpdate(t))}resumeToolCall(t){throw new Error("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.")}async unstable_recordToolInteraction({messageId:t,toolCallId:e,interaction:r}){let i;try{i=this.repository.getMessage(t)}catch{throw new Error("Tried to record a tool interaction on a non-existing message")}let{parentId:s,message:o}=i;if(o.role!=="assistant")throw new Error("Tried to record a tool interaction on a non-assistant message");let n=o.content.findIndex(h=>h.type==="tool-call"&&h.toolCallId===e);if(n===-1)throw new Error("Tried to record a tool interaction on a non-existing tool call");let u=o.content[n];if(u.type!=="tool-call")throw new Error("Tried to record a tool interaction on a non-existing tool call");let a={...o,content:o.content.map((h,l)=>l===n?{...h,unstable_interactions:O(u.unstable_interactions,r)}:h)};o.status.type==="running"&&this._messageReplacements.set(o,{message:a}),this.repository.addOrUpdateMessage(s,a),this._notifySubscribers(),this._persistMessageUpdate(a.id)}respondToToolApproval({approvalId:t,approved:e,optionId:r,text:i,answers:s,reason:o}){if(this.voice)throw new Error("Cannot respond to a tool approval while a voice session is connected");let n=this.repository.getMessages().findLast(p=>p.role==="assistant"&&p.content.some(f=>f.type==="tool-call"&&f.approval?.id===t));if(!n)throw new Error("Tried to respond to a non-existing tool approval");if(this.abortController!==null)throw new Error("Tried to respond to a tool approval while a run is in progress");if(n.status?.type!=="requires-action")throw new Error("Tried to respond to a tool approval on a message whose status is not requires-action");if(this.repository.hasChildren(n.id))throw new Error("Tried to respond to a tool approval on a message that later messages follow");if(this._followedDuringRun.has(n.id))throw new Error("Tried to respond to a tool approval that was cancelled or expired");let u=n.content.find(p=>p.type==="tool-call"&&p.approval?.id===t);if(u?.type!=="tool-call"||!u.approval)throw new Error("Tried to respond to a non-existing tool approval");if(u.approval.resolution!==void 0)throw new Error("Tried to respond to a tool approval that was cancelled or expired");if(u.approval.approved!==void 0)throw new Error("Tried to respond to an already decided tool approval");let a=u.approval,h=n.content.map(p=>{if(p!==u)return p;let f={...a,approved:e,...r!=null&&{optionId:r},...i!=null&&{text:i},...s!=null&&{answers:s},...o!=null&&{reason:o}};return e?{...p,approval:f}:{...p,approval:f,result:{error:o||"Tool approval denied"},isError:!0}});n={...n,content:h};let{parentId:l}=this.repository.getMessage(n.id);this.repository.addOrUpdateMessage(l,n),this._notifySubscribers(),this._notifyToolApprovalAnswered(n.id,u.toolCallId,u.toolName,e);let _=this.getMessageById(n.id);return this.repository.headId===n.id&&_?.message.role==="assistant"&&S(_.message,this._options.unstable_humanToolNames)?this._runLoop(_.parentId,_.message,this._lastRunConfig).catch(()=>{}):this._persistMessageUpdate(n.id),Promise.resolve()}};export{ut as LocalThreadRuntimeCore};
//# sourceMappingURL=local-thread-runtime-core.mjs.map