broods 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ import{getToolName as Re,isToolUIPart as Zt,readUIMessageStream as Ae}from"ai";import{convertToModelMessages as oa,generateId as ua,getToolName as ca,isToolUIPart as le}from"ai";var Ht=(t)=>{throw TypeError(t)},St=(t,e,a)=>e.has(t)||Ht("Cannot "+a),u=(t,e,a)=>(St(t,e,"read from private field"),a?a.call(t):e.get(t)),v=(t,e,a)=>e.has(t)?Ht("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,a),c=(t,e,a,r)=>(St(t,e,"write to private field"),r?r.call(t,a):e.set(t,a),a),o=(t,e,a)=>(St(t,e,"access private method"),a),Kt=String.fromCharCode(27),Sa=new RegExp(`${Kt}\\[[0-?]*[ -/]*[@-~]`,"g"),bt=new RegExp(`^${Kt}\\[[0-?]*[ -/]*[@-~]`);function B(t){let e=0,a=0;while(a<t.length){let r=t.slice(a).match(bt);if(r){a+=r[0].length;continue}let n=t.codePointAt(a);if(n==null)break;let i=String.fromCodePoint(n);e+=Jt(n),a+=i.length}return e}function H(t,e){if(e<=0)return"";let a="",r=0,n=0;while(n<t.length&&r<e){let i=t.slice(n).match(bt);if(i){a+=i[0],n+=i[0].length;continue}let d=t.codePointAt(n);if(d==null)break;let p=String.fromCodePoint(d),h=Jt(d);if(h>0&&r+h>e)break;a+=p,n+=p.length,r+=h}while(n<t.length){let i=t.slice(n).match(bt);if(!i)break;a+=i[0],n+=i[0].length}return a}function Jt(t){if(t===9)return 4;if(t<32||t>=127&&t<160)return 0;if(fe(t))return 0;return ve(t)?2:1}function fe(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t===1471||t>=1473&&t<=1474||t>=1476&&t<=1477||t===1479||t>=1552&&t<=1562||t>=1611&&t<=1631||t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t===1809||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2027&&t<=2035||t>=2070&&t<=2073||t>=2075&&t<=2083||t>=2085&&t<=2087||t>=2089&&t<=2093||t>=2137&&t<=2139||t>=2259&&t<=2306||t===2362||t===2364||t>=2369&&t<=2376||t===2381||t>=2385&&t<=2391||t===8205||t>=65024&&t<=65039||t>=917760&&t<=917999}function ve(t){return t>=4352&&(t<=4447||t===9001||t===9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=127744&&t<=128591||t>=129280&&t<=129535||t>=131072&&t<=262141)}var M={bold:"\x1B[1m",boldOff:"\x1B[22m",italic:"\x1B[3m",italicOff:"\x1B[23m"},me="─";function ge(t){var e;let a=t.split(`
2
+ `),r=[];for(let n=0;n<a.length;n+=1){let i=be(a,n);if(i!=null){r.push(...Te(i)),n=i.endIndex-1;continue}r.push(ye((e=a[n])!=null?e:""))}return r.join(`
3
+ `)}function ye(t){if(t.startsWith("### "))return C(`▶ ${t.slice(4)}`);if(t.startsWith("## "))return C(`■ ${t.slice(3)}`);if(t.startsWith("# "))return C(`█ ${t.slice(2)}`);let e=t.match(/^(\s*)[-+*]\s+(.*)$/);if(e){let[,a,r=""]=e;return C(`${a}•${r.length>0?` ${r}`:""}`)}if(/^\d+\. /.test(t))return C(t.replace(/^(\d+)\. /,"$1. "));if(t.startsWith("> "))return C(`│ ${t.slice(2)}`);return C(t)}function C(t){return t.replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*\n]+)\*\*/g,`${M.bold}$1${M.boldOff}`).replace(/__([^_\n]+)__/g,`${M.bold}$1${M.boldOff}`).replace(/\*([^*\n]+)\*/g,`${M.italic}$1${M.italicOff}`).replace(/_([^_\n]+)_/g,`${M.italic}$1${M.italicOff}`)}function be(t,e){var a,r,n;let i=gt((a=t[e])!=null?a:"");if(i==null||i.length<2)return;let d=gt((r=t[e+1])!=null?r:"");if(d==null||d.length!==i.length)return;let p=ke(d);if(p==null)return;let h=[],m=e+2;while(m<t.length){let f=gt((n=t[m])!=null?n:"");if(f==null)break;h.push(xe(f,i.length)),m+=1}return{alignments:p,endIndex:m,header:i,rows:h}}function gt(t){if(!t.includes("|"))return;let e=t.trim();if(e.startsWith("|"))e=e.slice(1);if(e.endsWith("|")&&!e.endsWith("\\|"))e=e.slice(0,-1);let a=[],r="";for(let n=0;n<e.length;n+=1){let i=e[n],d=e[n+1];if(i==="\\"&&d==="|"){r+="|",n+=1;continue}if(i==="|"){a.push(r.trim()),r="";continue}r+=i}return a.push(r.trim()),a}function ke(t){let e=[];for(let a of t){let r=a.match(/^(:)?-{3,}(:)?$/);if(r==null)return;let[,n,i]=r;e.push(n!=null&&i!=null?"center":i!=null?"right":"left")}return e}function xe(t,e){return Array.from({length:e},(a,r)=>{var n;return(n=t[r])!=null?n:""})}function Te(t){let e=t.header.map((i)=>`${M.bold}${C(i)}${M.boldOff}`),a=t.rows.map((i)=>i.map(C)),r=[e,...a],n=t.alignments.map((i,d)=>Math.max(3,...r.map((p)=>{var h;return B((h=p[d])!=null?h:"")})));return[Et(e,n,t.alignments),n.map((i)=>me.repeat(i)).join(" "),...a.map((i)=>Et(i,n,t.alignments))]}function Et(t,e,a){return t.map((r,n)=>{var i,d;return we(r,(i=e[n])!=null?i:0,(d=a[n])!=null?d:"left")}).join(" ")}function we(t,e,a){let r=Math.max(0,e-B(t));if(a==="right")return`${" ".repeat(r)}${t}`;if(a==="center"){let n=Math.floor(r/2),i=r-n;return`${" ".repeat(n)}${t}${" ".repeat(i)}`}return`${t}${" ".repeat(r)}`}var Yt="─";function Me(t){var e;let a=Math.max(20,t.width),r=Math.max(8,t.height),n=3,d=r-3-2,p=t.visibleBodyLines.slice(0,d);while(p.length<d)p.push("");return[Wt(a,t.title,t.rightTitle),...p.map((m)=>At(m,a)),Rt(a),Wt(a,t.inputActive?"Input":"Status"),At(t.inputActive?`> ${t.input}${t.inputCursorVisible===!1?" ":"█"}`:(e=t.status)!=null?e:"Streaming... ↑/↓ scroll · Ctrl+C quit",a),Rt(a)].join(`
4
+ `)}function Wt(t,e,a){let r=Math.max(0,t-2),n=e?H(` ${e} `,r):"",i=a?H(` ${a} `,Math.max(0,r-B(n))):"",d=Math.max(0,r-B(n)-B(i));return`┌${n}${Yt.repeat(d)}${i}┐`}function Rt(t){return`└${Yt.repeat(t-2)}┘`}function At(t,e){let a=e-4,r=H(t,a),n=" ".repeat(Math.max(0,a-B(r)));return`│ ${r}${n} │`}var G="\x1B",Se=`${G}[H`,_e=`${G}[2J`,$e=`${G}[2K`,Ce=`${G}[?2026h`,Ie=`${G}[?2026l`,ct,V,q,P,Z,kt,Gt,Be=class{constructor(t,e){v(this,kt),v(this,ct),v(this,V),v(this,q),v(this,P,!1),v(this,Z,!1);var a;c(this,V,t.write.bind(t)),c(this,ct,(a=e==null?void 0:e.useSynchronizedUpdates)!=null?a:!0),t.write=(r,n,i)=>{if(!u(this,P))c(this,Z,!0);return u(this,V).call(this,r,n,i)}}present(t){let e=Ee(t),a=u(this,q)&&!u(this,Z)?We(u(this,q),e):`${Se}${_e}${t}`;if(c(this,q,e),c(this,Z,!1),a.length===0)return;o(this,kt,Gt).call(this,a)}reset(){c(this,q,void 0)}};ct=new WeakMap;V=new WeakMap;q=new WeakMap;P=new WeakMap;Z=new WeakMap;kt=new WeakSet;Gt=function(t){c(this,P,!0);try{if(!u(this,ct)){u(this,V).call(this,t);return}u(this,V).call(this,`${Ce}${t}${Ie}`)}finally{c(this,P,!1)}};function Ee(t){return{lines:t.split(`
5
+ `)}}function We(t,e){let a="",r=Math.max(t.lines.length,e.lines.length);for(let n=0;n<r;n++){let i=e.lines[n];if(t.lines[n]===i)continue;a+=`${G}[${n+1};1H${$e}${i!=null?i:""}`}return a}var Ue="outputTokensPerSecond",k={reset:"\x1B[0m",dim:"\x1B[2m",user:"\x1B[96m",assistant:"\x1B[92m",reasoning:"\x1B[94m",tool:"\x1B[95m",error:"\x1B[91m"},Le={user:{color:k.user,border:"─"},assistant:{color:k.assistant,border:"─"},reasoning:{color:k.reasoning,border:"·"},tool:{color:k.tool,border:"─"},error:{color:k.error,border:"─"}},Oe=500,U="↑/↓ · PgUp/PgDn · Esc/Ctrl+C",Fe="↑/↓ · PgUp/PgDn · q/Esc/Ctrl+C",Q=`Processing input... ${U}`,Ut=`Processing tool results... ${U}`,xt=`Streaming... ${U}`,Lt=`Executing tools... ${U}`,T,_,z,nt,st,it,dt,x,S,A,E,tt,y,K,b,W,et,R,L,N,O,w,F,X,l,lt,ot,j,I,Qt,J,at,Xt,rt,ht,jt,_t,Tt,ut,Pt,te,$t,ft,g,Y,ee,Ct,D,vt,mt,It,ae,wt=class{constructor(t){v(this,l),v(this,T),v(this,_),v(this,z),v(this,nt),v(this,st),v(this,it),v(this,dt),v(this,x,[]),v(this,S,""),v(this,A,!1),v(this,E,0),v(this,tt,""),v(this,y,xt),v(this,K,!1),v(this,b,!1),v(this,W),v(this,et),v(this,R),v(this,L),v(this,N,!0),v(this,O),v(this,w),v(this,F),v(this,X);var e,a,r,n,i,d;c(this,T,(e=t==null?void 0:t.input)!=null?e:process.stdin),c(this,_,(a=t==null?void 0:t.output)!=null?a:process.stdout),c(this,z,(r=t==null?void 0:t.frameBuffer)!=null?r:new Be(u(this,_))),c(this,nt,(n=t==null?void 0:t.tools)!=null?n:"auto-collapsed"),c(this,st,(i=t==null?void 0:t.reasoning)!=null?i:"auto-collapsed"),c(this,it,(d=t==null?void 0:t.responseStatistics)!=null?d:Ue),c(this,dt,t==null?void 0:t.contextSize),c(this,et,t==null?void 0:t.contextSize)}async readPrompt(t){var e;return o(this,l,lt).call(this,t),c(this,A,!0),c(this,S,(e=t==null?void 0:t.initialPrompt)!=null?e:""),c(this,y,`Type a prompt and press Enter · ${U}`),o(this,l,Xt).call(this),o(this,l,g).call(this),await new Promise((a,r)=>{c(this,w,(n)=>{let i=pt(n);switch(i.type){case"character":c(this,S,u(this,S)+i.value),o(this,l,ht).call(this),o(this,l,g).call(this);break;case"backspace":c(this,S,u(this,S).slice(0,-1)),o(this,l,ht).call(this),o(this,l,g).call(this);break;case"enter":{let d=u(this,S);c(this,A,!1),o(this,l,rt).call(this),c(this,y,Q),o(this,l,_t).call(this,d),c(this,S,""),o(this,l,g).call(this),o(this,l,I).call(this),a(d);break}case"up":case"down":o(this,l,J).call(this,i.type);break;case"page-up":case"page-down":o(this,l,at).call(this,i.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":case"ctrl-c":o(this,l,rt).call(this),o(this,l,ot).call(this),r(yt());break;case"ignore":break}}),o(this,l,j).call(this)})}async renderStream(t,e){var a,r,n,i;o(this,l,lt).call(this,e),c(this,A,!1),c(this,y,Q),o(this,l,jt).call(this,e==null?void 0:e.submittedPrompt),c(this,b,!1),c(this,W,void 0),c(this,R,void 0),c(this,L,void 0);let d={tools:(a=e==null?void 0:e.tools)!=null?a:u(this,nt),reasoning:(r=e==null?void 0:e.reasoning)!=null?r:u(this,st),responseStatistics:(n=e==null?void 0:e.responseStatistics)!=null?n:u(this,it)};o(this,l,g).call(this);let p=new Promise((f)=>{c(this,X,f)});c(this,w,(f)=>o(this,l,Qt).call(this,f)),o(this,l,j).call(this);let h,m=Ze(o(this,l,te).call(this,t.uiMessageStream));try{let f=Ae({message:t.message,stream:m,onError:(s)=>o(this,l,$t).call(this,"Error",Ne(s))});for await(let s of ze(f,p)){if(u(this,b))break;h=s,o(this,l,Tt).call(this,s,d)}if(!u(this,b)&&h&&u(this,R)!=null)o(this,l,Tt).call(this,h,d)}finally{if(c(this,X,void 0),u(this,b))(i=t.abort)==null||i.call(t);if(o(this,l,I).call(this),c(this,y,u(this,b)?"Interrupted":(e==null?void 0:e.continueSession)?`Done · Enter another prompt · ${U}`:`Done · ${Fe}`),o(this,l,g).call(this),await o(this,l,ae).call(this,e),u(this,b)||!(e==null?void 0:e.continueSession))o(this,l,ot).call(this)}if(u(this,b))throw yt();return h}async readToolApproval(t,e){return o(this,l,lt).call(this,e),c(this,A,!1),c(this,y,`Approve ${Ye(t)}? y/n · ${U}`),c(this,b,!1),o(this,l,g).call(this),await new Promise((a,r)=>{c(this,w,(n)=>{let i=pt(n);switch(i.type){case"character":{let d=i.value.toLowerCase();if(d==="y")c(this,y,`Approved · ${Q}`),o(this,l,I).call(this),o(this,l,g).call(this),a({approved:!0});else if(d==="n")c(this,y,`Denied · ${Q}`),o(this,l,I).call(this),o(this,l,g).call(this),a({approved:!1,reason:"Denied by user."});break}case"up":case"down":o(this,l,J).call(this,i.type);break;case"page-up":case"page-down":o(this,l,at).call(this,i.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":case"ctrl-c":c(this,b,!0),o(this,l,ot).call(this),r(yt());break;default:break}}),o(this,l,j).call(this)})}};T=new WeakMap;_=new WeakMap;z=new WeakMap;nt=new WeakMap;st=new WeakMap;it=new WeakMap;dt=new WeakMap;x=new WeakMap;S=new WeakMap;A=new WeakMap;E=new WeakMap;tt=new WeakMap;y=new WeakMap;K=new WeakMap;b=new WeakMap;W=new WeakMap;et=new WeakMap;R=new WeakMap;L=new WeakMap;N=new WeakMap;O=new WeakMap;w=new WeakMap;F=new WeakMap;X=new WeakMap;l=new WeakSet;lt=function(t){var e,a,r,n;if(c(this,tt,(e=t==null?void 0:t.title)!=null?e:u(this,tt)),c(this,et,(a=t==null?void 0:t.contextSize)!=null?a:u(this,dt)),u(this,K))return;if(c(this,K,!0),u(this,z).reset(),u(this,_).write("\x1B[?1049h\x1B[?25l"),u(this,T).isTTY)(n=(r=u(this,T)).setRawMode)==null||n.call(r,!0),u(this,T).resume();c(this,F,()=>o(this,l,Y).call(this)),u(this,_).on("resize",u(this,F))};ot=function(){var t,e;if(o(this,l,I).call(this),o(this,l,rt).call(this),!u(this,K))return;if(u(this,T).isTTY)(e=(t=u(this,T)).setRawMode)==null||e.call(t,!1),u(this,T).pause();if(u(this,F))u(this,_).off("resize",u(this,F)),c(this,F,void 0);u(this,_).write("\x1B[?25h\x1B[?1049l"),u(this,z).reset(),c(this,K,!1)};j=function(){if(u(this,w))u(this,T).on("data",u(this,w))};I=function(){if(u(this,w))u(this,T).off("data",u(this,w)),c(this,w,void 0)};Qt=function(t){var e;let a=pt(t);switch(a.type){case"up":case"down":o(this,l,J).call(this,a.type);break;case"page-up":case"page-down":o(this,l,at).call(this,a.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":case"ctrl-c":c(this,b,!0),(e=u(this,X))==null||e.call(this);break;default:break}};J=function(t,e=1){let a=t==="up"?e:-e;c(this,E,o(this,l,Ct).call(this,u(this,E)+a)),o(this,l,g).call(this)};at=function(t){o(this,l,J).call(this,t==="page-up"?"up":"down",o(this,l,vt).call(this))};Xt=function(){var t,e;o(this,l,rt).call(this),o(this,l,ht).call(this),c(this,O,setInterval(()=>{c(this,N,!u(this,N)),o(this,l,g).call(this)},Oe)),(e=(t=u(this,O)).unref)==null||e.call(t)};rt=function(){if(u(this,O))clearInterval(u(this,O)),c(this,O,void 0);c(this,N,!0)};ht=function(){c(this,N,!0)};jt=function(t){if(t==null)return;let e=u(this,x).at(-1);if((e==null?void 0:e.kind)==="user"&&e.content===t)return;o(this,l,_t).call(this,t)};_t=function(t){let e=o(this,l,D).call(this);u(this,x).push({kind:"user",title:"User",content:t}),o(this,l,ft).call(this,e)};Tt=function(t,e){var a,r,n;let i=o(this,l,D).call(this),d=new Set,p=aa(t.metadata);c(this,W,(a=p.totalTokens)!=null?a:u(this,W)),c(this,R,(r=p.outputTokens)!=null?r:u(this,R)),c(this,L,(n=p.outputTokensPerSecond)!=null?n:u(this,L));for(let[h,m]of t.parts.entries()){let f=Ge(t.id,h);switch(m.type){case"text":{let s=m.text.trim();if(s.length===0)break;d.add(f),o(this,l,ut).call(this,{id:f,kind:"assistant",title:"Assistant",rightTitle:sa({totalTokens:u(this,W),outputTokens:u(this,R),outputTokensPerSecond:u(this,L)},e.responseStatistics),content:s});break}case"reasoning":{let s=m.text.trim();if(e.reasoning==="hidden"||s.length===0)break;d.add(f),o(this,l,ut).call(this,{id:f,kind:"reasoning",title:"Reasoning",content:s,collapsed:Ot(t,h,e.reasoning,e)});break}default:if(Zt(m)){if(e.tools==="hidden")break;d.add(f),o(this,l,ut).call(this,{id:f,...De(m,{mode:e.tools,collapsed:Ot(t,h,e.tools,e)})})}break}}o(this,l,Pt).call(this,t.id,d),o(this,l,ft).call(this,i)};ut=function(t){let e=t.id?u(this,x).find((a)=>a.id===t.id):void 0;if(e){let a=e.cache;e.kind=t.kind,e.title=t.title,e.rightTitle=t.rightTitle,e.content=t.content,e.collapsed=t.collapsed,e.cache=a&&ne(t,a)?a:void 0;return}u(this,x).push(t)};Pt=function(t,e){let a=`${t}:`;c(this,x,u(this,x).filter((r)=>r.id==null||!r.id.startsWith(a)||e.has(r.id)))};te=async function*(t){let e=!1;for await(let a of Qe(t)){let r=He(a,{hasPendingToolResults:e});if(a.type==="start-step")e=!1;else if(Ke(a))e=!0;if(r&&u(this,y)!==r)c(this,y,r),o(this,l,g).call(this);else if(Ve(a)&&u(this,y)!==xt)c(this,y,xt),o(this,l,g).call(this);if(a.type==="error")o(this,l,$t).call(this,"Error",a.errorText);if(a.type==="finish"){let n=ea(a);c(this,W,n.totalTokens),c(this,R,n.outputTokens),c(this,L,n.outputTokensPerSecond)}yield a}};$t=function(t,e){let a=o(this,l,D).call(this);u(this,x).push({kind:"error",title:t,content:e}),o(this,l,ft).call(this,a)};ft=function(t){if(u(this,E)!==0){let e=o(this,l,D).call(this)-t;c(this,E,o(this,l,Ct).call(this,u(this,E)+e))}o(this,l,g).call(this)};g=function(){let t=Me({width:o(this,l,mt).call(this),height:o(this,l,It).call(this),title:u(this,tt),rightTitle:ie(u(this,W),u(this,et)),visibleBodyLines:o(this,l,ee).call(this),input:u(this,S),inputActive:u(this,A),inputCursorVisible:u(this,N),status:u(this,y)});u(this,z).present(t)};Y=function(){u(this,z).reset(),o(this,l,g).call(this)};ee=function(){if(u(this,x).length===0)return["Waiting for input..."];let t=o(this,l,vt).call(this),e=o(this,l,D).call(this),a=Math.max(0,e-t-u(this,E)),r=a+t,n=[],i=0;for(let d of u(this,x)){let p=re(d,o(this,l,mt).call(this)-4),h=i+p.length;if(h>a&&i<r)n.push(...p.slice(Math.max(0,a-i),r-i));if(n.length>=t)break;i=h}return n};Ct=function(t){let e=Math.max(0,o(this,l,D).call(this)-o(this,l,vt).call(this));return Math.min(Math.max(0,t),e)};D=function(){if(u(this,x).length===0)return 1;let t=0;for(let e of u(this,x))t+=re(e,o(this,l,mt).call(this)-4).length;return t};vt=function(){return Math.max(1,o(this,l,It).call(this)-5)};mt=function(){var t;return Math.max(20,(t=u(this,_).columns)!=null?t:80)};It=function(){var t;return Math.max(8,(t=u(this,_).rows)!=null?t:24)};ae=async function(t){if((t==null?void 0:t.waitForExit)===!1||!u(this,T).isTTY||u(this,b))return;await new Promise((e)=>{c(this,w,(a)=>{let r=pt(a);switch(r.type){case"up":case"down":o(this,l,J).call(this,r.type);break;case"page-up":case"page-down":o(this,l,at).call(this,r.type);break;case"ctrl-l":o(this,l,Y).call(this);break;case"escape":o(this,l,I).call(this),e();break;case"character":if(r.value==="q")o(this,l,I).call(this),e();break;case"ctrl-c":o(this,l,I).call(this),process.exitCode=130,e();break;default:break}}),o(this,l,j).call(this)})};function yt(){return Error("Interrupted")}async function*ze(t,e){let a=t[Symbol.asyncIterator](),r=e.then(()=>({done:!0,value:void 0}));while(!0){let n=await Promise.race([a.next(),r]);if(n.done)break;yield n.value}}function Ne(t){if(t instanceof Error)return t.message;if(typeof t==="string")return t;return JSON.stringify(t)}function De(t,e){var a,r,n,i;let d=Re(t),p=`Tool · ${(a=t.title)!=null?a:d}`,h="input"in t?t.input:void 0,m=h===void 0?"Input: (streaming...)":`Input:
6
+ ${Ft(h)}`,f=Je(t);if(e.collapsed)return{kind:"tool",title:p,rightTitle:f,content:"",collapsed:!0};switch(t.state){case"input-streaming":return{kind:"tool",title:p,rightTitle:f,content:m};case"input-available":return{kind:"tool",title:p,rightTitle:f,content:m};case"approval-requested":return{kind:"tool",title:p,rightTitle:f,content:m};case"approval-responded":return{kind:"tool",title:p,rightTitle:f,content:m};case"output-available":return{kind:"tool",title:p,rightTitle:f,content:`${m}
7
+
8
+ Output:
9
+ ${Ft(t.output)}`};case"output-error":return{kind:"error",title:`Tool Error · ${(r=t.title)!=null?r:d}`,rightTitle:f,content:`${m}
10
+
11
+ Error:
12
+ ${t.errorText}`};case"output-denied":return{kind:"error",title:`Tool Denied · ${(n=t.title)!=null?n:d}`,rightTitle:f,content:`${m}
13
+
14
+ Reason: ${(i=t.approval.reason)!=null?i:"denied"}`}}}function Ot(t,e,a,r){switch(a){case"collapsed":return!0;case"auto-collapsed":return t.parts.slice(e+1).some((n)=>qe(n,r));case"full":case"hidden":return!1}}function qe(t,e){switch(t.type){case"text":return t.text.trim().length>0;case"reasoning":return e.reasoning!=="hidden"&&t.text.trim().length>0;default:return Zt(t)&&e.tools!=="hidden"}}function Ve(t){switch(t.type){case"text-start":case"text-delta":case"reasoning-start":case"reasoning-delta":case"tool-input-start":case"tool-input-delta":return!0;default:return!1}}function He(t,{hasPendingToolResults:e}){switch(t.type){case"start-step":return e?Ut:Q;case"tool-output-available":case"tool-output-error":case"tool-output-denied":return Ut;case"tool-input-available":return Lt;case"tool-approval-response":return t.approved?Lt:void 0;default:return}}function Ke(t){switch(t.type){case"tool-output-available":case"tool-output-error":case"tool-output-denied":return!0;default:return!1}}function Je(t){switch(t.state){case"input-streaming":return"waiting";case"approval-requested":return"approval requested";case"input-available":return"executing";case"approval-responded":return t.approval.approved?"executing":"denied";case"output-available":case"output-error":return"done";case"output-denied":return"denied"}}function Ft(t){if(typeof t==="string")return t;return JSON.stringify(t,null,2)}function Ye(t){var e;return`tool ${(e=t.title)!=null?e:t.toolName}`}function Ge(t,e){return`${t}:${e}`}function Ze(t){if(t instanceof ReadableStream)return t;return new ReadableStream({async start(e){try{for await(let a of t)e.enqueue(a);e.close()}catch(a){e.error(a)}}})}async function*Qe(t){if(t instanceof ReadableStream){let e=t.getReader();try{while(!0){let{done:a,value:r}=await e.read();if(a)return;yield r}}finally{e.releaseLock()}return}yield*t}function re(t,e){if(t.cache&&ne(t,t.cache,e))return t.cache.lines;let a=Xe(t,e);return t.cache={width:e,kind:t.kind,title:t.title,rightTitle:t.rightTitle,content:t.content,collapsed:t.collapsed===!0,lines:a},a}function ne(t,e,a=e.width){return e.width===a&&e.kind===t.kind&&e.title===t.title&&e.rightTitle===t.rightTitle&&e.content===t.content&&e.collapsed===(t.collapsed===!0)}function Xe(t,e){let a=Le[t.kind],r=Math.max(1,e-4),n=` ${t.title} `,i=t.rightTitle?` ${t.rightTitle} `:"";if(t.collapsed){let s=Math.max(0,e-2-n.length-i.length),he=`${a.color}╭${n}${a.border.repeat(s)}${i}╮${k.reset}`,pe=`${a.color}╰${a.border.repeat(Math.max(0,e-2))}╯${k.reset}`;return[he,pe]}let d=Math.max(0,e-2-n.length-i.length),p=`${a.color}╭${n}${a.border.repeat(d)}${i}╮${k.reset}`,h=`${a.color}╰${a.border.repeat(Math.max(0,e-2))}╯${k.reset}`,f=(t.content.length>0?ge(t.content):k.dim+"(streaming...)"+k.reset).split(`
15
+ `).flatMap((s)=>Pe(s,r));return[p,...f.map((s)=>je(s,r,a.color)),h]}function je(t,e,a){let r=H(t,e),n=" ".repeat(Math.max(0,e-B(r)));return`${a}│${k.reset} ${r}${n} ${a}│${k.reset}`}function Pe(t,e){if(t.length===0)return[""];let a=[],r=t;while(B(r)>e){let n=ta(r,e);a.push(r.slice(0,n).trimEnd()),r=r.slice(n).trimStart()}return a.push(r),a}function ta(t,e){let r=H(t,e+1).lastIndexOf(" ");if(r>0)return r;return H(t,e).length}function ea(t){var e,a;let r="usage"in t?t.usage:void 0,n="messageMetadata"in t?(e=t.messageMetadata)==null?void 0:e.usage:void 0,i="messageMetadata"in t?(a=t.messageMetadata)==null?void 0:a.performance:void 0;return{totalTokens:se(r!=null?r:n),outputTokens:Bt(r!=null?r:n),outputTokensPerSecond:i==null?void 0:i.outputTokensPerSecond}}function aa(t){var e;let a=t;return{totalTokens:se(a==null?void 0:a.usage),outputTokens:Bt(a==null?void 0:a.usage),outputTokensPerSecond:(e=a==null?void 0:a.performance)==null?void 0:e.outputTokensPerSecond}}function se(t){let e=t==null?void 0:t.totalTokens;if(typeof e==="number")return e;if(typeof(e==null?void 0:e.total)==="number")return e.total;let a=ra(t),r=Bt(t);if(a!=null&&r!=null)return a+r;return}function ra(t){let e=t==null?void 0:t.inputTokens;if(typeof e==="number")return e;if(typeof(e==null?void 0:e.total)==="number")return e.total;return t==null?void 0:t.promptTokens}function Bt(t){let e=t==null?void 0:t.outputTokens;if(typeof e==="number")return e;if(typeof(e==null?void 0:e.total)==="number")return e.total;return t==null?void 0:t.completionTokens}function ie(t,e){if(t==null)return;let a=`${t.toLocaleString()} ${t===1?"token":"tokens"}`,r=na(t,e);return r==null?a:`${a} ${r}`}function na(t,e){if(e==null||e<=0||!Number.isFinite(e))return;return`${Math.round(t/e*100).toLocaleString()}%`}function sa(t,e){if(e==="outputTokensPerSecond")return ia(t.outputTokensPerSecond);return ie(t.outputTokens)}function ia(t){if(t==null)return;return`${la(t)} tok/s`}function la(t){return Number.isInteger(t)?t.toLocaleString():t.toLocaleString(void 0,{maximumFractionDigits:1})}function pt(t){let e=t.toString("utf8");switch(e){case"\f":return{type:"ctrl-l"};case"\x03":return{type:"ctrl-c"};case"\x1B":return{type:"escape"};case"\r":case`
16
+ `:return{type:"enter"};case"":case"\b":return{type:"backspace"};case"\x1B[A":return{type:"up"};case"\x1B[B":return{type:"down"};case"\x1B[5~":return{type:"page-up"};case"\x1B[6~":return{type:"page-down"};default:if(e>=" "&&e!=="")return{type:"character",value:e};return{type:"ignore"}}}var da="outputTokensPerSecond",ha=class{constructor(t){this.chatId=ua();var e,a,r,n;this.agent=t.agent,this.transport=t.transport,this.renderer=(e=fa(t))!=null?e:pa(t),this.title=t.title,this.tools=(a=t.tools)!=null?a:"auto-collapsed",this.reasoning=(r=t.reasoning)!=null?r:"auto-collapsed",this.responseStatistics=(n=t.responseStatistics)!=null?n:da,this.contextSize=t.contextSize,this.sandbox=t.sandbox}async run(){let t=this.title,e=[],a=0,r=()=>`message-${++a}`,n,i=!1,d=!1;while(!0){if(!d){if(n==null){if(!this.renderer.readPrompt){if(i)return;throw Error("No prompt was provided and the renderer does not support prompt input.")}try{n=await this.renderer.readPrompt({title:t})}catch(h){if(Vt(h))return;throw h}if(n==null)return}e.push(ga(r(),n)),i=!0}let p=await this.streamMessages([...e],r);try{let h=await this.renderer.renderStream(p,{title:t,submittedPrompt:n,continueSession:Boolean(this.renderer.readPrompt),tools:this.tools,reasoning:this.reasoning,responseStatistics:this.responseStatistics,contextSize:this.contextSize,waitForExit:!1});if(h&&h.parts.length>0){let m=ya(h);if(m.length>0){if(!this.renderer.readToolApproval)throw Error("Tool approval was requested, but the renderer does not support tool approval input.");for(let f of m){let s=await this.renderer.readToolApproval(f,{title:t});ba(h,f,s)}Nt(e,h,d),d=!0,n=void 0;continue}Nt(e,h,d)}}catch(h){if(Vt(h))return;throw h}d=!1,n=void 0}}async streamMessages(t,e){let a=new AbortController,r=()=>a.abort();if(this.transport)return{uiMessageStream:await this.transport.sendMessages({trigger:"submit-message",chatId:this.chatId,messageId:void 0,messages:t,abortSignal:a.signal}),message:Mt(t),abort:r};let n=this.agent,i=await n.stream({prompt:await oa(t,{tools:n.tools}),abortSignal:a.signal,options:void 0,experimental_sandbox:this.sandbox});return{uiMessageStream:va(i.fullStream,e,t),message:Mt(t),abort:r}}};function pa(t){return t.tools===void 0&&t.reasoning===void 0&&t.responseStatistics===void 0&&t.contextSize===void 0?new wt:new wt({tools:t.tools,reasoning:t.reasoning,responseStatistics:t.responseStatistics,contextSize:t.contextSize})}function fa(t){if(t.renderer)return t.renderer;if(!t.screen&&!t.userInput)return;return new wt({tools:t.tools,reasoning:t.reasoning,responseStatistics:t.responseStatistics,contextSize:t.contextSize,input:t.userInput,output:t.screen})}async function*va(t,e,a=[]){var r,n;let i=new Set,d=new Set,p=new Set,h,m,f=!1;yield{type:"start",messageId:(n=(r=Mt(a))==null?void 0:r.id)!=null?n:e()};for await(let s of t)switch(s.type){case"text-start":i.add(s.id),yield{type:"text-start",id:s.id,providerMetadata:s.providerMetadata};break;case"text-delta":if(!i.has(s.id))i.add(s.id),yield{type:"text-start",id:s.id,providerMetadata:s.providerMetadata};yield{type:"text-delta",id:s.id,delta:s.text,providerMetadata:s.providerMetadata};break;case"text-end":i.delete(s.id),yield{type:"text-end",id:s.id,providerMetadata:s.providerMetadata};break;case"reasoning-start":d.add(s.id),yield{type:"reasoning-start",id:s.id,providerMetadata:s.providerMetadata};break;case"reasoning-delta":if(!d.has(s.id))d.add(s.id),yield{type:"reasoning-start",id:s.id,providerMetadata:s.providerMetadata};yield{type:"reasoning-delta",id:s.id,delta:s.text,providerMetadata:s.providerMetadata};break;case"reasoning-end":d.delete(s.id),yield{type:"reasoning-end",id:s.id,providerMetadata:s.providerMetadata};break;case"tool-input-start":yield{type:"tool-input-start",toolCallId:s.id,toolName:s.toolName,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic,title:s.title};break;case"tool-input-delta":yield{type:"tool-input-delta",toolCallId:s.id,inputTextDelta:s.delta};break;case"tool-call":p.add(s.toolCallId),yield{type:"tool-input-available",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic,title:s.title};break;case"tool-approval-request":if(!p.has(s.toolCall.toolCallId))p.add(s.toolCall.toolCallId),yield{type:"tool-input-available",toolCallId:s.toolCall.toolCallId,toolName:s.toolCall.toolName,input:s.toolCall.input,providerExecuted:s.toolCall.providerExecuted,providerMetadata:s.toolCall.providerMetadata,toolMetadata:s.toolCall.toolMetadata,dynamic:s.toolCall.dynamic,title:s.toolCall.title};yield{type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId,isAutomatic:s.isAutomatic};break;case"tool-approval-response":yield{type:"tool-approval-response",approvalId:s.approvalId,approved:s.approved,reason:s.reason,providerExecuted:s.providerExecuted};break;case"tool-result":yield{type:"tool-output-available",toolCallId:s.toolCallId,output:s.output,providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic,preliminary:s.preliminary};break;case"tool-error":yield{type:"tool-output-error",toolCallId:s.toolCallId,errorText:Dt(s.error),providerExecuted:s.providerExecuted,providerMetadata:s.providerMetadata,toolMetadata:s.toolMetadata,dynamic:s.dynamic};break;case"tool-output-denied":yield{type:"tool-output-denied",toolCallId:s.toolCallId};break;case"source":if(s.sourceType==="url")yield{type:"source-url",sourceId:s.id,url:s.url,title:s.title,providerMetadata:s.providerMetadata};else yield{type:"source-document",sourceId:s.id,mediaType:s.mediaType,title:s.title,filename:s.filename,providerMetadata:s.providerMetadata};break;case"file":yield{type:"file",url:qt(s.file.mediaType,s.file.base64),mediaType:s.file.mediaType,providerMetadata:s.providerMetadata};break;case"reasoning-file":yield{type:"reasoning-file",url:qt(s.file.mediaType,s.file.base64),mediaType:s.file.mediaType,providerMetadata:s.providerMetadata};break;case"start-step":yield{type:"start-step"};break;case"finish-step":h=s.usage,m=s.performance,yield{type:"finish-step"};break;case"finish":yield*zt(i,d),f=!0,yield{type:"finish",finishReason:s.finishReason,messageMetadata:ma(h!=null?h:s.totalUsage,m)};break;case"abort":yield{type:"abort",reason:s.reason};break;case"error":yield{type:"error",errorText:Dt(s.error)};break}if(!f)yield*zt(i,d),yield{type:"finish"}}function ma(t,e){if((t==null?void 0:t.totalTokens)==null&&(t==null?void 0:t.outputTokens)==null&&(e==null?void 0:e.outputTokensPerSecond)==null)return;return{...(t==null?void 0:t.totalTokens)==null&&(t==null?void 0:t.outputTokens)==null?{}:{usage:{...t.totalTokens==null?{}:{totalTokens:t.totalTokens},...t.outputTokens==null?{}:{outputTokens:t.outputTokens}}},...(e==null?void 0:e.outputTokensPerSecond)==null?{}:{performance:{outputTokensPerSecond:e.outputTokensPerSecond}}}}function*zt(t,e){for(let a of t)yield{type:"text-end",id:a};t.clear();for(let a of e)yield{type:"reasoning-end",id:a};e.clear()}function ga(t,e){return{id:t,role:"user",parts:[{type:"text",text:e}]}}function Nt(t,e,a){var r;if(a&&((r=t.at(-1))==null?void 0:r.role)==="assistant"){t[t.length-1]=e;return}t.push(e)}function Mt(t){let e=t.at(-1);return(e==null?void 0:e.role)==="assistant"?e:void 0}function ya(t){let e=[];for(let[a,r]of t.parts.entries()){if(!le(r)||r.state!=="approval-requested"||r.approval.isAutomatic===!0)continue;e.push({approvalId:r.approval.id,toolCallId:r.toolCallId,toolName:ca(r),title:r.title,input:r.input,providerExecuted:r.providerExecuted,messageId:t.id,partIndex:a})}return e}function ba(t,e,a){let r=t.parts[e.partIndex];if(!r||!le(r)||r.toolCallId!==e.toolCallId)throw Error(`Could not find tool approval request ${e.approvalId}.`);r.state="approval-responded",r.approval={id:e.approvalId,approved:a.approved,...a.reason?{reason:a.reason}:{}}}function Dt(t){if(t instanceof Error)return t.message;if(typeof t==="string")return t;return JSON.stringify(t)}function qt(t,e){return`data:${t};base64,${e}`}function Vt(t){return t instanceof Error&&t.message==="Interrupted"}async function oe(t){await new ha(t).run()}import{convertToModelMessages as ka,generateId as ue,toTextStream as xa,toUIMessageStream as Ta}from"ai";async function Aa(t){if(t.prompt!==void 0)wa(t.prompt);await oe({title:`broods · ${t.agent.name}`,tools:"full",transport:new ce(t.client,t.agent)})}async function Ua(t){let e=xa({stream:de(t.client.stream(t.agent,{input:t.prompt}),void 0,()=>{})});for await(let a of e)process.stdout.write(a);process.stdout.write(`
17
+ `)}async function wa(t){let e=process.stdin.listenerCount("data"),a=Date.now()+1e4;while(process.stdin.listenerCount("data")<=e){if(Date.now()>a)return;await new Promise((r)=>setTimeout(r,20))}process.stdin.emit("data",Buffer.from(t)),process.stdin.emit("data",Buffer.from("\r"))}class ce{client;agent;conversationKey=`tui-${ue()}`;sentApprovals=new Set;sentUserTurns=0;constructor(t,e){this.client=t;this.agent=e}async reconnectToStream(){return null}async sendMessages(t){let e=this.pendingEvents(await ka(t.messages));if(e.events.length===0)throw Error("Nothing new to send: the agent already saw this turn.");let a=this.client.stream(this.agent,{conversationKey:this.conversationKey,events:e.events});return Ta({stream:de(a,t.abortSignal,e.commit),originalMessages:t.messages,generateMessageId:ue,sendSources:!0})}pendingEvents(t){let e=[],a=[],r=0;for(let n of t){if(n.role==="user"){if(r+=1,r>this.sentUserTurns)e.push(n);continue}if(n.role!=="tool")continue;for(let i of n.content)if(i.type==="tool-approval-response"&&!this.sentApprovals.has(i.approvalId))a.push(i)}if(a.length>0)e.push({role:"tool",content:a});return{events:e,commit:()=>{this.sentUserTurns=r;for(let n of a)this.sentApprovals.add(n.approvalId)}}}}function Ma(t){return new Promise((e)=>{if(!t)return;let a=()=>e({done:!0,value:void 0});if(t.aborted)a();else t.addEventListener("abort",a,{once:!0})})}function de(t,e,a){let r=!1,n=()=>void t.return(void 0);return new ReadableStream({pull:async function(i){let d=await Promise.race([t.next(),Ma(e)]);if(e?.aborted){n(),i.close();return}if(!r)r=!0,a();if(d.done)i.close();else i.enqueue(d.value)},cancel:n})}export{Aa as runAgentTui,Ua as streamAgentText};