// @bun
import{ib as W,jb as Q}from"./chunk-910vkvsf.js";import{Lj as V}from"./chunk-gmt7f7kk.js";function U(){let B,G;return{promise:new Promise((z,F)=>{B=z,G=F}),resolve:B,reject:G}}async function $(B){let G=U(),H=U(),z={queue:[],closed:B.footer.isClosed},F,D=(A,M)=>{B.trace?.write("ui.patch",M),B.footer.event(A)},L=()=>{if(!z.closed||F)return;H.resolve()},R=()=>{if(z.closed)return;z.closed=!0,z.queue.length=0,z.ctrl?.abort(),G.resolve({type:"closed"}),L()},S=()=>{if(F||z.closed||z.queue.length===0)return;F=(async()=>{try{while(!z.closed&&z.queue.length>0){let A=z.queue.shift();if(!A)continue;if(A.mode!=="shell"&&Q(A.text)){if(D({type:"queue",queue:z.queue.length},{queue:z.queue.length}),!B.onNewSession){D({type:"stream.patch",patch:{status:"new sessions unavailable"}},{status:"new sessions unavailable"});continue}D({type:"stream.patch",patch:{phase:"running",status:"starting new session",queue:z.queue.length}},{phase:"running",status:"starting new session",queue:z.queue.length}),await B.onNewSession();continue}D({type:"turn.send",queue:z.queue.length},{phase:"running",status:"sending prompt",queue:z.queue.length});let M=Date.now(),I=new AbortController;z.ctrl=I;try{if(await B.footer.idle(),z.closed)break;if(A.mode!=="shell"){let K={kind:"user",text:A.text,phase:"start",source:"system"};B.trace?.write("ui.commit",K),B.footer.append(K)}if(B.onSend?.(A),z.closed)break;let J=B.run(A,I.signal).then(()=>({type:"done"}),(K)=>({type:"error",error:K})),O=await Promise.race([J,G.promise]);if(O.type==="closed"){I.abort();break}if(O.type==="error")throw O.error}finally{if(z.ctrl===I)z.ctrl=void 0;let J=V(Math.max(0,Date.now()-M));D({type:"turn.duration",duration:J},{duration:J})}}}catch(A){H.reject(A);return}finally{F=void 0,D({type:"turn.idle",queue:z.queue.length},{phase:"idle",status:"",queue:z.queue.length})}L()})()},T=(A)=>{if(!A.text.trim()||z.closed)return;if(A.mode!=="shell"&&W(A.text)){B.footer.close();return}if(z.queue.push(A),D({type:"queue",queue:z.queue.length},{queue:z.queue.length}),A.mode!=="shell"&&Q(A.text)){S();return}D({type:"first",first:!1},{first:!1}),S()},X=B.footer.onPrompt((A)=>{T(A)}),Y=B.footer.onClose(()=>{R()});try{if(z.closed)return;T({text:B.initialInput??"",parts:[]}),L(),await H.promise}finally{X(),Y(),R(),await F?.catch(()=>{})}}
export{$ as ab};
