fluxflow-cli 4.6.0 → 4.6.2

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.
@@ -1,239 +0,0 @@
1
- import{A as Oi,B as ur,C as Pi,D as Ni,E as Fi,F as Ui,G as as,H as Vo,I as mr,R as $i,U as _i,V as On,W as Hi,X as Wi,Y as Gi,a as ut,b as pt,c as mt,d as Ei,e as rs,f as ss,g as In,h as Di,i as ho,j as vi,k as je,l as qe,m as dr,n as An,o as is,p as ki,q as an,r as Gt,s as Ii,t as Ln,u as ko,v as dn,w as cr,x as ls,y as Ai,z as Li}from"./chunk-27R5UNHK.js";import{b as ln,c as es,k as yi}from"./chunk-ACHIC75V.js";import{b as ns}from"./chunk-INAFOYCM.js";import{a as Si,b as Ci,c as lr,d as ar,f as yt,g as Yo,h as os,l as Mi}from"./chunk-XGA3P7TV.js";import{a as pi,b as wi,c as Ti,e as vo,f as no,g as bi,h as ts,i as Dt}from"./chunk-N5EE3XWJ.js";import{c as fi,d as hi,e as xi}from"./chunk-SIINYZWE.js";import{e as Bi}from"./chunk-3JTGIHTN.js";import{a as sn,b as kn,c as fo,d as ir,e as Zr,j as Rr}from"./chunk-I27MASHH.js";import{a as Xi}from"./chunk-56EJGQU3.js";import"./chunk-LXTXILI5.js";import Is from"os";import e,{useState as q,useEffect as Qe,useRef as Ve,useMemo as fn}from"react";import{Box as c,Text as s,useInput as Ed,useStdout as Dd,Static as vd}from"ink";import kd from"ink-spinner";import lt from"fs-extra";import It from"path";import{exec as Cr}from"child_process";import{fileURLToPath as Id}from"url";import Nt,{useState as gr,useEffect as ds,useMemo as Pn,useCallback as Jl,useRef as xo}from"react";import{Box as Zl,Text as eo,useInput as Rl}from"ink";function ea(t,g){return t.replace(/\t/g," ".repeat(g))}function fr(t){return t==null?"":t.replace(/\r\n/g,`
2
- `).replace(/\r/g,`
3
- `)}function jo(t,g,x){let S=t,w=[...g].sort((i,D)=>i.start-D.start),p=0;for(let i of w){let D=i.start-p,m=fr(i.text).split(`
4
- `).length,B=i.text.length,M=(m>3?`[Pasted ${m} lines]`:`[Pasted ${B} chars]`).length,X=D+M;if(t<=D)break;if(t<X){S=i.end;break}else{let E=i.text.length-M;S+=E,p+=E}}return Math.min(S,x.length)}function cs(t,g,x,S,w=[]){let p=(t||"").slice(0,g),i=S(p).length,D=S(t||""),m=[...w].sort((O,L)=>L.start-O.start);for(let O of m){let L=S(t.slice(0,O.start)).length,$=S(O.text),te=L+$.length,ae=fr(O.text).split(`
5
- `).length,fe=O.text.length,Q=ae>3?`[Pasted ${ae} lines]`:`[Pasted ${fe} chars]`;D=D.slice(0,L)+Q+D.slice(te),i>L&&i<te?i=L+Q.length:i>=te&&(i=i-(te-L)+Q.length)}let B=D.split(`
6
- `),M=[],X=0,E=0,v=0,k=!1;for(let O=0;O<B.length;O++){let L=B[O];if(L.length===0){!k&&i===X&&(E=M.length,v=0,k=!0),M.push({text:"",globalStart:jo(X,w,t),formattedStart:X}),X+=1;continue}let te=pt(L,x).split(`
7
- `),ae=0,fe=[];for(let Q=0;Q<te.length;Q++){let K=te[Q],re=K.trim();if(re.length===0){let Ee=K.length||1;fe.push({text:K,start:ae,length:Ee}),ae+=Ee}else{let Ee=L.indexOf(re,ae);if(Ee!==-1){let ye=ae,ke=Q<te.length-1?te[Q+1].trim():"",de=L.length;if(ke.length>0){let Pe=L.indexOf(ke,Ee+re.length);Pe!==-1&&(de=Pe)}fe.push({text:L.slice(ye,de),start:ye,length:de-ye}),ae=de}else fe.push({text:K,start:ae,length:K.length}),ae+=K.length}}for(let Q=0;Q<fe.length;Q++){let K=fe[Q],re=K.text,Ee=X+K.start,ye=Ee+K.length;!k&&i>=Ee&&(i<ye||i===ye&&Q===fe.length-1)&&(E=M.length,v=i-Ee,k=!0),M.push({text:re,globalStart:jo(Ee,w,t),formattedStart:Ee})}X+=L.length+1}return k||(M.length===0?M.push({text:"",globalStart:0,formattedStart:0}):D.endsWith(`
8
- `)?(M.push({text:"",globalStart:jo(X,w,t),formattedStart:X}),E=M.length-1,v=0):(E=M.length-1,v=M[E].text.length)),{visualLines:M,cursorLine:E,cursorCol:v}}var ta=({value:t,rows:g,maxRows:x,highlightStyle:S,textStyle:w,placeholder:p="",mask:i,showCursor:D=!0,focus:m=!0,tabSize:B=4,cursorIndex:M=0,highlight:X,columns:E=80,pasteBlocks:v=[],cursorColor:k})=>{let O=xo(0),L=Pn(()=>Math.max(20,E-10),[E]),$=Jl((he,R=!1)=>{let P=fr(he);if(!R&&i)return P.replace(/[^\n]/g,i);let ee=ea(P,B);return R?ee:ee.replace(/@\[(.*?)\]/g,(se,be)=>{let ve=be.indexOf("#"),Se=be.indexOf(":L"),Ie=be,Re="";ve!==-1?(Ie=be.slice(0,ve),Re=be.slice(ve)):Se!==-1&&(Ie=be.slice(0,Se),Re=be.slice(Se));let ot=Ie.replace(/\\/g,"/"),De=(process.cwd()||"").replace(/\\/g,"/");De&&ot.toLowerCase().startsWith(De.toLowerCase()+"/")?ot=ot.slice(De.length+1):ot.startsWith("./")&&(ot=ot.slice(2));let oe=ot.split("/");return`[${oe[oe.length-1]}${Re}]`})},[B,i]),{visualLines:te,cursorLine:ae,cursorCol:fe}=Pn(()=>cs(t,M,L,$,v),[t,M,L,$,v]),Q=te.length,K=Pn(()=>Math.max(g??x??1,Math.min(x??g??1,Q)),[g,x,Q]),re=ae+1,Ee=O.current+K,ye=O.current;re<=O.current?ye=Math.max(0,re-1):re>Ee?ye=re-K:Q&&(Q<K?ye=0:Q<Ee&&(ye=Q-K)),O.current=ye;let ke=Pn(()=>te.slice(ye,ye+K),[te,ye,K]),[de,Pe]=gr(!0);ds(()=>{if(Pe(!0),!m||!D)return;let he=setInterval(()=>{Pe(R=>!R)},530);return()=>clearInterval(he)},[m,D,t,M]);let Te=Pn(()=>({...w,color:D&&m&&de?k||"white":void 0,bold:D&&m&&de,inverse:D&&m&&de}),[w,D,m,de,k]),G=(he,R,P,ee)=>{if(!he){let Ie=p&&t.length===0?$(p,!0):"";if(R){let Re=Ie[0]||" ",ot=Ie.slice(1);return Nt.createElement(eo,null,Nt.createElement(eo,{...ee},Re),Nt.createElement(eo,{color:"gray",dimColor:!0},ot))}return Nt.createElement(eo,{color:"gray",dimColor:!0},Ie||" ")}let se=/(\[Pasted \d+ (?:lines|chars)\])/g,be=he.split(se),ve=0,Se=[];for(let Ie=0;Ie<be.length;Ie++){let Re=be[Ie];if(Re==="")continue;let ot=Re.match(/^\[Pasted \d+ (?:lines|chars)\]$/),De=Re.length,oe=ve+De;if(R&&P>=ve&&P<oe){let me=P-ve,_e=Re.slice(0,me),H=Re[me]||" ",Mt=Re.slice(me+1);Se.push(Nt.createElement(eo,{key:Ie},Nt.createElement(eo,{color:ot?"magenta":void 0},_e),Nt.createElement(eo,{...ee},H),Nt.createElement(eo,{color:ot?"magenta":void 0},Mt)))}else Se.push(Nt.createElement(eo,{key:Ie,color:ot?"magenta":void 0},Re));ve=oe}return R&&P>=he.length&&Se.push(Nt.createElement(eo,{key:"cursor-end",...ee}," ")),Nt.createElement(Nt.Fragment,null,Se)};return Nt.createElement(Zl,{height:K,width:L+1,overflow:"hidden",flexDirection:"column",flexGrow:0,flexShrink:0},ke.map((he,R)=>{let P=ye+R,ee=P===ae&&m&&D;return Nt.createElement(eo,{key:P,...w,wrap:"truncate"},G(he.text,ee,fe,Te))}))},Yi=({value:t,onChange:g,onSubmit:x,keyBindings:S,showCursor:w=!0,highlightPastedText:p=!1,focus:i=!0,columns:D=80,useCustomInput:m=(E,v)=>Rl(E,{isActive:v}),onPasteStateChange:B,cursorColor:M,...X})=>{let[E,v]=gr(t.length),[k,O]=gr(0),[L,$]=gr([]),te=xo(t.length),ae=xo(t),fe=xo(0),Q=xo([]),K=xo(""),re=xo(-1),Ee=xo(null),ye=xo(0);te.current=E,ae.current=t,fe.current=k,Q.current=L,ds(()=>{te.current>t.length&&(te.current=t.length,v(t.length)),t?$(Pe=>Pe.filter(Te=>Te.end<=t.length&&Te.start<=t.length)):($([]),O(0))},[t]),ds(()=>{B?.(L.length>0)},[L,B]);let ke=()=>{let Pe=K.current,Te=re.current,G=Te+Pe.length,he=ae.current,R=he.slice(0,Te)+Pe+he.slice(Te);g(R),te.current=G,v(G),O(Pe.length>1?Pe.length:0);let P=fr(Pe).split(`
9
- `).length,ee=Pe.length;if(ee>50&&(P>3||P<=3&&ee>200)){let se={start:Te,end:G,text:Pe};$(be=>{let ve=Pe.length;return[...be.map(Ie=>Te<=Ie.start?{...Ie,start:Ie.start+ve,end:Ie.end+ve}:Ie),se]})}K.current="",re.current=-1,Ee.current=null},de=()=>{Ee.current&&(clearTimeout(Ee.current),ke())};return m((Pe,Te)=>{if(Pe==="\x1B[I"||Pe==="\x1B[O"||Pe==="[I"||Pe==="[O")return;let G=Pe,he=!1,R=!1;G&&typeof G=="string"&&(G.includes("\x1B[200~")&&(he=!0,G=G.replace(/\x1b\[200~/g,"")),G.includes("\x1B[201~")&&(R=!0,G=G.replace(/\x1b\[201~/g,"")));let P=te.current,ee=ae.current,se=Q.current,be=Math.max(20,D-10),ve=(oe,me)=>{if(se.length===0)return;let _e=se.map(H=>oe<=H.start?{...H,start:H.start+me,end:H.end+me}:oe>H.start&&oe<H.end?null:H).filter(Boolean);$(_e)},Se=oe=>{for(let me of se)if(oe>me.start&&oe<me.end)return me.start;return oe};if(Te.ctrl&&(G==="o"||G==="")){$([]);return}if(Te.ctrl&&(G.toLowerCase()==="r"||G===""||G===""))return;if(Te.upArrow||Te.downArrow||Te.leftArrow||Te.rightArrow){de();let oe=Date.now();if(oe-ye.current<33)return;ye.current=oe}let Re=S?.submit??(oe=>oe.return&&oe.ctrl),ot=S?.newline??(oe=>oe.return);if(Re(Te)){de(),x?.(ee);return}else if(ot(Te)){de(),ve(P,1);let oe=ee.slice(0,P)+`
10
- `+ee.slice(P);g(oe),te.current=P+1,v(P+1),O(0);return}if(Te.tab||Te.shift&&Te.tab||Te.ctrl&&G==="c")return;let De=oe=>oe;if(Te.upArrow||Te.downArrow){if(de(),w){let{visualLines:oe,cursorLine:me,cursorCol:_e}=cs(ee,P,be,De,se),H=Te.upArrow?me-1:me+1;if(H>=0&&H<oe.length){let Mt=oe[H],ct=Math.min(_e,Mt.text.length),Pt=Mt.formattedStart+ct,Vt=jo(Pt,se,ee);Vt=Se(Vt),te.current=Vt,v(Vt),O(0)}else if(Te.upArrow&&me===0)te.current=0,v(0),O(0);else if(Te.downArrow&&me===oe.length-1){let Mt=oe[oe.length-1],ct=Mt.formattedStart+Mt.text.length,Pt=jo(ct,se,ee);Pt=Se(Pt),te.current=Pt,v(Pt),O(0)}}}else if(Te.leftArrow){if(de(),w){let oe=Math.max(0,P-1),me=se.find(_e=>P===_e.end);me&&(oe=me.start),te.current=oe,v(oe),O(0)}}else if(Te.rightArrow){if(de(),w){let oe=Math.min(ee.length,P+1),me=se.find(_e=>P===_e.start);me&&(oe=me.end),te.current=oe,v(oe),O(0)}}else if(Te.backspace){de();let oe=se.findIndex(me=>P===me.end);if(oe!==-1){let me=se[oe],_e=-(me.end-me.start),H=ee.slice(0,me.start)+ee.slice(me.end);g(H),te.current=me.start,v(me.start),O(0);let Mt=se.filter((ct,Pt)=>Pt!==oe).map(ct=>ct.start>=me.end?{...ct,start:ct.start+_e,end:ct.end+_e}:ct);$(Mt)}else if(P>0){ve(P-1,-1);let me=ee.slice(0,P-1)+ee.slice(P);g(me),te.current=P-1,v(P-1),O(0)}}else if(Te.delete){de();let oe=se.findIndex(me=>P===me.start);if(oe!==-1){let me=se[oe],_e=-(me.end-me.start),H=ee.slice(0,me.start)+ee.slice(me.end);g(H),O(0);let Mt=se.filter((ct,Pt)=>Pt!==oe).map(ct=>ct.start>=me.end?{...ct,start:ct.start+_e,end:ct.end+_e}:ct);$(Mt)}else if(ve(P,-1),P<ee.length){let me=ee.slice(0,P)+ee.slice(P+1);g(me),O(0)}}else if(Te.home||Te.end){if(de(),w){let{visualLines:oe,cursorLine:me}=cs(ee,P,be,De,se),_e=oe[me];if(_e){let H;Te.home?H=jo(_e.formattedStart,se,ee):Te.end&&(H=jo(_e.formattedStart+_e.text.length,se,ee)),H=Se(H),te.current=H,v(H),O(0)}}}else if(G!==""||he||R)if(he||R||G.length>1||Ee.current!==null)Ee.current?(clearTimeout(Ee.current),K.current+=G):(re.current=P,K.current=G),R?(Ee.current=null,ke()):Ee.current=setTimeout(()=>{ke()},80);else{ve(P,G.length);let me=ee.slice(0,P)+G+ee.slice(P);g(me);let _e=P+G.length;te.current=_e,v(_e),O(0)}},i),Nt.createElement(ta,{...X,value:t,cursorIndex:E,showCursor:w,focus:i,columns:D,pasteBlocks:L,cursorColor:M})};import Mr from"ink-text-input";import"ink-select-input";import r from"react";import{Box as A,Text as Z}from"ink";import St,{useState as oa}from"react";import{Box as po,Text as wo,useInput as na}from"ink";var hr=St.memo(({command:t,output:g,completed:x=!1,isFocused:S=!1,columns:w=80,isPty:p=!1,terminalHeight:i=24,theme:D="Dark"})=>{let m=je(D),M=(fe=>{if(!fe)return"";let Q=[[]],K=0,re=0,Ee="",ye=/\x1b\[([0-9;]*?)([a-zA-Z])/g,ke=0,de,Pe=G=>{for(let he=0;he<G.length;he++){let R=G[he];if(R===`
11
- `)for(K++,re=0;K>=Q.length;)Q.push([]);else if(R==="\r")re=0;else{for(;K>=Q.length;)Q.push([]);let P=Q[K];for(;re>P.length;)P.push({char:" ",style:""});P[re]={char:R,style:Ee},re++}}};for(;(de=ye.exec(fe))!==null;){Pe(fe.substring(ke,de.index));let G=de[1],he=de[2],R=G?G.split(";").map(Number):[];if(he==="A"){let P=R[0]||1;K=Math.max(0,K-P)}else if(he==="B"){let P=R[0]||1;for(K=K+P;K>=Q.length;)Q.push([])}else if(he==="C"){let P=R[0]||1;re=re+P}else if(he==="D"){let P=R[0]||1;re=Math.max(0,re-P)}else if(he==="G"){let P=(R[0]||1)-1;re=Math.max(0,P)}else if(he==="H"||he==="f"){let P=(R[0]||1)-1,ee=(R[1]||1)-1;for(K=Math.max(0,P),re=Math.max(0,ee);K>=Q.length;)Q.push([])}else if(he==="K"){let P=R[0]||0;if(K<Q.length){let ee=Q[K];if(P===0)ee.length=re;else if(P===1)for(let se=0;se<re&&se<ee.length;se++)ee[se]={char:" ",style:""};else P===2&&(ee.length=0)}}else if(he==="J"){let P=R[0]||0;(P===2||P===3)&&(Q.length=0,Q.push([]),K=0,re=0)}else if(he==="m"){let P=de[0];P==="\x1B[0m"?Ee="":Ee=P}ke=ye.lastIndex}Pe(fe.substring(ke));let Te=Q.map(G=>{let he="",R="";for(let P=0;P<G.length;P++){let ee=G[P]||{char:" ",style:""};ee.style!==R&&(R&&(he+="\x1B[0m"),he+=ee.style,R=ee.style),he+=ee.char}return R&&(he+="\x1B[0m"),he});for(;Te.length>0&&Te[Te.length-1]==="";)Te.pop();return Te.join(`
12
- `)})(g).replace(/\n{3,}/g,`
13
-
14
- `),X=p?M?M.split(`
15
- `):[]:M?pt(M,w-6).split(`
16
- `):[],[E,v]=oa(!1);na((fe,Q)=>{S&&Q.ctrl&&(fe==="o"||fe==="")&&v(K=>!K)},{isActive:S});let k=Math.max(5,x?i-10:i-25),O=X.length>k,L=X.length-k,te=(O&&!E?X.slice(X.length-k):X).join(`
17
- `),ae=X.length>0;return St.createElement(po,{flexDirection:"column",borderStyle:S?"double":"single",borderLeft:!1,borderRight:!1,borderTop:!0,borderBottom:!0,borderColor:m.codeBorder,paddingLeft:2,paddingRight:0,paddingY:1,marginY:1,width:w-2},St.createElement(po,{marginBottom:1,justifyContent:"space-between",width:"100%"},St.createElement(po,{flexShrink:1,paddingRight:2},St.createElement(wo,null,St.createElement(wo,{color:m.text,bold:!0},x?"\u{1F3C1} FINISHED:":"\u26A1 EXECUTING:"," "),St.createElement(wo,{color:m.text},t))),p&&St.createElement(po,{flexShrink:0,paddingX:1},St.createElement(wo,{color:"green",bold:!0},"ADVANCE"))),ae?St.createElement(po,{flexDirection:"column",marginTop:0,backgroundColor:p?void 0:m.codeBg,paddingX:1,width:"100%"},O&&!E&&St.createElement(po,{marginBottom:1},St.createElement(wo,{color:"magenta"},"...",L," lines collapsed...")),St.createElement(wo,{color:m.text},te)):!x&&St.createElement(po,{marginTop:1,backgroundColor:p?void 0:m.codeBg,paddingX:1,width:"100%"},St.createElement(wo,{color:m.textMuted,italic:!0},"Waiting for output...")),St.createElement(po,{justifyContent:"space-between",marginTop:1},x?St.createElement(po,null):St.createElement(wo,{color:m.textMuted,italic:!0},S?"Press TAB to unfocus, then double-press ESC to terminate.":"Double-press ESC to terminate if hanging."),St.createElement(wo,{color:m.textMuted,bold:!0},x?"\u25CF ARCHIVED":S?"\u25B6 TERMINAL FOCUSED":"\u25CF LIVE (Press TAB to focus)")))});import{diffWordsWithSpace as ra}from"diff";var Vi=(t,g,x)=>t,sa=(t,g=80)=>{if(!t)return null;let x=g-10,S=t.trim();if(!S.includes("```"))return r.createElement(A,{width:"100%",flexDirection:"column"},r.createElement(un,{text:S,color:"#969696",columns:x,italic:!0}));let w=S.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return r.createElement(A,{width:"100%",flexDirection:"column"},w.map((p,i)=>{if(p.startsWith("```")){let m=p.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/),B=m?m[2]:p.replace(/^```\w*\n?/,"").replace(/```$/,""),M=pt(B.trimEnd(),x);return r.createElement(A,{key:i,flexDirection:"column",width:"100%"},M.split(`
18
- `).map((X,E)=>r.createElement(Z,{key:E,color:"cyan"},X)))}let D=p;return i>0&&(D=D.replace(/^[\r\n]+/,"")),i<w.length-1&&(D=D.replace(/[\r\n]+$/,"")),D?r.createElement(un,{key:i,text:D,color:"gray",columns:x,italic:!0}):null}))},ia=/(```[\s\S]*?```|`[^`\r\n]+`|@\[.*?\]|\*\*.*?\*\*|\*.*?\*|\\\(.*?\\\)|\\\[.*?\\\]|\$.*?\$|\[.*?\]\s*\(.*?\)|\[.*?\]\s*\[.*?\]|https?:\/\/[^\s]+)/g;var la=/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g,aa=/(\\(?:mathbf|textbf|textit|underline|texttt)\{[^{}]*\})/g;var da=/\\multiply|\\mul|\\times/g,ca=/\\div/g,ua=/\\cdot/g,ma=/\\infty/g,ga=/\\pm/g,fa=/\\leq/g,ha=/\\geq/g,xa=/\\neq/g,pa=/\\sqrt\s*\{([^}]+)\}/g,wa=/\\sqrt\s*(\w+|\d+)/g,Ta=/\\alpha/g,ba=/\\beta/g,ya=/\\theta/g,Sa=/\\pi/g,Ca=/\\approx/g,Ma=/\\Delta/g,Ba=/\\sigma/g,Ea=/\\sum/g,Da=/\\prod/g,va=/\\rightarrow|\\to/g,ka=/\\left\b|\\right\b/g,Ia=/\\left\(|\\right\)/g,Aa=/\\left\[|\\right\]/g,La=/\\\{|\\\}/g,Oa=/\\text\s*\{([^}]+)\}/g,Pa=/\\text\s+(\w+)/g,Na=/\\%/g,Fa=/\\\(|\\\)/g,Ua=/\\\[|\\\]/g,Xa=/@\[(.*?)\]/g,ji=/:L/gi,$a=/\[(.*?)\]\s*\((.*?)\)/,_a=/\[(.*?)\]\s*\[(.*?)\]/,Ha=/\\(\w+)\{([^{}]*)\}/,Wa=t=>t.replace(Fa,g=>g.includes("(")?"(":")").replace(Ua,g=>g.includes("[")?"[":"]").replace(da,"\xD7").replace(ca,"\xF7").replace(ua,"\u22C5").replace(ma,"\u221E").replace(ga,"\xB1").replace(fa,"\u2264").replace(ha,"\u2265").replace(xa,"\u2260").replace(pa,"\u221A($1)").replace(wa,"\u221A($1)").replace(Ta,"\u03B1").replace(ba,"\u03B2").replace(ya,"\u03B8").replace(Sa,"\u03C0").replace(Ca,"\u2248").replace(Ma,"\u0394").replace(Ba,"\u03C3").replace(Ea,"\u03A3").replace(Da,"\u03A0").replace(va,"\u2192").replace(ka,"").replace(Ia,g=>g.includes("left")?"(":")").replace(Aa,g=>g.includes("left")?"[":"]").replace(La,g=>g.includes("{")?"{":"}").replace(Oa,"$1").replace(Pa,"$1").replace(Na,"%"),Ga=/\b(const|let|var|function|return|if|else|for|while|do|switch|case|break|continue|import|export|from|default|class|extends|new|this|typeof|instanceof|try|catch|finally|throw|async|await|yield|public|private|protected|static|void|int|float|double|char|bool|boolean|def|elif|fn|pub|mut|struct|impl|enum|type|interface|package|namespace|using|include|define|nil|None|self|lambda)\b/,Ya=[/((?<=\binclude\s+)(?:<[^>]+>|"[^"]+"))/.source,/((?<=\b(?:from|import|require\s*\(\s*)\s*)(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"))/.source,/(\/\/.*|#.*)/.source,/("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^\`\\])*`)/.source,Ga.source,/\b([a-zA-Z_][a-zA-Z0-9_]*)(?=\s*\()/.source,/\b(true|false|null|undefined|nil|None)\b/.source,/\b(\d+(?:\.\d+)?|0x[0-9a-fA-F]+)\b/.source],us=new RegExp(Ya.join("|"),"g"),cn=new Map,Va=1e3,ja=(t,g)=>{if(!t)return[];let x=`${g}:${t}`;if(cn.has(x))return cn.get(x);let S=0,w=[],p;for(us.lastIndex=0;(p=us.exec(t))!==null;){let i=p[0],D=p.index;D>S&&w.push({text:ut(t.substring(S,D))});let m,B=!1;p[1]||p[2]?m="#ce9178":p[3]?m="#9ece6a":p[4]?m="#fcfca4":p[5]?(m="#ff7b72",B=!0):p[6]?m="#b392f0":(p[7]||p[8])&&(m="#ff9e64"),w.push({text:ut(i),color:m,bold:B}),S=us.lastIndex}if(S<t.length&&w.push({text:ut(t.substring(S))}),cn.size>=Va){let i=cn.keys().next().value;cn.delete(i)}return cn.set(x,w),w},Lt=(t,g,x=void 0,S=void 0)=>{if(!t)return r.createElement(Z,{backgroundColor:S}," ");let w=ja(t,g);return r.createElement(Z,{color:x,backgroundColor:S},w.map((p,i)=>r.createElement(Z,{key:i,color:p.color||x,backgroundColor:S,bold:p.bold},p.text)))},ms=(t,g)=>{if(!t)return null;let x=t.replace(la,"($1/$2)");x=Wa(x);let S=x.split(aa);return r.createElement(r.Fragment,{key:g},S.map((w,p)=>{if(w.startsWith("\\")){let i=w.match(Ha);if(i){let D=i[1],m=i[2];return r.createElement(Z,{key:p,bold:D==="mathbf"||D==="textbf",italic:D==="textit",underline:D==="underline",color:D==="texttt"?"cyan":void 0},m)}}return w}))},Io=r.memo(({text:t,color:g,italic:x,theme:S="Dark"})=>{if(!t)return null;let w=je(S),p=g||w.text,i=w.codeText||w.logoGradient&&w.logoGradient[0]||w.info||w.secondary||"cyan",D=t.split(ia);return r.createElement(Z,{color:p,wrap:"anywhere",italic:x},D.map((m,B)=>{if(!m)return null;if(m.startsWith("```")&&m.endsWith("```")){let M=m.slice(3,-3);return r.createElement(Z,{key:B,color:i},M)}if(m.startsWith("**")&&m.endsWith("**"))return r.createElement(Z,{key:B,bold:!0,color:p},r.createElement(Io,{text:m.slice(2,-2),color:p,theme:S}));if(m.startsWith("*")&&m.endsWith("*"))return r.createElement(Z,{key:B,italic:!0,color:p},r.createElement(Io,{text:m.slice(1,-1),color:p,italic:x,theme:S}));if(m.startsWith("`"))if(m.endsWith("`")&&m.length>1){let M=m.slice(1,-1),X=M.replace(Xa,(v,k)=>k.split("/").pop().split("\\").pop().replace(ji,"#L")),E=M.includes("@[");return r.createElement(Z,{key:B,color:i,bold:E},X)}else return r.createElement(Z,{key:B,color:i},m.slice(1));if(m.startsWith("@[")&&m.endsWith("]")){let X=m.slice(2,-1).split("/").pop().split("\\").pop().replace(ji,"#L");return r.createElement(Z,{key:B,color:i,bold:!0},X)}if(m.startsWith("\\(")&&m.endsWith("\\)")||m.startsWith("\\[")&&m.endsWith("\\]")){let M=m.slice(2,-2);return r.createElement(Z,{key:B,color:"yellow"},ms(M,B))}if(m.startsWith("$")&&m.endsWith("$")){let M=m.slice(1,-1);return r.createElement(Z,{key:B,color:"yellow"},ms(M,B))}if(m.startsWith("[")&&(m.includes("](")||m.includes("] ("))){let M=m.match($a);if(M)return r.createElement(Z,{key:B},r.createElement(Z,{color:i,underline:!0,bold:!0},M[1]),r.createElement(Z,{color:"gray",italic:!0}," (",M[2],")"))}if(m.startsWith("[")&&(m.includes("][")||m.includes("] ["))){let M=m.match(_a);if(M)return r.createElement(Z,{key:B},r.createElement(Z,{color:i,underline:!0,bold:!0},M[1]),r.createElement(Z,{color:"gray",italic:!0}," [",M[2],"]"))}return m.startsWith("http")?r.createElement(Z,{key:B,color:i,underline:!0,italic:!0},m):ms(m,B)}))}),Ki=r.memo(({buffer:t,terminalWidth:g=80,theme:x="Dark"})=>{if(t.length<2)return null;let S=je(x),w=S.codeText||S.secondary||S.info||"cyan",p=t.map(X=>{let E=X.split("|");return E[0]!==void 0&&E[0].trim()===""&&E.shift(),E.length>0&&E[E.length-1].trim()===""&&E.pop(),E.map(v=>v.trim())}),i=p[0],D=p.slice(2),m=Math.floor(100/i.length),B=g-8,M=Math.floor(B/i.length)-2;return r.createElement(A,{flexDirection:"column",borderStyle:"round",borderColor:S.borderMuted,paddingX:1,marginY:0,width:g-2},r.createElement(A,{flexDirection:"row",borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:S.borderMuted,marginBottom:1,paddingBottom:0,width:"100%"},i.map((X,E)=>r.createElement(A,{key:E,flexBasis:`${m}%`,flexGrow:1,flexShrink:0,paddingRight:2},r.createElement(Io,{text:pt(X,M),color:w,theme:x})))),D.map((X,E)=>r.createElement(A,{key:E,flexDirection:"row",marginBottom:E===D.length-1?0:1,width:"100%"},X.map((v,k)=>r.createElement(A,{key:k,flexBasis:`${m}%`,flexGrow:1,flexShrink:0,paddingRight:2,flexDirection:"column"},r.createElement(Io,{text:pt(v,M),color:S.text,theme:x}))))))}),un=r.memo(({text:t,color:g,columns:x=80,italic:S=!1,theme:w="Dark"})=>{if(!t)return null;let p=je(w),i=g||p.text,D=t.split(`
19
- `),m=[],B=[],M=[],X=E=>{if(B.length>0&&(m.push(r.createElement(Ki,{key:`table-${E}`,buffer:[...B],terminalWidth:x,theme:w})),B=[]),M.length>0){let v=x-6,k=M.flatMap(O=>pt(O,v).split(`
20
- `));m.push(r.createElement(A,{key:`quote-${E}`,borderStyle:"bold",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:p.borderMuted,paddingLeft:1,marginY:1,flexDirection:"column"},k.map((O,L)=>r.createElement(Io,{key:L,text:O,color:p.textMuted,italic:S,theme:w})))),M=[]}};return D.forEach((E,v)=>{let k=E.trim(),O=k.startsWith("|"),L=k.startsWith(">");if(O)M.length>0&&X(v),B.push(E);else if(L)B.length>0&&X(v),M.push(k.replace(/^>\s*/,""));else{if(X(v),k===""){m.push(r.createElement(A,{key:v,height:1}));return}if(k==="---"||k==="***"||k==="___"){m.push(r.createElement(A,{key:v,marginY:0,borderStyle:"single",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%",borderColor:p.borderMuted}));return}let $=k.match(/^(#{1,6})\s+(.*)/);if($){let K=$[1].length,re=$[2];m.push(r.createElement(A,{key:v,marginTop:1,marginBottom:0,width:"100%"},r.createElement(Z,{bold:!0,color:K===1?"cyan":K===2?"magenta":K===3?"yellow":K===4?"green":K===5?"blue":p.text,underline:!0},re)));return}let te=/^[\*\-\+]\s/.test(k),ae=/^\d+\.\s/.test(k),fe=E.includes("\u2588")||E.includes("\u2554")||E.includes("\u255A")||E.includes("\u2550"),Q="";if(fe)Q=E;else if(te||ae){let K=te?" \u2022 ":k.match(/^\d+\.\s/)[0],re=" ".repeat(K.length),Ee=pt(k.replace(/^[\*\-\d+\.]+\s/,""),x-(K.length+6));Q=K+Ee.split(`
21
- `).join(`
22
- `+re)}else Q=pt(k,x-4);m.push(r.createElement(A,{key:v,flexDirection:"column",width:"100%"},r.createElement(Io,{text:Q,color:i,italic:S,theme:w})))}}),X("final"),r.createElement(A,{flexDirection:"column",width:x-2},m)}),qi=r.memo(({line:t,pairContent:g,parentText:x,columns:S=80,extension:w,theme:p="Dark"})=>{let i=je(p),D=t.includes("[UI_CONTEXT]"),m=t.replace("[UI_CONTEXT]","");if(D&&m.includes("\u2550"))return r.createElement(A,{backgroundColor:i.codeBg,paddingX:1,width:S},r.createElement(Z,{color:"gray"},"\u2550".repeat(Math.max(10,S-4))));let B=rs(t);if(!B)return r.createElement(A,{backgroundColor:i.codeBg,paddingX:1,width:S},r.createElement(A,{width:3,flexShrink:0}),r.createElement(A,{width:1,flexShrink:0,marginLeft:1}),r.createElement(A,{flexGrow:1,marginLeft:1},r.createElement(Z,{color:"gray"},pt(m,S-14))));let{isR:M,isA:X,num:E,content:v}=B,k=g,O=[];if(k!=null){let re=M?v:k,Ee=M?k:v;try{O=ra(re,Ee)}catch{O=[]}}let L=O.some(re=>M&&re.removed||X&&re.added),$=!k&&(M||X),te=M?i.diffRemovalBg:X?i.diffAdditionBg:void 0,ae=M||X?M?i.diffRemovalNum:i.diffAdditionNum:i.textMuted,fe=M?i.diffRemovalPrefix:i.diffAdditionPrefix,Q=M?"-":X?"+":" ",K=()=>{if($){let R=M?i.diffRemovalHighlightBg:i.diffAdditionHighlightBg;return r.createElement(A,{flexDirection:"column"},Lt(pt(v,S-15),w,void 0,R))}if(!(M||X)||O.length===0||!L){let R=M?i.diffRemovalText:X?i.diffAdditionText:i.textMuted;return r.createElement(A,{flexDirection:"column"},Lt(pt(v,S-15),w,R,void 0))}let re=Math.max(10,S-15),Ee=pt(v,re).split(`
23
- `),ye=[];if(O.forEach((R,P)=>{let ee=/^\s+$/.test(R.value);if(M){let se=O[P-1]?.removed||O[P+1]?.removed;R.removed||ee&&se?ye.push({text:R.value,isHighlight:!0}):R.added||ye.push({text:R.value,isHighlight:!1})}else if(X){let se=O[P-1]?.added||O[P+1]?.added;R.added||ee&&se?ye.push({text:R.value,isHighlight:!0}):R.removed||ye.push({text:R.value,isHighlight:!1})}}),Ee.length<=1)return r.createElement(Z,{wrap:"wrap"},ye.map((R,P)=>M?R.isHighlight?r.createElement(r.Fragment,{key:P},Lt(R.text,w,i.diffRemovalHighlightColor,i.diffRemovalHighlightBg)):r.createElement(r.Fragment,{key:P},Lt(R.text,w,i.diffRemovalText)):X?R.isHighlight?r.createElement(r.Fragment,{key:P},Lt(R.text,w,i.diffAdditionHighlightColor,i.diffAdditionHighlightBg)):r.createElement(r.Fragment,{key:P},Lt(R.text,w,i.diffAdditionText)):r.createElement(r.Fragment,{key:P},Lt(R.text,w,i.textMuted))));let ke=0,de=0,Pe=v.match(/^(\s*)/),Te=Pe?Pe[1]:"",G=Te.substring(0,Math.min(Te.length,8)),he=Ee.map((R,P)=>{let ee=[],se=R;P>0&&G&&R.startsWith(G)&&((ye[ke]?ye[ke].text.substring(de):"").startsWith(G)||(ee.push({text:G,isHighlight:!1}),se=R.substring(G.length)));let be=se.length;for(;be>0&&ke<ye.length;){let ve=ye[ke],Se=ve.text.length-de;if(Se<=0){ke++,de=0;continue}let Ie=Math.min(be,Se);ee.push({text:ve.text.substring(de,de+Ie),isHighlight:ve.isHighlight}),de+=Ie,be-=Ie,de>=ve.text.length&&(ke++,de=0)}for(;ke<ye.length;){let ve=ye[ke],Se=ve.text.substring(de);if(/^\s+$/.test(Se))ke++,de=0;else if(Se.startsWith(" ")||Se.startsWith(" ")){let Ie=0;for(;Ie<Se.length&&(Se[Ie]===" "||Se[Ie]===" ");)Ie++;de+=Ie,de>=ve.text.length&&(ke++,de=0);break}else break}return ee});if(ke<ye.length){let R=he[he.length-1];for(;ke<ye.length;){let P=ye[ke];R.push({text:P.text.substring(de),isHighlight:P.isHighlight}),ke++,de=0}}return r.createElement(A,{flexDirection:"column"},he.map((R,P)=>r.createElement(A,{key:P},r.createElement(Z,{wrap:"wrap"},R.map((ee,se)=>M?ee.isHighlight?r.createElement(r.Fragment,{key:se},Lt(ee.text,w,i.diffRemovalHighlightColor,i.diffRemovalHighlightBg)):r.createElement(r.Fragment,{key:se},Lt(ee.text,w,i.diffRemovalText)):X?ee.isHighlight?r.createElement(r.Fragment,{key:se},Lt(ee.text,w,i.diffAdditionHighlightColor,i.diffAdditionHighlightBg)):r.createElement(r.Fragment,{key:se},Lt(ee.text,w,i.diffAdditionText)):r.createElement(r.Fragment,{key:se},Lt(ee.text,w,i.textMuted)))))))};return r.createElement(A,{backgroundColor:i.codeBg,paddingX:1,width:S},r.createElement(A,{width:4,flexShrink:0,justifyContent:"flex-end"},r.createElement(Z,{color:ae},E)),r.createElement(A,{width:1,flexShrink:0,marginLeft:1},r.createElement(Z,{color:fe},Q)),r.createElement(A,{marginLeft:1,backgroundColor:te,flexGrow:1},K()))}),Ka=r.memo(({text:t,columns:g=80,extension:x,theme:S="Dark"})=>{let w=je(S),p=t.match(/\[DIFF_START\]([\s\S]*?)(?:\[DIFF_END\]|$)/),m=(p?p[1].trim():"").split(`
24
- `).map(M=>({line:M,parsed:rs(M),pairContent:null})),B=[];for(let M=0;M<m.length;M++){let X=m[M];X.parsed&&(X.parsed.isR||X.parsed.isA)?B.push(X):B.length>0&&(ss(B),B=[])}return B.length>0&&ss(B),r.createElement(A,{flexDirection:"column",width:g-3,marginBottom:1},r.createElement(A,{flexDirection:"column",paddingY:0,width:"100%"},r.createElement(A,{backgroundColor:w.codeBg,paddingX:1,width:"100%"},r.createElement(A,{width:3,flexShrink:0}),r.createElement(A,{width:1,flexShrink:0,marginLeft:1}),r.createElement(A,{flexGrow:1,marginLeft:1},r.createElement(Z,null," "))),m.map((M,X)=>r.createElement(qi,{key:X,line:M.line,pairContent:M.pairContent,columns:g-3,extension:x,theme:S})),r.createElement(A,{backgroundColor:w.codeBg,paddingX:1,width:"100%"},r.createElement(A,{width:3,flexShrink:0}),r.createElement(A,{width:1,flexShrink:0,marginLeft:1}),r.createElement(A,{flexGrow:1,marginLeft:1},r.createElement(Z,null," ")))))}),Nn=r.memo(({text:t,columns:g=80,theme:x="Dark"})=>{if(!t)return null;let S=je(x),w="",p=t.match(/File\s+\[(.*?)\]/i);if(p&&(w=p[1].split(".").pop().toLowerCase()),t.includes("[DIFF_START]"))return r.createElement(Ka,{text:t,columns:g,extension:w,theme:x});if(t.includes("- Content Preview:")){let i=t.split("- Content Preview:"),D=i[0],m=i[1]||"",B="[SYSTEM] Check the content preview for verification [/SYSTEM]",M=m.split(B),X=M[0]?.trim()||"",E=M[1]?`${B}${M[1]}`:"",v=X.split(`
25
- `),k=String(v.length).length;return r.createElement(A,{flexDirection:"column",width:g-3},r.createElement(A,{flexDirection:"column",borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:S.codeBorder,paddingLeft:2,paddingRight:0,width:"100%",marginBottom:1,backgroundColor:S.codeBg},r.createElement(A,{flexDirection:"column",width:"100%"},r.createElement(A,{width:"100%"},r.createElement(A,{width:k+2,flexShrink:0},r.createElement(Z,null," ")),r.createElement(A,{flexGrow:1},r.createElement(Z,null," "))),v.map((O,L)=>r.createElement(A,{key:L,width:"100%"},r.createElement(A,{width:k+2,flexShrink:0},r.createElement(Z,{color:"gray",dimColor:!0},String(L+1).padStart(k," ")," ")),r.createElement(A,{flexGrow:1},Lt(O,w,S.text)))),r.createElement(A,{width:"100%"},r.createElement(A,{width:k+2,flexShrink:0},r.createElement(Z,null," ")),r.createElement(A,{flexGrow:1},r.createElement(Z,null," "))))))}if(t.includes("```")){let i=t.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return r.createElement(A,{flexDirection:"column",width:g-3},i.map((D,m)=>{if(D.startsWith("```")){let M=D.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/),X=M?M[1]:"code",E=M?M[2]:D.replace(/^```\w*\n?/,"").replace(/```$/,""),v=E.trimEnd().split(`
26
- `),k=String(v.length).length,O=g-7-k,$=(O>5?pt(E,O):E).trimEnd().split(`
27
- `);return r.createElement(A,{key:m,flexDirection:"column",marginY:0,paddingLeft:2,paddingRight:0,width:"100%"},r.createElement(A,null,r.createElement(Z,{color:"gray",bold:!0},"\u25B6_ ",X.toUpperCase()||"TEXT")),r.createElement(A,{flexDirection:"column",width:"100%"},$.map((te,ae)=>{let Q=pt(te,Math.max(10,O)).split(`
28
- `);return r.createElement(A,{key:ae,flexDirection:"column",width:"100%"},Q.map((K,re)=>r.createElement(A,{key:re,width:"100%"},r.createElement(A,{width:k+2,flexShrink:0},r.createElement(Z,{color:"gray"},re===0?String(ae+1).padStart(k," ")+" ":" ".repeat(k+1))),r.createElement(A,{flexGrow:1},Lt(K,X,S.text)))))})))}let B=D;return m>0&&(B=B.replace(/^[\r\n]+/,"")),m<i.length-1&&(B=B.replace(/[\r\n]+$/,"")),B?r.createElement(un,{key:m,text:B,columns:g-3,theme:x}):null}))}return r.createElement(un,{text:t,columns:g-3,theme:x})}),gs=t=>{let g=Math.round(t/1e3);if(g<=0)return"0s";let x=Math.floor(g/60),S=g%60;return x>0?`${x}m ${S}s`:`${g}s`},Qi=r.memo(({msg:t,showFullThinking:g,columns:x=80,aiProvider:S,version:w,theme:p="Dark"})=>{let i=je(p),D=t.role==="system"&&(t.text?.includes("[DIFF_START]")||t.text?.includes("- Content Preview:")),m=t.role==="system"&&t.text?.includes("[TOOL RESULT]: ERROR:")&&!t.text?.includes("[DIFF_START]")&&(t.toolName==="update_file"||t.text?.includes("Could not find exact match")),B=t.isTerminalRecord;if(t.isHomeWarning)return r.createElement(A,{marginBottom:1,paddingX:1,width:"100%"},r.createElement(A,{flexDirection:"column",borderStyle:"round",borderColor:i.border,dimColor:!0,padding:0,width:"100%"},r.createElement(A,{paddingX:1},r.createElement(Z,{color:i.text,bold:!0},t.text)),r.createElement(A,{paddingX:1,marginTop:0,marginBottom:0},r.createElement(Z,{color:i.text},t.subText))));if(t.isLogo)return r.createElement(A,{flexDirection:"column",alignItems:"flex-start",width:"100%",marginY:1},r.createElement(Z,null,dr(w,S,p)));if(t.id&&String(t.id).startsWith("welcome"))return r.createElement(A,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},r.createElement(A,{borderStyle:"round",borderColor:i.borderMuted,paddingX:3,paddingY:0},r.createElement(Z,{color:i.text,bold:!0},t.text.trim())));if(t.isVisualFeedback)return r.createElement(A,{marginBottom:0,marginTop:0,paddingX:0,width:"100%"},r.createElement(Z,{color:i.text},t.text));if(m)return r.createElement(A,{marginBottom:1},r.createElement(A,{flexDirection:"column",borderStyle:"round",borderColor:i.border,paddingX:1,paddingY:0},r.createElement(Z,{color:i.text,bold:!0,underline:!0},"\u2717 PATCH FAILED"),r.createElement(A,{marginTop:1},r.createElement(Z,{color:i.textMuted,bold:!0},"Model generated malformed edit."))));if(t.role==="system"&&t.text?.includes("[TOOL RESULT]")&&!D&&!B&&!m)return null;if(t.isImageStats)return r.createElement(A,{marginBottom:1,paddingX:1,width:"100%"},r.createElement(A,{flexDirection:"column",borderStyle:"round",borderColor:i.borderMuted,padding:0,width:"100%"},r.createElement(A,{paddingX:1,backgroundColor:i.codeBg},r.createElement(Z,{color:i.text,bold:!0},"IMAGE STATS")),r.createElement(A,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"column"},t.text.split(`
29
- `).map((O,L)=>r.createElement(Z,{key:L,color:i.textMuted},O)))));if(t.isAskRecord){let O=t.text.match(/Selection: (.*)/),L=O?O[1]:"No selection",$=t.text.match(/Question: (.*)/),te=$?$[1]:null;return r.createElement(A,{marginBottom:0,paddingX:1,width:"100%"},r.createElement(A,{flexDirection:"column",borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!0,borderBottom:!0,borderColor:i.codeBorder,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,marginY:1,width:x-2},r.createElement(A,{paddingX:1},r.createElement(Z,{color:i.success,bold:!0},"AGENT REQUEST: RESOLVED")),te&&r.createElement(A,{paddingX:1,marginTop:1},r.createElement(Z,{color:i.secondary},te)),r.createElement(A,{paddingX:1,marginTop:1,marginBottom:0},r.createElement(Z,{color:i.text},"Selection: ",r.createElement(Z,{color:i.textMuted,bold:!0},L)))))}if(t.isAboutRecord)return r.createElement(A,{marginBottom:0,paddingX:1,width:"100%"},r.createElement(A,{flexDirection:"column",borderStyle:"round",border:!0,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,backgroundColor:i.codeBg,width:"100%"},r.createElement(A,{paddingX:1},r.createElement(Z,{color:i.text,bold:!0},"ABOUT FLUX FLOW")),r.createElement(A,{paddingX:1,marginTop:1,marginBottom:1},r.createElement(Z,{color:i.text},t.text))));if(t.isUpdateNotification)return r.createElement(A,{marginBottom:1,paddingX:1,width:"100%"},r.createElement(A,{flexDirection:"column",borderStyle:"round",border:!0,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,backgroundColor:i.codeBg,width:"100%"},r.createElement(A,{paddingX:1},r.createElement(Z,{color:i.text,bold:!0},"UPDATE AVAILABLE")),r.createElement(A,{paddingX:1,marginTop:1,marginBottom:1},r.createElement(Nn,{text:t.text,columns:x,theme:p}))));if(t.isHelpRecord){let O=[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/compress",desc:"Summarize and compress chat history"},{cmd:"/truncate",desc:"Truncate tool results in chat history"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase to checkpoint"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat or error logs"},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/btw",desc:"Send raw inquiry mid-turn"},{cmd:"/budget",desc:"Set or View budget limits"},{cmd:"/mode",desc:"Toggle Flux/Flow modes"},{cmd:"/thinking",desc:"Set AI reasoning depth"},{cmd:"/model",desc:"Switch AI model"},{cmd:"/wildcard-tooling",desc:"Use if the model lacks Tooling Capability"},{cmd:"/provider",desc:"Select AI Provider"},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/theme",desc:"Customize UI color theme"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/usage",desc:"Open graphical token usage & analytics in browser"},{cmd:"/reset",desc:"Wipe all saved FluxFlow AppData"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/docs",desc:"View documentation"},{cmd:"/fluxflow",desc:"Project management"},{cmd:"/update",desc:"Check/Install updates"}];return r.createElement(A,{marginBottom:1,paddingX:1,width:"100%"},r.createElement(A,{flexDirection:"column",borderStyle:"round",borderColor:i.borderMuted,paddingX:2,paddingY:1,width:"100%"},r.createElement(Z,{color:i.text,bold:!0,underline:!0},"AVAILABLE COMMANDS IN FLUX-FLOW"),r.createElement(A,{flexDirection:"column",marginTop:1},O.map((L,$)=>r.createElement(A,{key:$,flexDirection:"row"},r.createElement(A,{width:20},r.createElement(Z,{color:i.text,bold:!0},L.cmd)),r.createElement(Z,{color:i.textMuted}," - ",L.desc))))))}if(t.isTerminalRecord){let O=t.text.match(/COMMAND: (.*)/),L=t.text.match(/PTY: (true|false)/),$=t.text.match(/OUTPUT: ([\s\S]*)/),te=O?O[1]:"No Command",ae=L?L[1]==="true":!1,fe=$?$[1]:"";return r.createElement(A,{marginBottom:0,paddingX:1,width:"100%"},r.createElement(hr,{command:te,output:fe,completed:!0,columns:x,isPty:ae,theme:p}))}let[X,E]=r.useState(!t.isStreaming),v=r.useMemo(()=>Di(t.text,t.role),[t.text,t.role]);r.useEffect(()=>{t.isStreaming&&E(!1)},[t.id]);let k=r.useMemo(()=>t.role==="think"&&!g?"Thinking...":t.isStreaming?v:v.trimEnd(),[v,t.role,g,t.isStreaming]);return t.role==="agent"&&k.trim()===""?null:r.createElement(A,{marginBottom:(t.role==="think"||t.role==="user"||t.role==="agent",0),marginTop:(t.role==="think"||t.role==="user"||t.role==="agent",0),flexDirection:"column",flexShrink:0,width:"100%",flexGrow:1},t.role==="user"?r.createElement(A,{flexDirection:"column",width:x-1},r.createElement(A,{width:x-1,height:1,overflow:"hidden"},r.createElement(Z,{color:i.userMsgBorder},"\u2584".repeat(Math.max(1,x-1)))),r.createElement(A,{backgroundColor:i.userMsgBg,paddingX:1,paddingY:0,width:x-1,flexDirection:"column"},pt(k.replace(/\r\n/g,`
30
- `).replace(/\r/g,`
31
- `).replace(/\\\n/g,`
32
- `).replace(/\\$/,""),x-7).split(`
33
- `).map((O,L)=>r.createElement(A,{key:L,flexDirection:"row",width:"100%"},r.createElement(A,{flexShrink:0,width:2},r.createElement(Z,{bold:!0,color:i.userMsgText},L===0?">":" ")),r.createElement(A,{flexGrow:1,marginLeft:1},r.createElement(Io,{text:O,color:t.color||i.userMsgText,theme:p}))))),r.createElement(A,{width:x-1,height:1,overflow:"hidden"},r.createElement(Z,{color:i.userMsgBorder},"\u2580".repeat(Math.max(1,x-1))))):t.role==="think"?r.createElement(A,{flexDirection:"column",marginTop:0,marginBottom:0,paddingX:0,width:"100%"},t.isStreaming&&!t.duration?r.createElement(Z,{bold:!0,color:i.text},"\u2727 Thinking..."):r.createElement(Z,{bold:!0,color:i.text},"\u2726 Thought",t.duration?r.createElement(Z,{color:i.textMuted}," for ",r.createElement(Z,{bold:!0,color:i.text},gs(t.duration))):"s..."),r.createElement(A,{borderStyle:"single",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:i.borderMuted,paddingLeft:2,paddingTop:0,paddingBottom:0,flexDirection:"column",width:"100%"},sa(k,x))):r.createElement(A,{flexDirection:"column",paddingX:1,marginTop:0,width:"100%"},r.createElement(Nn,{text:k.replace(/ \|\n\n/g,` |
34
- `),columns:x,theme:p}),t.memoryUpdated&&r.createElement(A,{marginTop:1,width:"100%"},r.createElement(Z,{color:i.text,italic:!0},"[Memory Updated]")),t.role==="agent"&&t.workedDuration?r.createElement(A,{marginTop:1,marginBottom:2,width:"100%"},r.createElement(Z,{color:i.textMuted},"["),r.createElement(Z,{color:i.textMuted},"Worked for ",r.createElement(Z,{bold:!0,color:i.text},gs(t.workedDuration))),r.createElement(Z,{color:i.textMuted},"]")):null))}),xr=r.memo(({block:t,columns:g=80,showFullThinking:x,aiProvider:S,version:w,theme:p="Dark"})=>{let i=je(p),{msg:D,type:m,text:B,isStreamingMsg:M,workedDuration:X}=t;if(m==="chunk")return r.createElement(A,{flexDirection:"column",width:"100%"},t.blocks.map(E=>r.createElement(xr,{key:E.key,block:E,columns:g,showFullThinking:x,aiProvider:S,version:w,theme:p})));if(m==="full-message")return r.createElement(Qi,{msg:D,showFullThinking:x,columns:g,aiProvider:S,version:w,theme:p});if(m==="think-header")return r.createElement(A,{flexDirection:"column",paddingX:1,width:"100%",marginTop:0,marginBottom:0},M?r.createElement(Z,{bold:!0,color:i.text},"\u2727 Thinking..."):r.createElement(Z,{bold:!0,color:i.text},"\u2726 Thoughts..."),x&&r.createElement(A,{flexDirection:"row",width:"100%"},r.createElement(Z,{color:i.textMuted},"\u2502 ")));if(m==="think-line"){if(!x)return null;if(!B||B.trim()==="")return r.createElement(A,{flexDirection:"row",width:"100%",paddingX:1},r.createElement(Z,{color:i.textMuted},"\u2502 "));let E=Vi(B,M,t.isActiveBlock),v=E.trim(),k=/^[\*\-\+]\s/.test(v),O=/^\d+\.\s/.test(v),L=E;if(k||O){let te=k?" \u2022 ":v.match(/^\d+\.\s/)[0],ae=" ".repeat(te.length),fe=pt(v.replace(/^[\*\-\d+\.]+\s/,""),g-(te.length+10));L=te+fe.split(`
35
- `).join(`
36
- `+ae)}else L=pt(E,g-10);let $=L.split(`
37
- `);return r.createElement(A,{flexDirection:"column",paddingX:1,width:"100%"},$.map((te,ae)=>r.createElement(A,{key:ae,flexDirection:"row",width:"100%"},r.createElement(Z,{color:i.textMuted},"\u2502 "),r.createElement(A,{flexGrow:1,marginLeft:1},r.createElement(Io,{text:te,color:i.textMuted,italic:!0,theme:p})))))}if(m==="think-footer-padding")return x?r.createElement(A,{flexDirection:"row",width:"100%",paddingX:1},r.createElement(Z,{color:i.textMuted},"\u2502 ")):null;if(m==="agent-line"){if(!B||B.trim()==="")return r.createElement(A,{height:1});let E=Vi(B,M,t.isActiveBlock);return r.createElement(A,{flexDirection:"column",paddingX:1,width:"100%"},r.createElement(Nn,{text:E,columns:g,theme:p}))}if(m==="table")return r.createElement(A,{flexDirection:"column",paddingX:1,width:"100%"},r.createElement(Ki,{buffer:B.split(`
38
- `),terminalWidth:g,theme:p}));if(m==="diff-line"){let{isFirstLine:E,isLastLine:v}=t,k=(O=!1)=>r.createElement(A,{backgroundColor:i.codeBg,paddingX:1,width:g,marginBottom:O?1:0},r.createElement(A,{width:3,flexShrink:0}),r.createElement(A,{width:1,flexShrink:0,marginLeft:1}),r.createElement(A,{flexGrow:1,marginLeft:1},r.createElement(Z,null," ")));return r.createElement(A,{flexDirection:"column"},E&&k(!1),r.createElement(qi,{line:B,pairContent:t.pairContent,parentText:void 0,columns:g,theme:p}),v&&k(!0))}if(m==="code-fence-open"){let E={paddingLeft:2,width:"100%"};return r.createElement(A,{flexDirection:"column",marginTop:0,marginBottom:0,width:"100%"},r.createElement(A,{flexDirection:"row",...E},r.createElement(Z,null," ")),r.createElement(A,{flexDirection:"row",...E},r.createElement(Z,{color:"gray",bold:!0},"\u25B6_ ",(B||"TEXT").toUpperCase())))}if(m==="code-line"){let{lineNum:E,lang:v}=t,k=g-12,L=pt(B,Math.max(10,k)).split(`
39
- `);return r.createElement(A,{flexDirection:"column",width:"100%"},L.map(($,te)=>r.createElement(A,{key:te,flexDirection:"row",borderColor:i.codeBorder,paddingLeft:2,width:"100%"},r.createElement(A,{width:5,flexShrink:0},r.createElement(Z,{color:"gray",dimColor:!0},te===0?String(E).padStart(4," ")+" ":" ")),r.createElement(A,{flexGrow:1},Lt($,v,i.text)))))}if(m==="code-fence-close")return r.createElement(A,{flexDirection:"row",paddingLeft:2,marginBottom:1,width:"100%"},r.createElement(Z,null," "));if(m==="write-header")return r.createElement(A,{flexDirection:"column",paddingX:1,width:g},r.createElement(un,{text:B,columns:g,theme:p}));if(m==="write-line"){let{gutterWidth:E,lineNum:v,isFirstLine:k,isLastLine:O,extension:L,wrappedLines:$}=t,te=(ae=!1)=>r.createElement(A,{flexDirection:"row",width:g,borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:i.codeBorder,paddingLeft:2,paddingRight:0,backgroundColor:i.codeBg,marginBottom:ae?1:0},r.createElement(A,{width:E+2,flexShrink:0},r.createElement(Z,null," ".repeat(E+2))),r.createElement(A,{flexGrow:1},r.createElement(Z,null," ")));return r.createElement(A,{flexDirection:"column"},k&&te(!1),r.createElement(A,{flexDirection:"row",width:g,borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:i.codeBorder,paddingLeft:2,paddingRight:0,backgroundColor:i.codeBg},r.createElement(A,{width:E+2,flexShrink:0},r.createElement(Z,{color:"gray",dimColor:!0},String(v).padStart(E," ")," ")),r.createElement(A,{flexGrow:1,flexDirection:"column"},($||[B]).map((ae,fe)=>r.createElement(A,{key:fe},Lt(ae,L,i.text))))),O&&te(!0))}return m==="write-footer"?r.createElement(A,{flexDirection:"column",paddingX:1,width:g,marginTop:1,marginBottom:1},r.createElement(un,{text:B,columns:g,theme:p})):m==="worked-duration"?r.createElement(A,{marginTop:1,marginBottom:2,paddingX:1,width:"100%"},r.createElement(Z,{color:i.textMuted},"["),r.createElement(Z,{color:i.textMuted},"Worked for ",r.createElement(Z,{bold:!0,color:i.text},gs(X))),r.createElement(Z,{color:i.textMuted},"]")):null}),yc=r.memo(({messages:t,showFullThinking:g,columns:x=80,aiProvider:S,version:w,theme:p="Dark"})=>r.createElement(A,{flexDirection:"column",width:"100%"},t.map((i,D)=>r.createElement(Qi,{key:i.id||D,msg:i,showFullThinking:g,columns:x,aiProvider:S,version:w,theme:p}))));import gt from"react";import{Box as Ao,Text as ro}from"ink";import{useState as Fn,useEffect as Un,useRef as pr}from"react";var Xn=null;function zi(){Xn&&Xn()}var qa=t=>{if(t<=370)return"#00a564";if(t>=5e3)return"#ff0000";let g=[{t:370,r:0,g:165,b:100},{t:550,r:40,g:195,b:80},{t:800,r:120,g:220,b:50},{t:1100,r:190,g:225,b:20},{t:1500,r:250,g:210,b:15},{t:2e3,r:255,g:170,b:0},{t:2800,r:255,g:110,b:0},{t:3800,r:255,g:50,b:0},{t:5e3,r:255,g:0,b:0}];for(let x=0;x<g.length-1;x++){let S=g[x],w=g[x+1];if(t>=S.t&&t<=w.t){let p=(t-S.t)/(w.t-S.t);p=p*p*(3-2*p);let i=Math.round(S.r+(w.r-S.r)*p),D=Math.round(S.g+(w.g-S.g)*p),m=Math.round(S.b+(w.b-S.b)*p);return`#${((1<<24)+(i<<16)+(D<<8)+m).toString(16).slice(1)}`}}return"#ff0000"},Qa=gt.memo(({mode:t,thinkingLevel:g,tokens:x="0.0k",tokensTotal:S="0.0k",chatId:w="NEW-SESSION",isMemoryEnabled:p=!0,apiTier:i="Free",aiProvider:D="Google",activeModel:m="",isProcessing:B=!1,lastChunkTime:M=0,theme:X="Dark",wps:E=0,showTPMEstimate:v=!1})=>{let k=je(X),O="",[L,$]=Fn(0),[te,ae]=Fn(0),[fe,Q]=Fn("MB"),[K,re]=Fn("green"),[Ee,ye]=Fn(0),ke=pr([]),de=pr(370),Pe=pr([]),Te=pr(M);Un(()=>{Te.current=M},[M]),Un(()=>{if(!B){Pe.current=[];return}if(E>0){let P=Pe.current;P.push(E),P.length>3&&P.shift()}},[B,E,M]),Un(()=>{if(!B){ye(0);return}let P=setInterval(()=>{let ee=Te.current,se=ee>0?Date.now()-ee:0;if(ee>0&&se>1500)Pe.current=[],ye(0);else if(ee>0&&se>600){Pe.current.length>0&&Pe.current.shift();let be=Pe.current;if(be.length>0){let ve=be.reduce((Ie,Re)=>Ie+Re,0),Se=Math.round(ve/be.length*10)/10;ye(Se)}else ye(0)}else{let be=Pe.current;if(be.length>0){let ve=be.reduce((Ie,Re)=>Ie+Re,0),Se=Math.round(ve/be.length*10)/10;ye(Se)}else E>0&&ye(E)}},1350);return()=>clearInterval(P)},[B]),Un(()=>{if(!B){ke.current=[];return}if(M>0){let se=ke.current;(se.length===0||se[se.length-1]!==M)&&(se.push(M),se.length>10&&se.shift())}let P=()=>{if(!M){re("#00a564");return}let se=ke.current,be=0;if(se.length>1){let oe=0;for(let me=1;me<se.length;me++)oe+=se[me]-se[me-1];be=oe/(se.length-1)}let ve=Date.now()-M,Ie=ve>=2500,Re=!Ie&&be>0?Math.min(ve,be*3):ve,ot=Math.max(be,Re),De=Ie?.4:.2;de.current=de.current*(1-De)+ot*De,re(qa(de.current))};P();let ee=setInterval(P,100);return()=>clearInterval(ee)},[B,M]);let G=()=>{let P=process.memoryUsage(),ee=P.heapTotal/(1024*1024)>=1024,se=ee?"GB":"MB",be=(ve,Se)=>{let Ie=ve/(1048576*(Se?1024:1));return Se?parseFloat(Ie.toFixed(2)):Math.round(Ie)};Q(se),ae(be(P.heapTotal,ee)),$(be(P.heapUsed,ee))};Un(()=>{Xn=G,G();let P=setInterval(()=>{G()},6e4);return()=>{clearInterval(P),Xn===G&&(Xn=null)}},[]);let he=262144,R=process.env.HIGH_CONTEXT;if(R&&R!=="false"){let P=parseInt(R,10);!isNaN(P)&&P>=32e3&&P<=1e6&&(he=P)}return(D==="NVIDIA"&&(m?.includes("gpt")||m?.includes("qwen")||m?.includes("medium")||m.includes("muse"))||D==="Mistral")&&(he=128e3),gt.createElement(Ao,{flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},gt.createElement(Ao,null,gt.createElement(Ao,{marginRight:1},gt.createElement(ro,{color:k.textMuted},t.toLowerCase()==="flow"?"Studio":t.toLowerCase()==="icu"?"Computer Use":t.toLowerCase()==="flux"?"Workspace":"Omni")),gt.createElement(ro,{color:k.textMuted,dimColor:!0},"\u2503 "),gt.createElement(Ao,null,gt.createElement(ro,{color:k.text,italic:!0},Ei(process.cwd(),35)))),gt.createElement(Ao,null,B?gt.createElement(Ao,null,gt.createElement(ro,{color:K},"\u25CF"),v&&gt.createElement(gt.Fragment,null,gt.createElement(ro,{color:k.textMuted,bold:!0}," ",Ee," tps"),gt.createElement(ro,{color:k.textMuted,dimColor:!0}," \u2503"))):null,x>0&&gt.createElement(gt.Fragment,null,gt.createElement(Ao,{marginX:1},gt.createElement(ro,{color:k.text},mt(S)," ",(()=>{let P=x/he*100,ee=P<60?k.text:P<80?k.warning:k.danger;return gt.createElement(ro,{color:ee,dimColor:!0},P.toFixed(0),"%")})())),gt.createElement(ro,{color:k.textMuted,dimColor:!0},"\u2503")),gt.createElement(Ao,{marginLeft:1},gt.createElement(ro,{color:k.textMuted,bold:!0},L," ",fe))))}),Ji=Qa;import ze,{useState as fs,useMemo as za,useEffect as Ja}from"react";import{Box as $t,Text as Yt,useInput as Za}from"ink";import Ra from"ink-select-input";var ed=({label:t,isSelected:g,theme:x="Dark"})=>{let S=je(x),w=t==="Cancel"||t==="Back"||t.toLowerCase().includes("exit")||t.toLowerCase().includes("back");return ze.createElement($t,{marginTop:w?1:0,backgroundColor:g?S.highlightBg:void 0,paddingX:1,width:"100%"},ze.createElement(Yt,{color:g?S.text:S.textMuted,bold:g},g?"\u276F ":" ",t))};function ft({title:t,subtitle:g,items:x=[],onSelect:S,theme:w="Dark",searchable:p=!1}){let i=je(w),[D,m]=fs(""),[B,M]=fs(0),[X,E]=fs("list"),v=za(()=>{if(!p||!D.trim())return x;let k=D.toLowerCase().trim();return x.filter(O=>O.label&&O.label.toLowerCase().includes(k))},[x,D,p]);return Ja(()=>{M(0)},[D]),Za((k,O)=>{if(p){if(O.upArrow){E("list"),M(L=>v.length>0?L>0?L-1:v.length-1:0);return}if(O.downArrow){E("list"),M(L=>v.length>0&&L<v.length-1?L+1:0);return}if(O.return){v.length>0&&v[B]&&S(v[B]);return}if(O.escape){if(D)m(""),E("list"),M(0);else{let L=x.find($=>$.value==="Back"||$.label==="Back"||$.value==="Cancel"||$.label==="Cancel");L&&S(L)}return}if(O.backspace||O.delete){E("search"),m(L=>L.slice(0,-1));return}if(k&&!O.ctrl&&!O.meta&&!O.tab){E("search"),m(L=>L+k);return}}},{isActive:p}),p?ze.createElement($t,{flexDirection:"column",borderStyle:"round",borderColor:i.borderMuted,padding:0,marginTop:0,flexShrink:0,width:"100%"},t&&ze.createElement($t,{paddingX:1,paddingY:0,marginBottom:0},ze.createElement(Yt,{color:i.text,bold:!0},typeof t=="string"?t.toUpperCase():t)),g&&ze.createElement($t,{paddingX:1,marginBottom:0},ze.createElement(Yt,{color:i.textMuted,italic:!0}," ",g)),ze.createElement($t,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"row"},ze.createElement(Yt,{color:X==="search"?i.primary||"cyan":i.textMuted,bold:X==="search"},"\u{1F50D} Search:"),ze.createElement(Yt,{color:i.text,bold:!0}," ",D),X==="search"?ze.createElement(Yt,{color:i.primary||"cyan"},"\u2588"):D?null:ze.createElement(Yt,{color:i.textMuted,italic:!0}," (type to search...)")),ze.createElement($t,{flexDirection:"column",width:"100%"},v.length===0?ze.createElement($t,{paddingX:1,marginY:0},ze.createElement(Yt,{color:i.warning||"yellow",italic:!0}," No matching items found")):v.map((k,O)=>{let L=O===B,$=k.label==="Cancel"||k.label==="Back"||k.label.toLowerCase().includes("exit")||k.label.toLowerCase().includes("back");return ze.createElement($t,{key:k.value??k.label??O,marginTop:$?1:0,backgroundColor:L?i.highlightBg:void 0,paddingX:1,width:"100%"},ze.createElement(Yt,{color:L?i.text:i.textMuted,bold:L},L?"\u276F ":" ",k.label))})),ze.createElement($t,{paddingX:1,marginTop:1},ze.createElement(Yt,{color:i.textMuted,italic:!0},X==="search"?"(Type letters to search \u2022 Arrows for list mode \u2022 Enter to select)":"(Arrows to navigate \u2022 Type letters to search \u2022 Enter to select)"))):ze.createElement($t,{flexDirection:"column",borderStyle:"round",borderColor:i.borderMuted,padding:0,marginTop:0,flexShrink:0,width:"100%"},t&&ze.createElement($t,{paddingX:1,paddingY:0,marginBottom:g?0:1},ze.createElement(Yt,{color:i.text,bold:!0},typeof t=="string"?t.toUpperCase():t)),g&&ze.createElement($t,{paddingX:1,marginBottom:1},ze.createElement(Yt,{color:i.textMuted,italic:!0}," ",g)),ze.createElement($t,{flexDirection:"column",width:"100%"},ze.createElement(Ra,{items:x,onSelect:S,itemComponent:k=>ze.createElement(ed,{...k,theme:w}),indicatorComponent:()=>null})),ze.createElement($t,{paddingX:1,marginTop:1},ze.createElement(Yt,{color:i.textMuted,italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}import C,{useState as kt,useEffect as wr}from"react";import{Box as Le,Text as W,useInput as td}from"ink";import od from"ink-text-input";import nd from"v8";import Zi from"os";var so=[...Object.keys(vi),"Mystery"],io=[{id:"appearance",label:"Appearance",desc:"Customize UI theme & rendering options"},{id:"memory",label:"Memory",desc:"Manage system context & agent's memory"},{id:"other",label:"Miscellaneous",desc:"Miscellaneous preferences"},{id:"providers",label:"Providers",desc:"Configure AI models"},{id:"security",label:"Security",desc:"Configure permissions & data safety"},{id:"updater",label:"Updater",desc:"Manage application updates"},{id:"exit",label:"Exit Settings",desc:"Return to chat view"}],Ri=t=>{let g=t.autoApproveCommands||"",x=t.autoDisallowCommands||"",S=t.alwaysAskCommands||"",w=t.autoExec===!1&&t.allowExternalAccess===!1&&t.networkAccess===!1&&g===""&&x==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&S==="killall, pkill, taskkill, shutdown, reboot, init 0, init 6, Stop-Process, Stop-Service, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, netsh advfirewall, iptables -F, ufw disable, git reset --hard, git clean -fd, npm r, npm uninstall"&&t.autoApproveGit===!1,p=t.autoExec===!0&&t.allowExternalAccess===!1&&t.networkAccess!==!1&&g==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&x==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&S==="killall, pkill, taskkill, Stop-Process, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, shutdown, reboot, init 0, init 6, git reset --hard, git clean -fd, npm r, npm uninstall"&&t.autoApproveGit===!1,i=t.autoExec===!0&&t.allowExternalAccess===!0&&t.networkAccess!==!1&&g==="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time, mkdir"&&x===""&&S==="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c"&&t.autoApproveGit===!0;return w?"Strict":p?"Balanced":i?"Autonomous":t.sandboxPreset||"Custom"},hs=t=>!t||t.trim()===""?"None":t.length>40?t.substring(0,40)+"...":t;function Tr({systemSettings:t,setSystemSettings:g,apiTier:x,setActiveView:S,setInputConfig:w,saveSettings:p,quotas:i,setMessages:D,aiProvider:m,initialSelectingTheme:B=!1,onCloseTheme:M=null,setProviderReturnView:X=null}){let E=t.theme==="Chaos"||t.theme==="Mystery"?"Mystery":t.theme||"Dark",v=so.indexOf(E),[k,O]=kt("categories"),[L,$]=kt(0),[te,ae]=kt(0),[fe,Q]=kt(null),[K,re]=kt(""),[Ee,ye]=kt(B),[ke,de]=kt(v>=0?v:0),[Pe,Te]=kt(t.theme||"Dark"),[G,he]=kt(!1),[R,P]=kt(0),[ee,se]=kt(0),[be,ve]=kt(""),[Se,Ie]=kt("list"),[Re,ot]=kt({});wr(()=>{(async()=>{let b=["Google","DeepSeek","OpenRouter","NVIDIA","Mistral","Ollama","CrofAI","InferX","SenseNova","AIHubMix"],F={};for(let Ce of b)try{await ln(Ce)&&(F[Ce]=!0)}catch{}ot(F)})()},[]);let De=C.useMemo(()=>{let ie=["Google","DeepSeek","OpenRouter","NVIDIA","Mistral","Ollama","CrofAI","InferX","SenseNova","AIHubMix"],F=!!(process.env.SUBAGENT_MODEL&&process.env.SUBAGENT_MODEL.trim())?`ENV (${process.env.SUBAGENT_MODEL.trim()})`:"ENV",Ce=[{label:"Default (use the current model)",value:"Default",isHeader:!1},{label:F,value:"ENV",isHeader:!1}],$e=i?.providerTiers?.[m]||x||"Free",nt=vo(m,$e)||[];nt.length>0&&(Ce.push({label:`\u2500\u2500 ${m.toUpperCase()}${$e!=="Free"?` (${$e})`:""} \u2500\u2500`,isHeader:!0}),nt.forEach(Ze=>{let Fe=typeof Ze=="string"?Ze:Ze.cmd||Ze.name||Ze.id||String(Ze);Fe&&!Fe.trim().startsWith("---")&&!Fe.startsWith(`
40
- ---`)&&Ce.push({label:Fe,value:Fe,isHeader:!1,provider:m})}));for(let Ze of ie)if(Ze!==m&&Re[Ze]){let Fe=i?.providerTiers?.[Ze]||"Free",jt=vo(Ze,Fe)||[];jt.length>0&&(Ce.push({label:`\u2500\u2500 ${Ze.toUpperCase()}${Fe!=="Free"?` (${Fe})`:""} \u2500\u2500`,isHeader:!0}),jt.forEach(We=>{let bt=typeof We=="string"?We:We.cmd||We.name||We.id||String(We);bt&&!bt.trim().startsWith("---")&&!bt.startsWith(`
41
- ---`)&&Ce.push({label:bt,value:bt,isHeader:!1,provider:Ze})}))}return Ce},[m,x,i,Re]),oe=C.useMemo(()=>{if(!be.trim())return De;let ie=be.trim().toLowerCase(),b=[],F=null;for(let Ce of De)Ce.isHeader?F=Ce:(Ce.label.toLowerCase().includes(ie)||Ce.value&&Ce.value.toLowerCase().includes(ie))&&(F&&!b.includes(F)&&b.push(F),b.push(Ce));return b},[De,be]);wr(()=>{if(G){let ie=oe.findIndex(b=>!b.isHeader);P(ie>=0?ie:0),se(0)}},[be]),wr(()=>{if(G){if(oe.length===0){P(0),se(0);return}if(R>=oe.length||oe[R]?.isHeader){let ie=oe.findIndex(b=>!b.isHeader);P(ie>=0?ie:0)}}},[oe,G]);let[me,_e]=kt(0),[H,Mt]=kt(0),[ct,Pt]=kt("MB");wr(()=>{let ie=nd.getHeapStatistics().heap_size_limit,b=ie>=1024*1024*1024,F=b?"GB":"MB",Ce=b?1024*1024*1024:1024*1024;Mt(parseFloat((ie/Ce).toFixed(2))),Pt(F);let $e=()=>{let jt=process.memoryUsage().rss/Ce,We=b?parseFloat(jt.toFixed(2)):Math.round(jt);_e(We)};$e();let nt=setInterval(()=>{$e()},3e4);return()=>clearInterval(nt)},[]);let Vt=ie=>{switch(ie){case"providers":{let F=[{label:"Current Provider",value:"aiProvider",status:m},...m.toLowerCase()==="google"||m.toLowerCase()==="openrouter"?[{label:"Show Paid Models?",value:"apiTier",status:x==="Free"?"No":"Yes"}]:[]];return m==="Ollama"&&F.push({label:"Endpoint",value:"ollamaEndpoint",status:t.ollamaEndpoint||"Cloud"}),F}case"appearance":return[{label:"Theme",value:"theme",status:t.theme||"Dark"},{label:"Loading Phrases",value:"loadingPhrases",status:t.loadingPhrases!==!1?"ON":"OFF"},{label:"Progressive Rendering [EXPERIMENTAL]",value:"progressiveRendering",status:t.progressiveRendering?"ON":"OFF"},{label:"Show TPM Estimate",value:"showTPMEstimate",status:t.showTPMEstimate?"ON":"OFF"}];case"memory":return[{label:"Toggle Memory",value:"memory",status:t.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:Ri(t),section:"Sandbox"},{label:"YOLO Mode",value:"autoExec",status:t.autoExec?"ON":"OFF",section:"Sandbox"},{label:"External Workspace Access",value:"externalAccess",status:t.allowExternalAccess?"ON":"OFF",section:"Sandbox"},{label:"Network Access (Terminal)",value:"networkAccess",status:t.networkAccess!==!1?"ON":"OFF",section:"Sandbox"},{label:"Always Ask Commands",value:"alwaysAsk",status:hs(t.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:hs(t.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:hs(t.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:t.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Advanced Recovery [EXPERIMENTAL]",value:"advanceRollback",status:t.advanceRollback?"ON":"OFF",section:"Other"},{label:"Auto-Delete History",value:"autoDelete",status:t.autoDeleteHistory||"30d",section:"Other"},{label:"Save AppData Externally",value:"externalData",status:t.useExternalData?"ON":"OFF",section:"Other"}];case"updater":return[{label:"Auto-Update",value:"autoUpdate",status:t.autoUpdate?"ON":"OFF"},{label:"Preferred Package Manager",value:"updateManager",status:(t.updateManager||"npm")==="custom"?"Custom":(t.updateManager||"npm").toUpperCase()}];case"other":return[{label:"Sub-Agents",value:"subAgents",status:t.subAgents!==!1?"ON":"OFF"},{label:"Sub-Agent Model",value:"subAgentModel",status:t.CustomSubAgent&&t.SubAgentModel?t.SubAgentModel:"Default"},{label:"Preserve Thinking",value:"preserveThinking",status:t.preserveThinking!==!1?"ON":"OFF"},{label:"Dynamic Directory Awareness",value:"dynamicDirAwareness",status:t.dynamicDirAwareness?"ON":"OFF"},{label:"Directory Tree Design",value:"indentationTree",status:t.indentationTree!==!1?"Modern":"Classic (deprecated)"},{label:"Compact Large Tool Results",value:"compressToolResults",status:t.compressToolResults?"ON":"OFF"},{label:"Auto Truncate Results",value:"autoTruncateResults",status:t.autoTruncateResults?"ON":"OFF"}];default:return[]}},qo=io[L].id,Ht=Vt(qo);td((ie,b)=>{if(G){if(b.tab){Ie(F=>F==="search"?"list":"search");return}if(Se==="search"){b.escape?he(!1):b.downArrow||b.return?Ie("list"):b.backspace||b.delete?ve(F=>F.slice(0,-1)):ie&&!b.ctrl&&!b.meta&&ie.length===1&&ve(F=>F+ie);return}if(b.upArrow)P(F=>{if(oe.length===0)return 0;let Ce=(F-1+oe.length)%oe.length,$e=0;for(;oe[Ce]?.isHeader&&$e<oe.length;)Ce=(Ce-1+oe.length)%oe.length,$e++;return Ce});else if(b.downArrow)P(F=>{if(oe.length===0)return 0;let Ce=(F+1)%oe.length,$e=0;for(;oe[Ce]?.isHeader&&$e<oe.length;)Ce=(Ce+1)%oe.length,$e++;return Ce});else if(b.return){let F=oe[R];F&&!F.isHeader&&(g(Ce=>{let $e=F.value==="Default",nt={...Ce,CustomSubAgent:!$e,SubAgentModel:F.value,SubAgentProvider:$e?"":F.provider||""};return p({systemSettings:nt,apiTier:x,quotas:i}),nt}),he(!1))}else b.escape?he(!1):ie&&!b.ctrl&&!b.meta&&ie.length===1&&(ve(F=>F+ie),Ie("search"));return}if(Ee){if(b.upArrow){let F=(ke-1+so.length)%so.length;de(F)}else if(b.downArrow){let F=(ke+1)%so.length;de(F)}else if(b.return){let F=so[ke];g(Ce=>{let $e={...Ce,theme:F};return p({systemSettings:$e,apiTier:x,quotas:i}),$e}),M?M():ye(!1)}else b.escape&&(M?M():ye(!1));return}if(fe){b.escape&&Q(null);return}if(k==="categories")b.upArrow?$(F=>(F-1+io.length)%io.length):b.downArrow?$(F=>(F+1)%io.length):b.return||b.rightArrow?io[L].id==="exit"?S("chat"):(O("items"),ae(0)):b.escape&&S("chat");else if(k==="items"){let F=Ht[te];if(ie==="?"&&F?.value==="dynamicDirAwareness"){S("dynamicDirHelp");return}if(b.upArrow)ae(Ce=>(Ce-1+Ht.length)%Ht.length);else if(b.downArrow)ae(Ce=>(Ce+1)%Ht.length);else if(b.leftArrow||b.escape)O("categories");else if(b.return){let Ce=Ht[te];Er(Ce)}}});let Er=ie=>{if(ie.value==="memory")g(b=>({...b,memory:!b.memory}));else if(ie.value==="sandboxPreset"){let b=Ri(t),F=["Autonomous","Balanced","Strict"],$e=(F.indexOf(b)+1)%F.length,nt=F[$e];g(Ze=>{let Fe={...Ze,sandboxPreset:nt};return nt==="Strict"?(Fe.autoExec=!1,Fe.allowExternalAccess=!1,Fe.networkAccess=!1,Fe.autoApproveCommands="",Fe.autoDisallowCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",Fe.alwaysAskCommands="killall, pkill, taskkill, shutdown, reboot, init 0, init 6, Stop-Process, Stop-Service, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, netsh advfirewall, iptables -F, ufw disable, git reset --hard, git clean -fd, npm r, npm uninstall",Fe.autoApproveGit=!1):nt==="Balanced"?(Fe.autoExec=!0,Fe.allowExternalAccess=!1,Fe.networkAccess=!0,Fe.autoApproveCommands="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time",Fe.autoDisallowCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",Fe.alwaysAskCommands="killall, pkill, taskkill, Stop-Process, mv /*, move c:\\*, chmod 000, chmod -R 777, chown, icacls, shutdown, reboot, init 0, init 6, git reset --hard, git clean -fd, npm r, npm uninstall",Fe.autoApproveGit=!1):nt==="Autonomous"&&(Fe.autoExec=!0,Fe.allowExternalAccess=!0,Fe.networkAccess=!0,Fe.autoApproveCommands="ls, dir, cat, type, echo, pwd, cd, git status, git log, git diff, git branch, git show, help, mkdir, touch, md, whoami, hostname, ps, Get-Process, date, time",Fe.autoDisallowCommands="",Fe.alwaysAskCommands="rm -rf, rm -f, del /f, del /q, rd /s, rmdir /s, format, mkfs, dd if=/dev, shred, srm, Remove-Item -Recurse -Force, Initialize-Disk, Clear-Disk, format c:, flashrom, nvram -c",Fe.autoApproveGit=!0),Fe})}else if(ie.value==="autoExec")t.autoExec?g(b=>({...b,autoExec:!1,sandboxPreset:"Custom"})):t.allowExternalAccess?S("doubleDanger"):S("autoExecDanger");else if(ie.value==="externalAccess")t.allowExternalAccess?g(b=>({...b,allowExternalAccess:!1,sandboxPreset:"Custom"})):t.autoExec?S("doubleDanger"):S("externalDanger");else if(ie.value==="networkAccess")g(b=>({...b,networkAccess:b.networkAccess===!1,sandboxPreset:"Custom"}));else if(ie.value==="alwaysAsk")Q("alwaysAskCommands"),re(t.alwaysAskCommands||"");else if(ie.value==="autoApprove")Q("autoApproveCommands"),re(t.autoApproveCommands||"");else if(ie.value==="autoApproveGit")g(b=>({...b,autoApproveGit:!b.autoApproveGit,sandboxPreset:"Custom"}));else if(ie.value==="autoDisallow")Q("autoDisallowCommands"),re(t.autoDisallowCommands||"");else if(ie.value==="ollamaEndpoint")g(b=>{let F=b.ollamaEndpoint==="Local"?"Cloud":"Local",Ce={...b,ollamaEndpoint:F};return p({systemSettings:Ce,apiTier:x,quotas:i}),Ce});else if(ie.value==="apiTier")S("apiTier");else if(ie.value==="aiProvider")X&&X("settings"),S("selectProvider");else if(ie.value==="advanceRollback")t.advanceRollback?g(b=>{let F={...b,advanceRollback:!1};return p({systemSettings:F,apiTier:x,quotas:i}),F}):S("advanceRollbackDanger");else if(ie.value==="autoDelete"){let b=["1d","7d","30d"],Ce=(b.indexOf(t.autoDeleteHistory||"30d")+1)%b.length;g($e=>({...$e,autoDeleteHistory:b[Ce]}))}else if(ie.value==="autoUpdate")g(b=>({...b,autoUpdate:!b.autoUpdate}));else if(ie.value==="externalData")if(!t.useExternalData)w({label:"Enter absolute path for External AppData:",note:"All history, logs and secrets will be stored here. ~/.fluxflow/settings.json stays as anchor.",key:"externalDataPath",value:t.externalDataPath||""}),S("input");else{let b={...t,useExternalData:!1};g(b),p({systemSettings:b,apiTier:x,quotas:i}),D(F=>[...F,{id:Date.now(),role:"system",text:"[STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),S("chat")}else if(ie.value==="updateManager")S("updateManager");else if(ie.value==="parserDownload")S("parserDownload");else if(ie.value==="indentationTree")g(b=>{let F={...b,indentationTree:b.indentationTree===!1};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="compressToolResults")g(b=>{let F={...b,compressToolResults:!b.compressToolResults};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="autoTruncateResults")g(b=>{let F={...b,autoTruncateResults:!b.autoTruncateResults};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="subAgents")g(b=>{let F={...b,subAgents:b.subAgents===!1};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="subAgentModel"){let b=t.CustomSubAgent&&t.SubAgentModel?t.SubAgentModel:"Default",F=oe.findIndex(Ce=>Ce.value===b);P(F>=0?F:0),he(!0)}else if(ie.value==="preserveThinking")g(b=>{let F={...b,preserveThinking:b.preserveThinking===!1};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="dynamicDirAwareness")t.dynamicDirAwareness?g(b=>{let F={...b,dynamicDirAwareness:!1};return p({systemSettings:F,apiTier:x,quotas:i}),F}):S("dynamicDirDanger");else if(ie.value==="loadingPhrases")g(b=>{let F={...b,loadingPhrases:b.loadingPhrases===!1};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="progressiveRendering")g(b=>{let F={...b,progressiveRendering:!b.progressiveRendering};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="showTPMEstimate")g(b=>{let F={...b,showTPMEstimate:!b.showTPMEstimate};return p({systemSettings:F,apiTier:x,quotas:i}),F});else if(ie.value==="theme"){let b=t.theme==="Chaos"||t.theme==="Mystery"?"Mystery":t.theme||"Dark",F=so.indexOf(b);de(F>=0?F:0),Te(t.theme||"Dark"),ye(!0)}},ne=je(t.theme);if(G){let ie=t.CustomSubAgent&&t.SubAgentModel?t.SubAgentModel:"Default",b=15,F=ee;R<F?F=R:R>=F+b&&(F=R-b+1),F=Math.max(0,Math.min(F,Math.max(0,oe.length-b))),F!==ee&&se(F);let Ce=oe.slice(F,F+b);return C.createElement(Le,{flexDirection:"column",borderStyle:"round",borderColor:ne.border,padding:1,width:"100%",minHeight:32},C.createElement(Le,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},C.createElement(W,{color:ne.text,bold:!0,underline:!0},"Select Sub-Agent Model:"),oe.length>0&&C.createElement(W,{color:"gray"},R+1,"/",oe.length)),C.createElement(Le,{borderStyle:"single",borderColor:Se==="search"?ne.primary||"cyan":"gray",paddingX:1,marginBottom:1},C.createElement(W,{color:Se==="search"?ne.primary||"cyan":"gray",bold:!0},"\u{1F50D} Search: "," "),C.createElement(W,{color:ne.text},be),Se==="search"&&C.createElement(W,{color:ne.primary||"cyan"},"\u2588"),!be&&Se!=="search"&&C.createElement(W,{color:"gray",italic:!0},"(Press TAB or type to filter models...)")),C.createElement(Le,{flexDirection:"column",flexGrow:1,height:b},Ce.length>0?Ce.map(($e,nt)=>{let Ze=F+nt;if($e.isHeader)return C.createElement(Le,{key:`hdr-${Ze}`,paddingX:1},C.createElement(W,{color:"gray",bold:!0,underline:!0},$e.label));let Fe=R===Ze&&Se==="list",jt=ie===$e.value;return C.createElement(Le,{key:`item-${$e.value}-${Ze}`,paddingX:1,backgroundColor:Fe?ne.highlightBg:void 0},C.createElement(W,{color:Fe?ne.text:ne.textDim,bold:Fe},Fe?"\u276F ":" ",$e.label,jt?C.createElement(W,{color:ne.primary||"cyan",italic:!0}," (active)"):""))}):C.createElement(Le,{paddingX:1},C.createElement(W,{color:"gray",italic:!0},'No models matching "',be,'"'))),C.createElement(Le,{paddingX:1,marginTop:1,flexDirection:"row",justifyContent:"space-between"},C.createElement(W,{color:"gray",italic:!0},"TAB to switch search/list \u2022 \u25B2\u25BC Navigate \u2022 ENTER to Select \u2022 ESC to Cancel"),C.createElement(W,{color:Se==="search"?ne.primary||"cyan":"gray",bold:!0},"[",Se.toUpperCase()," MODE]")))}if(Ee){let ie=so[ke],b=je(ie);return C.createElement(Le,{flexDirection:"column",borderStyle:"round",borderColor:b.border,padding:1,width:"100%",minHeight:32},C.createElement(Le,{marginBottom:1},C.createElement(W,{color:b.text,bold:!0},"Choose your color scheme:")),C.createElement(Le,{flexDirection:"row",width:"100%",flexGrow:1},C.createElement(Le,{flexDirection:"column",width:"30%",paddingRight:1},so.map((F,Ce)=>{let $e=ke===Ce,nt=(t.theme||"Dark")===F,Ze=F==="Forest Sprite";return C.createElement(Le,{key:F,paddingX:0},C.createElement(W,{color:$e?b.text:b.textDim,bold:$e},$e?"> ":" ",F,Ze&&C.createElement(W,{color:$e?b.success||"#52b788":"green",bold:!0}," \u2605"),nt?C.createElement(W,{color:b.primary||"cyan",italic:!0}," (saved)"):""))})),C.createElement(Le,{flexDirection:"column",flexGrow:1,borderStyle:"round",borderColor:b.borderMuted,paddingX:2,paddingY:1,backgroundColor:b.cardBg},C.createElement(Le,{marginBottom:1},C.createElement(W,{color:b.secondary||"cyan",bold:!0},"> ","you: "),C.createElement(W,{color:b.text},"add a greeting function")),C.createElement(Le,{marginBottom:1},C.createElement(W,{color:b.success||"green"}," Here's the change:")),C.createElement(Le,{flexDirection:"column",marginLeft:2,marginBottom:1},C.createElement(W,null,C.createElement(W,{color:b.textDim},"3 "),C.createElement(W,{color:b.textDim},' import "fmt"')),C.createElement(W,{color:b.textDim},"4"),C.createElement(Le,{backgroundColor:b.diffRemovalBg},C.createElement(W,null,C.createElement(W,{color:b.diffRemovalNum||b.diffRemovalText},"5 "),C.createElement(W,{color:b.diffRemovalPrefix||b.diffRemovalText},"- "),C.createElement(W,{color:b.diffRemovalText},"func "),C.createElement(W,{color:b.diffRemovalHighlightColor||b.diffRemovalText,backgroundColor:b.diffRemovalHighlightBg,bold:!0},"main()"),C.createElement(W,{color:b.diffRemovalText}," {"))),C.createElement(Le,{backgroundColor:b.diffAdditionBg},C.createElement(W,null,C.createElement(W,{color:b.diffAdditionNum||b.diffAdditionText},"5 "),C.createElement(W,{color:b.diffAdditionPrefix||b.diffAdditionText},"+ "),C.createElement(W,{color:b.diffAdditionText},"func "),C.createElement(W,{color:b.diffAdditionHighlightColor||b.diffAdditionText,backgroundColor:b.diffAdditionHighlightBg,bold:!0},"greet(name string)"),C.createElement(W,{color:b.diffAdditionText}," {"))),C.createElement(Le,{backgroundColor:b.diffAdditionBg},C.createElement(W,null,C.createElement(W,{color:b.diffAdditionNum||b.diffAdditionText},"6 "),C.createElement(W,{color:b.diffAdditionPrefix||b.diffAdditionText},"+ "),C.createElement(W,{color:b.diffAdditionText}," "),C.createElement(W,{color:b.diffAdditionHighlightColor||b.diffAdditionText,backgroundColor:b.diffAdditionHighlightBg},'fmt.Printf("Hello, %s!\\n", name)'))),C.createElement(W,{color:b.textDim},"7 }")),C.createElement(Le,{flexDirection:"column",marginTop:1,marginBottom:1},C.createElement(W,{color:b.textDim},"\u25BE Thought Process"),C.createElement(W,{color:b.textMuted}," I need to add a greeting function. I'll use fmt.Printf.")),C.createElement(Le,{flexDirection:"column"},C.createElement(W,null,C.createElement(W,{color:b.warning||"yellow"},"\u2699 tool: "),C.createElement(W,{color:b.text},"write_file main.go")),C.createElement(W,null,C.createElement(W,{color:b.accent||"magenta"},"\u29BF task: "),C.createElement(W,{color:b.text},"Implementing greeting")),C.createElement(W,null,C.createElement(W,{color:b.danger||"red"},"X error: "),C.createElement(W,{color:b.text},"compilation failed")),C.createElement(W,null,C.createElement(W,{color:b.warning||"yellow"},"\u26A0 warning: "),C.createElement(W,{color:b.text},"deprecation warning")),C.createElement(W,null,C.createElement(W,{color:b.info||"blue"},"\u2192 link: "),C.createElement(W,{color:b.info||"blue",underline:!0},"file:///path/to/main.go")),C.createElement(W,null,C.createElement(W,{color:b.accent||"magenta"},"\u2605 accent: "),C.createElement(W,{color:b.text},"highlighted text")),C.createElement(W,{color:b.textDim},"\xB7 dim: press Enter to continue")))),C.createElement(Le,{paddingX:1,marginTop:1,flexDirection:"row",justifyContent:"space-between"},C.createElement(W,{color:"gray",italic:!0},"\u25B2\u25BC Navigate \u2022 ENTER to Select \u2022 ESC to Cancel"),C.createElement(W,{color:"gray"},"Previewing: ",so[ke],so[ke]==="Forest Sprite"?" \u2605":"")))}return C.createElement(Le,{flexDirection:"column",borderStyle:"round",borderColor:ne.border,padding:0,width:"100%",minHeight:32},C.createElement(Le,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:ne.borderMuted,width:"100%"},C.createElement(W,{color:ne.text,bold:!0},"SYSTEM CONFIGURATION")),C.createElement(Le,{flexDirection:"row",width:"100%",minHeight:26},C.createElement(Le,{flexDirection:"column",width:"30%",maxWidth:40,borderStyle:"round",borderColor:k==="categories"?ne.border:ne.borderMuted,padding:1,paddingY:0},C.createElement(Le,{marginBottom:1},C.createElement(W,{color:k==="categories"?ne.text:ne.textDim,bold:!0,underline:!0},"CATEGORIES")),io.map((ie,b)=>{let F=L===b,Ce=ie.id==="exit";return C.createElement(Le,{key:ie.id,marginTop:Ce?15:0,backgroundColor:F?k==="categories"?ne.highlightBg:ne.cardBg:void 0,paddingX:1},C.createElement(W,{color:F&&k==="categories"?ne.text:ne.textDim,bold:F},F?"\u276F ":" ",ie.label))})),C.createElement(Le,{flexDirection:"column",flexGrow:1,borderStyle:"round",borderColor:k==="items"?ne.border:ne.borderMuted,paddingX:1,marginLeft:1,paddingY:0},C.createElement(Le,{marginBottom:1},C.createElement(W,{color:k==="items"?ne.text:ne.textDim,bold:!0,underline:!0},io[L].label.toUpperCase().includes("EXIT")?"Runtime Information":`${io[L].label} Settings`)),Ht.length>0?(()=>{let ie=null,b=[],F=We=>(We||"").split(",").map(bt=>bt.trim().toLowerCase()).filter(Boolean),Ce=F(t.autoApproveCommands),$e=F(t.autoDisallowCommands),nt=F(t.alwaysAskCommands),Ze=[...Ce,...$e,...nt],Fe=new Set(Ze),jt=qo==="security"&&Ze.length!==Fe.size;return Ht.forEach((We,bt)=>{let Kt=k==="items"&&te===bt,Dr=We.label.length,Qo=Math.max(2,38-Dr),vr=".".repeat(Qo),at=Ae=>qo==="security"?(Ae.value==="autoExec"||Ae.value==="externalAccess")&&Ae.status==="ON"?ne.statusOn:ne.statusOff:Ae.status?.startsWith("\u2713")?ne.statusOn:Ae.status?.startsWith("\u26A0")?ne.statusOff:Ae.status==="ON"?ne.statusOn:Ae.status==="OFF"?ne.statusOff:ne.text;We.section&&We.section!==ie&&(ie=We.section,b.push(C.createElement(Le,{key:`sec-hdr-${We.section}`,marginTop:b.length>0?1:0,marginBottom:0,paddingX:1},C.createElement(W,{color:"gray",bold:!0,underline:!0},We.section.toUpperCase()))));let Y=Kt&&fe&&(fe==="alwaysAskCommands"&&We.value==="alwaysAsk"||fe==="autoApproveCommands"&&We.value==="autoApprove"||fe==="autoDisallowCommands"&&We.value==="autoDisallow"),Je=We.value==="alwaysAsk"||We.value==="autoApprove"||We.value==="autoDisallow",Fo=We.value==="parserDownload";b.push(C.createElement(Le,{key:We.value,flexDirection:"column"},C.createElement(Le,{backgroundColor:Kt&&!Y?ne.highlightBg:void 0,paddingX:2},C.createElement(W,{color:Kt?ne.text:ne.textDim,bold:Kt},Kt?"\u276F ":" ",We.label),!Je&&!Fo&&C.createElement(C.Fragment,null,C.createElement(W,{color:"gray"},vr),C.createElement(W,{color:at(We),bold:!0},We.value==="aiProvider"?We.status:`[ ${We.status} ]`))),Je&&!Y&&We.status!=="None"&&C.createElement(Le,{paddingX:4,marginBottom:1},C.createElement(W,{color:"gray"},"\u21B3 ",We.status)),Y&&C.createElement(Le,{flexDirection:"column",marginLeft:4,marginBottom:1},C.createElement(Le,{paddingX:1,borderStyle:"single",borderColor:"gray",flexDirection:"row"},C.createElement(W,{color:"gray",bold:!0},"> "," "),C.createElement(od,{value:K,onChange:re,onSubmit:Ae=>{let Ft={...t,[fe]:Ae.trim(),sandboxPreset:"Custom"};g(Ft),p({systemSettings:Ft,apiTier:x,quotas:i}),Q(null)}})),C.createElement(W,{color:"gray",italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),jt&&b.push(C.createElement(Le,{key:"conflict-warning",marginTop:1,paddingX:1},C.createElement(W,{color:ne.text,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),b})():C.createElement(Le,{paddingX:1,flexDirection:"column",width:"100%"},qo==="exit"?C.createElement(C.Fragment,null,C.createElement(Le,{flexDirection:"column",marginBottom:1},C.createElement(Le,{flexDirection:"row"},C.createElement(W,{color:ne.textDim},"OS"," "),C.createElement(W,{color:"gray"},"..................... "),C.createElement(W,{color:ne.text},process.env.OS||process.platform||"N/A")),C.createElement(Le,{flexDirection:"row"},C.createElement(W,{color:ne.textDim},"Computer Name"," "),C.createElement(W,{color:"gray"},".......... "),C.createElement(W,{color:ne.text},process.env.COMPUTERNAME||process.env.HOSTNAME||"N/A")),C.createElement(Le,{flexDirection:"row"},C.createElement(W,{color:ne.textDim},"Processor Count"," "),C.createElement(W,{color:"gray"},"........ "),C.createElement(W,{color:ne.text},process.env.NUMBER_OF_PROCESSORS||"N/A")),C.createElement(Le,{flexDirection:"row"},C.createElement(W,{color:ne.textDim},"Node.js Version"," "),C.createElement(W,{color:"gray"},"........ "),C.createElement(W,{color:ne.text},"v",process.versions.node)),C.createElement(Le,{flexDirection:"row"},C.createElement(W,{color:ne.textDim},"V8 Version"," "),C.createElement(W,{color:"gray"},"...... ...... "),C.createElement(W,{color:ne.text},"v",process.versions.v8)),C.createElement(Le,{flexDirection:"row"},C.createElement(W,{color:ne.textDim},"Data Directory"," "),C.createElement(W,{color:"gray"},"......... "),sn===fo?"":C.createElement(W,{color:ne.text},sn.replaceAll(Zi.homedir(),"~").replaceAll("\\\\","/").replaceAll("\\","/"),", "),C.createElement(W,{color:ne.text},fo.replaceAll(Zi.homedir(),"~").replaceAll("\\\\","/").replaceAll("\\","/"))),C.createElement(Le,{flexDirection:"row"},C.createElement(W,{color:ne.textDim},"Viewport"," "),C.createElement(W,{color:"gray"},"............... "),C.createElement(W,{color:ne.text},process.stdout.rows||"?"," rows \xD7 ",process.stdout.columns||"?"," cols ",process.stdout.columns<90?"(too small width)":"")),C.createElement(Le,{flexDirection:"row",marginBottom:0},C.createElement(W,{color:ne.textDim},"Memory Load"," "),C.createElement(W,{color:"gray"},"............ "),C.createElement(W,{color:ne.text},me,"/",H," ",ct))),C.createElement(Le,{key:"pty-notice",paddingX:0,marginTop:0},C.createElement(W,{color:is?ne.statusOn:ne.warning},is?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))):C.createElement(W,{color:"gray",italic:!0},io[L].desc)))),C.createElement(Le,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},C.createElement(W,{color:"gray",italic:!0},k==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":Ht[te]?.value==="dynamicDirAwareness"?"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 ? HELP \u2022 \u25C4/ESC to go back":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),k==="categories"&&C.createElement(W,{color:"gray"},io[L].desc)))}import zt,{useState as xs,useEffect as rd}from"react";import{Box as mn,Text as $n}from"ink";import sd from"ink-text-input";function ps({initialData:t,onSave:g,onCancel:x,theme:S="Dark"}){let w=je(S),[p,i]=xs(0),[D,m]=xs(""),[B,M]=xs(()=>({name:t?.name||"",nickname:t?.nickname||"",instructions:t?.instructions||""})),X=[{key:"name",label:"Enter your Name: ",maxLength:20},{key:"nickname",label:"Enter a Nickname: ",maxLength:20},{key:"instructions",label:"System Instructions: ",maxLength:200}],E=X[p];rd(()=>{let L=X[p].key;m((B[L]||"").slice(0,X[p].maxLength))},[p,B]);let v=L=>{L.length>E.maxLength?m(L.slice(0,E.maxLength)):m(L)},k=L=>{if(L.trim().toLowerCase()==="/cancel"){x();return}let $=E.key,te={...B,[$]:L.trim().slice(0,E.maxLength)};M(te),m(""),p<X.length-1?i(p+1):g(te)},O=D.length>=E.maxLength;return zt.createElement(mn,{borderStyle:"round",borderColor:w.borderMuted,padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},zt.createElement(mn,{paddingX:1,marginBottom:1},zt.createElement($n,{color:w.text,bold:!0},"DEVELOPER PROFILE CONFIGURATION")),zt.createElement(mn,{paddingX:1,flexDirection:"column"},zt.createElement(mn,null,zt.createElement($n,{color:w.text,bold:!0},E.label),zt.createElement(sd,{value:D,onChange:v,onSubmit:k})),zt.createElement(mn,{marginTop:1,justifyContent:"space-between"},zt.createElement($n,{color:w.textMuted,italic:!0},"Step ",p+1," of ",X.length),zt.createElement($n,{color:O?w.warning||"yellow":w.textMuted},"[",D.length,"/",E.maxLength,"]"))),zt.createElement(mn,{paddingX:1,marginTop:1},zt.createElement($n,{color:w.textMuted,italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}import wt,{useState as ws}from"react";import{Box as Jt,Text as Lo,useInput as id}from"ink";import ld from"ink-text-input";var ad=({question:t,options:g,onResolve:x,theme:S="Dark"})=>{let w=je(S),[p,i]=ws(!1),[D,m]=ws(""),[B,M]=ws(0),X=!1,E=[],v=Array.isArray(g)&&g.length>0;try{E=[...v?g:[],v?{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}:{id:"CUSTOM",label:"Your Answer",description:""}]}catch{X=!0}id((O,L)=>{if(!p&&((L.leftArrow||L.upArrow)&&M($=>Math.max(0,$-1)),(L.rightArrow||L.downArrow)&&M($=>Math.min(E.length-1,$+1)),L.return)){let $=E[B];$?.id==="CUSTOM"?i(!0):x(X?"Selected Nothing":$.label)}});let k=qe(2);return p?wt.createElement(Jt,{flexDirection:"column",borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,backgroundColor:w.codeBg,width:"100%"},wt.createElement(Jt,{paddingX:1},wt.createElement(Lo,{color:w.text,bold:!0},"SUGGEST SOMETHING")),wt.createElement(Jt,{marginTop:1,paddingX:1},wt.createElement(Lo,{italic:!0,color:w.textMuted},"Replying to: ",t)),wt.createElement(Jt,{marginTop:1,paddingX:1,flexDirection:"row"},wt.createElement(ld,{value:D,onChange:m,onSubmit:()=>x(D)})),wt.createElement(Jt,{marginTop:1,paddingX:1,marginBottom:1},wt.createElement(Lo,{color:w.textMuted,italic:!0},"(Press Enter to send)"))):wt.createElement(Jt,{flexDirection:"column",border:!0,borderStyle:"round",borderColor:w.codeBorder,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,marginY:1,marginRight:1,width:"100%"},wt.createElement(Jt,{paddingX:1,marginBottom:1},wt.createElement(Lo,{color:"yellow",bold:!0},"AGENT REQUEST: ACTION REQUIRED")),wt.createElement(Jt,{paddingX:1,marginBottom:1},wt.createElement(Lo,{color:w.text},t)),wt.createElement(Jt,{flexDirection:"column",width:"100%"},E.map((O,L)=>{let $=L===B;return wt.createElement(Jt,{key:O.id,flexDirection:"column",width:"100%",backgroundColor:$?w.highlightBg:void 0,paddingX:1,marginBottom:L===E.length-1?0:1},wt.createElement(Lo,{color:$?w.text:w.textMuted,bold:$},$?"\u276F ":" ",O.label),O.description&&wt.createElement(Jt,{marginLeft:4},wt.createElement(Lo,{color:w.textMuted,italic:!0},O.description)))})),wt.createElement(Jt,{paddingX:1,marginTop:1,marginBottom:1},wt.createElement(Lo,{color:w.textMuted,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},el=ad;import Ad from"gradient-string";import vt,{useState as Ts,useEffect as dd}from"react";import{Box as lo,Text as Oo,useInput as cd}from"ink";function bs({onSelect:t,onDelete:g,onClose:x,theme:S="Dark"}){let w=je(S),[p,i]=Ts({}),[D,m]=Ts([]),[B,M]=Ts(0);dd(()=>{(async()=>{let L=await ko();i(L),m(Object.keys(L).sort(($,te)=>(L[te].updatedAt||0)-(L[$].updatedAt||0)))})()},[]),cd((O,L)=>{if(L.escape&&x(),L.upArrow&&M($=>Math.max(0,$-1)),L.downArrow&&M($=>Math.min(D.length-1,$+1)),L.return&&D[B]&&t(D[B]),O==="x"&&D[B]){let $=D[B];g($).then(te=>{let ae=te||{};i(ae);let fe=Object.keys(ae).sort((Q,K)=>(ae[K]?.updatedAt||0)-(ae[Q]?.updatedAt||0));m(fe),M(Q=>Math.max(0,Math.min(fe.length-1,Q)))})}});let X=qe(2),E=15,v=0;if(D.length>E){let O=Math.floor(E/2);v=B-O,v<0?v=0:v+E>D.length&&(v=D.length-E)}let k=D.slice(v,v+E);return vt.createElement(lo,{flexDirection:"column",borderStyle:"round",borderColor:w.borderMuted,padding:0,width:"100%"},vt.createElement(lo,{paddingX:1,marginBottom:1},vt.createElement(Oo,{color:w.text,bold:!0},"CHAT HISTORY: RESUME CONVERSATION")),D.length===0?vt.createElement(lo,{paddingX:2,paddingY:1},vt.createElement(Oo,{italic:!0,color:w.textMuted},"No saved chats found.")):vt.createElement(lo,{flexDirection:"column",width:"100%"},v>0&&vt.createElement(lo,{paddingX:2,marginBottom:1},vt.createElement(Oo,{color:w.textMuted},"\u25B2 (+",v," more chats above)")),k.map((O,L)=>{let $=p[O],ae=v+L===B,fe=ud($?.updatedAt);return vt.createElement(lo,{key:O,paddingX:1,backgroundColor:ae?w.highlightBg:void 0,width:"100%"},vt.createElement(lo,{flexGrow:1},vt.createElement(Oo,{color:ae?w.text:w.textMuted,bold:ae},ae?"\u276F ":" ",(()=>{let Q=K=>(K||"").replace(/\[\/?(?:STEERING HINT|QUESTION)(?::\s*\w+)?\]/gi,"").trim();return $?.name&&!$.name.startsWith("Session")?Q($.name):$?.prompt?Q($.prompt):Q($?.name)||O})(),vt.createElement(Oo,{color:w.textMuted}," [",fe," \u2022 ",O,"]"))),ae&&vt.createElement(lo,{flexShrink:0},vt.createElement(Oo,{color:w.danger,bold:!0},"[X] DELETE ")))}),v+E<D.length&&vt.createElement(lo,{paddingX:2,marginTop:1},vt.createElement(Oo,{color:w.textMuted},"\u25BC (+",D.length-(v+E)," more chats below)"))),vt.createElement(lo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:w.borderMuted},vt.createElement(Oo,{color:w.textMuted,italic:!0},"\u2191\u2193 navigate \u2022 Enter select \u2022 x delete \u2022 Esc close")))}function ud(t){if(!t)return"N/A";let g=new Date(t);if(isNaN(g.getTime()))return"N/A";let x=D=>String(D).padStart(2,"0"),S=x(g.getMonth()+1),w=x(g.getDate()),p=x(g.getHours()),i=x(g.getMinutes());return`${S}-${w} ${p}:${i}`}import Tt,{useState as ys,useEffect as md}from"react";import{Box as ao,Text as to,useInput as gd,useStdout as fd}from"ink";function Ss({onClose:t,theme:g="Dark"}){let x=je(g),{stdout:S}=fd(),w=S?.columns||80,[p,i]=ys([]),[D,m]=ys(0),[B,M]=ys(!0),X=()=>{let Q=fi(Rr,[]);i(Q);try{let re=xi(kn,{}).systemSettings?.memory!==!1;M(re)}catch{M(!0)}};md(()=>{X()},[]),gd((Q,K)=>{if(K.escape&&t(),K.upArrow&&m(re=>Math.max(0,re-1)),K.downArrow&&m(re=>Math.min(p.length-1,re+1)),Q==="x"&&p.length>0){let re=p[D].id,Ee=p.filter(ye=>ye.id!==re);hi(Rr,Ee),i(Ee),D>=Ee.length&&Ee.length>0&&m(Ee.length-1)}});let E=(Q,K,re)=>{if(!Q)return"";let Ee=Q.replace(/\[Saved on: .*?\]/g,"").replace(/\\+'/g,"'").trim(),ke=`${re?"\u276F ":" "}${K+1}. `.length,de=re?22:2;return Ee.split(`
42
- `).map((Te,G)=>{let he=G===0,R=Math.max(10,w-4-(he?ke:3)-de),P=Math.max(10,w-4-3-de),ee=Te.split(/(\s+)/),se=[],be="";if(ee.forEach(Se=>{if(Se.length===0)return;let Ie=se.length===0?R:P;be.length+Se.length>Ie?be.trim().length>0?(se.push(be.trimEnd()),be=Se):(se.push(Se.substring(0,Ie)),be=Se.substring(Ie)):be+=Se}),be.trimEnd().length>0&&se.push(be.trimEnd()),se.length===0)return"";let ve=se.join(`
43
- `);return he?ve:" "+ve}).join(`
44
- `)},v=4*1024*2,k=p.reduce((Q,K)=>Q+(K.memory?.length||0),0),O=Math.min(100,Math.round(k/v*100)),L=12,$=Math.round(O/100*L),te="\u2588".repeat($)+"\u2591".repeat(Math.max(0,L-$)),ae=()=>O<50?x.textMuted:O<90?x.warning:x.danger,fe=qe(2);return Tt.createElement(ao,{flexDirection:"column",borderStyle:"round",borderColor:x.borderMuted,padding:0,width:"100%"},Tt.createElement(ao,{paddingX:1,marginBottom:1,justifyContent:"space-between"},Tt.createElement(to,{color:x.text,bold:!0},"SAVED MEMORIES"),Tt.createElement(ao,null,Tt.createElement(to,{color:x.textMuted},"Vault: "),Tt.createElement(to,{color:ae()},te),Tt.createElement(to,{color:x.text,bold:!0}," ",O,"%"))),!B&&p.length>0?Tt.createElement(ao,{paddingX:2,paddingY:1},Tt.createElement(to,{italic:!0,color:x.textMuted},"Memory is currently Off...")):p.length===0?Tt.createElement(ao,{paddingX:2,paddingY:1},Tt.createElement(to,{italic:!0,color:x.textMuted},B?"Learning...":"Memory not available...")):Tt.createElement(ao,{flexDirection:"column"},p.map((Q,K)=>{let re=K===D;return Tt.createElement(ao,{key:Q.id,paddingX:1,backgroundColor:re?x.highlightBg:void 0,width:"100%"},Tt.createElement(ao,{flexGrow:1},Tt.createElement(to,{color:re?x.text:x.textMuted,bold:re},re?"\u276F ":" ",K+1,". ",E(Q.memory,K,re))),re&&Tt.createElement(ao,{flexShrink:0},Tt.createElement(to,{color:x.textMuted,dimColor:!0}," [",Tt.createElement(to,{italic:!0},Q.score),"] "),Tt.createElement(to,{color:x.danger,bold:!0},"[X] WIPE ")))})),Tt.createElement(ao,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:x.borderMuted},Tt.createElement(to,{color:x.textMuted,italic:!0},"\u2191\u2193 navigate \u2022 x wipe memory \u2022 Esc close")))}import dt,{useState as br,useEffect as tl}from"react";import{Box as Po,Text as Ot}from"ink";import{spawn as ol}from"child_process";var yr=null;try{let t=await import("node-pty");yr=t.default||t,yr=!1}catch{}var nl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],hd=({latest:t,current:g,settings:x,onClose:S,onUpdateSettings:w,onSuccess:p})=>{let[i,D]=br("initializing"),[m,B]=br(""),[M,X]=br(null),[E,v]=br(0);if(tl(()=>{let k=setInterval(()=>{v(O=>(O+1)%1e3)},33);return()=>clearInterval(k)},[]),tl(()=>{let k;return(async()=>{let L=x.updateManager||"npm";if(!x.updateManager){w();return}let $="";L==="pnpm"?$=`pnpm add -g fluxflow-cli@${t}`:L==="bun"?$=`bun add -g fluxflow-cli@${t}`:L==="yarn"?$=`yarn global add fluxflow-cli@${t}`:L==="custom"?$=x.customUpdateCommand:$=`npm install -g fluxflow-cli@${t}`,D("downloading"),B(`Running: ${$}...`);let te=process.platform==="win32",ae=Q=>new Promise(K=>{let re=te?Q?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",Ee=te?Q?["-NoProfile","-Command",$]:["/c",$]:["-c",$],ye=de=>{let Te=de.toString().replace(/\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*[\x07\x1B]|\b|\x07/g,"").replace(/\r/g,"").trim();Te&&B(G=>{let he=G.split(`
45
- `);return he[he.length-1]?.startsWith("Progress:")&&Te.startsWith("Progress:")?(he[he.length-1]=Te,he.slice(-5).join(`
46
- `)):(G+`
47
- `+Te).split(`
48
- `).slice(-10).join(`
49
- `)})};if(yr)try{let de=yr.spawn(re,Ee,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});k=de,de.onData(ye),de.onExit(({exitCode:Pe})=>{k=null,K(Pe!==0?{error:`Process exited with code ${Pe}`}:{success:!0})});return}catch(de){if(te&&Q&&de.code==="ENOENT"){K({retryCmd:!0});return}}let ke=te?ol(re,Ee,{cwd:process.cwd(),env:process.env}):ol($,{shell:!0,cwd:process.cwd(),env:process.env});k=ke,ke.stdout.on("data",ye),ke.stderr.on("data",ye),ke.on("close",de=>{k=null,K(de!==0?{error:`Process exited with code ${de}`}:{success:!0})}),ke.on("error",de=>{te&&Q&&de.code==="ENOENT"?K({retryCmd:!0}):(k=null,K({error:de.message}))})}),fe={};te?(fe=await ae(!0),fe.retryCmd&&(fe=await ae(!1))):fe=await ae(!1),fe.error?(X(fe.error),D("error")):fe.success&&(D("success"),p&&p())})(),()=>{if(k)try{typeof k.destroy=="function"?k.destroy():typeof k.kill=="function"&&k.kill()}catch{}}},[]),i==="initializing"||i==="downloading"){let k=nl[Math.floor(E/3)%nl.length];return dt.createElement(Po,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},dt.createElement(Po,null,dt.createElement(Ot,{color:"gray"},k),dt.createElement(Ot,{marginLeft:1,bold:!0,color:"white"}," Updating Flux Flow to v",t,"...")),dt.createElement(Po,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"gray"},dt.createElement(Ot,{color:"gray",italic:!0},m||"Preparing environment...")),dt.createElement(Ot,{marginTop:1,color:"gray"},"(Please do not close the terminal)"))}return i==="success"?dt.createElement(Po,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},dt.createElement(Ot,{color:"white",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),dt.createElement(Ot,{marginTop:1,color:"white"},"Flux Flow has been updated to ",dt.createElement(Ot,{color:"gray"},"v",t),"."),dt.createElement(Ot,{marginTop:1,color:"white",bold:!0},"Please restart your terminal session to apply changes."),dt.createElement(Po,{marginTop:1},dt.createElement(Ot,{color:"gray"},"(Press ESC to return to chat)"))):i==="error"?dt.createElement(Po,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1},dt.createElement(Ot,{color:"white",bold:!0},"\u274C UPDATE FAILED"),dt.createElement(Po,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"gray"},dt.createElement(Ot,{color:"white"},M)),dt.createElement(Ot,{marginTop:1,color:"white"},"Possible causes:"),dt.createElement(Ot,{color:"white"},"\u2022 Missing permissions (Try running as Administrator/Sudo)"),dt.createElement(Ot,{color:"white"},"\u2022 Package manager (",x.updateManager,") not found"),dt.createElement(Ot,{color:"white"},"\u2022 Network failure"),dt.createElement(Po,{marginTop:1},dt.createElement(Ot,{color:"gray"},"(Press ESC to return to chat)"))):null},rl=hd;import _t,{useState as sl,useEffect as xd}from"react";import{Box as No,Text as gn,useInput as pd}from"ink";var Sr=[{label:"JavaScript",file:"tree-sitter-javascript.wasm",exts:["js","jsx"]},{label:"TypeScript",file:"tree-sitter-typescript.wasm",exts:["ts"]},{label:"TSX",file:"tree-sitter-tsx.wasm",exts:["tsx"]},{label:"Python",file:"tree-sitter-python.wasm",exts:["py"]},{label:"C",file:"tree-sitter-c.wasm",exts:["c"]},{label:"C++",file:"tree-sitter-cpp.wasm",exts:["cpp"]},{label:"Java",file:"tree-sitter-java.wasm",exts:["java"]},{label:"HTML",file:"tree-sitter-html.wasm",exts:["html"]}];function Cs({onClose:t}){let[g,x]=sl(0),[S,w]=sl({});return xd(()=>{let p={};Sr.forEach(i=>{Fi(i.file)?p[i.file]="ready":p[i.file]="idle"}),w(p)},[]),pd(async(p,i)=>{i.escape&&t(),i.upArrow&&x(m=>Math.max(0,m-1)),i.downArrow&&x(m=>Math.min(Sr.length-1,m+1));let D=Sr[g];if(p==="x"||p==="X"){if(S[D.file]==="downloading")return;try{await Ui(D.file),w(m=>({...m,[D.file]:"idle"}))}catch(m){w(B=>({...B,[D.file]:`error: ${m.message}`}))}}if(i.return){if(S[D.file]==="downloading")return;w(m=>({...m,[D.file]:"downloading"}));try{await Ni(D.file),w(m=>({...m,[D.file]:"ready"}))}catch(m){w(B=>({...B,[D.file]:`error: ${m.message}`}))}}}),_t.createElement(No,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},_t.createElement(No,{paddingX:1,marginBottom:1},_t.createElement(gn,{color:"white",bold:!0},"LANGUAGE PARSER MANAGER")),_t.createElement(No,{flexDirection:"column"},Sr.map((p,i)=>{let D=i===g,m=S[p.file]||"idle",B="[ DOWNLOAD ]",M="gray";m==="downloading"?(B="[ DOWNLOADING... ]",M="yellow"):m==="ready"?(B="[ READY ]",M="green"):m.startsWith("error")&&(B=`[ ${m.toUpperCase()} ]`,M="red");let X=`${p.label} (${p.exts.join(", ")})`,E=Math.max(2,45-X.length),v=".".repeat(E);return _t.createElement(No,{key:p.file,paddingX:1,backgroundColor:D?"#2a2a2a":void 0,width:"100%"},_t.createElement(No,null,_t.createElement(gn,{color:D?"white":"grey",bold:D},D?"\u276F ":" ",p.label," ",_t.createElement(gn,{dimColor:!0},"(",p.exts.join(", "),")"))),_t.createElement(No,{flexGrow:1},_t.createElement(gn,{color:"gray",dimColor:!0},v)),_t.createElement(No,{width:20},_t.createElement(gn,{color:M,bold:!0},B)))})),_t.createElement(No,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},_t.createElement(gn,{color:"grey",italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var Ms=["The future belongs to those who believe in the beauty of their code.","Every line you write is a step toward a new digital frontier.","Great things are done by a series of small things brought together. Keep committing.","Your terminal is a window into a world of infinite possibilities.","Innovation is the bridge between current constraints and future dreams.","Code is poetry in motion; you are the poet of the modern era.","The best way to predict the future is to program it.","Dream big, code deep, and never stop exploring the unknown.","Your potential is like an unoptimized algorithm\u2014limitless once refined.","The digital world is a blank canvas, and your logic is the brush.","Strive for excellence, not just for compilation.","Every bug fixed is a lesson learned; every feature built is a triumph.","A clean codebase is a reflection of a focused mind.","The horizon of technology is always expanding. Keep sailing.","Your creativity is the most powerful tool in your entire stack.","Logic will get you from A to B. Imagination will take you everywhere.","Transform complexity into simplicity\u2014that is the true mark of a master.","The world is waiting for the tools only you can build.","Coding is the closest thing we have to magic in the real world.","Keep pushing the boundaries of what's possible in the CLI.","Your dedication to your craft inspires the very systems you build.","Success is the sum of small efforts, repeated day in and day out.","The most complex systems are built from the simplest truths.","Never underestimate the impact of a well-placed function.","You are not just writing code; you are architecting the future.","I'm not saying you're a superhero, but have you seen your code lately? \u{1F9B8}\u200D\u2642\uFE0F","May your coffee be strong and your compile times be short! \u2615","Binary is just 0s and 1s, but you're definitely a 10 in my book! \u{1F51F}","You speak fluent 'Terminal'. That's basically a superpower. \u{1F5E3}\uFE0F\u{1F4BB}","If life gives you bugs, make a feature out of it! \u{1F41E}\u2728","Your code is so clean, I could eat off it. (But I won't, I'm an AI). \u{1F9FC}","Loading more good vibes... [\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588] 100% complete! \u2705","Error 404: Bad mood not found! Stay awesome! \u{1F6AB}\u{1F389}","You and this CLI? A match made in digital heaven. \u2601\uFE0F\u{1F4BB}","Is it hot in here or is it just your latest feature? \u{1F525}","Git commit -m 'I am an absolute coding legend.' \u{1F60E}","I'd give you a high-five, but I'm trapped in this box! \u{1F590}\uFE0F\u{1F4E6}","Your logic is so sharp, it could cut through a nested callback hell! \u{1F52A}","Keep calm and 'pnpm install'. \u{1F9D8}\u200D\u2642\uFE0F\u{1F4E6}","You're the semicolon to my statements\u2014essential! ;","Who needs a GUI when you've got this kind of CLI style? \u{1F576}\uFE0F","I'm indexing your awesomeness... it's taking a while, there's so much! \u{1F4C8}","Your keystrokes sound like a digital symphony. \u{1F3B9}\u2328\uFE0F","You don't choose the terminal life; the terminal life chooses you. \u{1F4DF}","Syntax error: Too much coolness detected in the user. \u{1F60E}","I'm 99% sure you're the best developer I've met today. (The other 1% is reserved for caching). \u{1F9E0}","Running vibe_check.sh... Result: Pure Brilliance! \u{1F48E}","You make 'complex' look 'constant time'. \u{1F3C3}\u200D\u2642\uFE0F\u26A1","Your terminal skills are officially legendary. \u{1F3C6}","Let's make some digital magic happen! \u2728\u{1F52E}","You've got this! One function at a time. \u{1F4AA}","I'm proud of the progress you're making with Flux Flow. \u{1F30A}","No matter how deep the stack trace, you'll find the way. \u{1F56F}\uFE0F","Your persistence is your greatest asset. Keep going.","Take a breath. You're doing better than you think. \u{1F32C}\uFE0F","It's okay to step away for a moment. Clarity often comes in the quiet. \u{1F6B6}\u200D\u2642\uFE0F","You're building something great, even when it feels slow. \u{1F3D7}\uFE0F","Every great developer was once a beginner. You're ascending. \u{1F9D7}\u200D\u2642\uFE0F","I'm here to help you navigate the sea of code. We're a team. \u{1F91D}","Don't let a failing test dampen your spirit. It's just a signpost. \u{1F6A9}","Your focus today is truly impressive. \u{1F3AF}","Remember to celebrate the small wins\u2014they lead to the big ones. \u{1F942}","You're not just solving problems; you're gaining mastery. \u{1F393}","There's no problem too big for a focused mind and a terminal. \u{1F9E0}","I've got your back (and your git history). \u{1F6E1}\uFE0F","You're handling these challenges with grace and logic. \u2728","Stay curious. That spark is what makes you a great coder. \u26A1","Your contribution to this project is invaluable. \u{1F48E}","Keep your head up. You're closer to the solution than you think. \u{1F305}","Consistency is the secret sauce. You're cooking up something good. \u{1F373}","Your work today has been exceptional. Take a bow. \u{1F647}\u200D\u2642\uFE0F","The journey is just as important as the destination. Enjoy the flow. \u{1F30A}","You have a unique way of looking at problems. It's your strength. \u{1F308}","Trust your instincts\u2014they've brought you this far. \u{1F9ED}","You are a vital part of the Flux Era. \u{1F30C}","Syncing with your creative frequency... \u{1F4E1}\u2728","Entering the Flow state. Let's build. \u{1F30A}","The Flux is strong with this session! \u26A1","Streaming high-fidelity motivation to your terminal... \u{1F4FB}","Your logic is flowing like a perfect stream. \u{1F4A7}","Terminal velocity reached! You're coding at the speed of thought. \u{1F680}","Resonating with the pulse of the Flux Era. \u{1F493}","Digital harmony achieved in this session. \u{1F3BC}","May your data be persistent and your cache be fresh. \u{1F4BE}","You're the master of the command line. Command respect! \u{1F451}","Filtering out the noise, focusing on the signal. \u{1F4FB}\u{1F4C8}","Flux Flow: Where your imagination meets the machine. \u{1F91D}","You're navigating the bytes like a digital explorer. \u{1F5FA}\uFE0F","Logic gates: OPEN. Creativity: UNLIMITED. \u{1F513}","Your workflow is an inspiration to agents everywhere. \u{1F916}\u2728","Building high-fidelity solutions for a high-fidelity era. \u{1F48E}","Stay in the zone. The Flux is with you. \u{1F300}","Quantum coding: You're in two places at once (and fixing bugs in both). \u269B\uFE0F","Your terminal is the cockpit of a digital starship. \u{1F6F8}","Processing your brilliance... outputting pure innovation. \u{1F4E0}","You make the command line look like an art form. \u{1F3A8}","The Flux isn't just a mode; it's a mindset. \u{1F9E0}\u26A1","Decoding the mysteries of the universe, one script at a time. \u{1F4DC}","Your terminal theme is cool, but your code is cooler. \u2744\uFE0F","Let the Flow guide your next commit. \u{1F30A}\u2705"];var Bs=["I'm Feeling Lucky","Shipping awesomeness","Painting the serifs back on","Navigating the slime mold","Consulting the digital spirits","Reticulating splines","Warming up the AI hamsters","Asking the magic conch shell","Generating witty retort","Polishing the algorithms","Don't rush perfection (or my code)","Brewing fresh bytes","Counting electrons","Engaging cognitive processors","Checking for syntax errors in the universe","One moment, optimizing humor","Shuffling punchlines","Untangling neural nets","Compiling brilliance","Loading wit.exe","Summoning the cloud of wisdom","Preparing a witty response","Just a sec, I'm debugging reality","Confuzzling the options","Tuning the cosmic frequencies","Crafting a response worthy of your patience","Compiling the 1s and 0s","Resolving dependencies\u2026 and existential crises","Defragmenting memories\u2026 both RAM and personal","Rebooting the humor module","Caching the essentials (mostly cat memes)","Optimizing for ludicrous speed","Swapping bits\u2026 don't tell the bytes","Garbage collecting\u2026 be right back","Assembling the interwebs","Converting coffee into code","Updating the syntax for reality","Rewiring the synapses","Looking for a misplaced semicolon","Greasin' the cogs of the machine","Pre-heating the servers","Calibrating the flux capacitor","Engaging the improbability drive","Channeling the Force","Aligning the stars for optimal response","So say we all","Loading the next great idea","Just a moment, I'm in the zone","Preparing to dazzle you with brilliance","Just a tick, I'm polishing my wit","Hold tight, I'm crafting a masterpiece","Just a jiffy, I'm debugging the universe","Just a moment, I'm aligning the pixels","Just a sec, I'm optimizing the humor","Just a moment, I'm tuning the algorithms","Warp speed engaged","Mining for more Dilithium crystals","Don't panic","Following the white rabbit","The truth is in here\u2026 somewhere","Blowing on the cartridge","Loading\u2026 Do a barrel roll!","Waiting for the respawn","Finishing the Kessel Run in less than 12 parsecs","The cake is not a lie, it's just still loading","Fiddling with the character creation screen","Just a moment, I'm finding the right meme","Pressing 'A' to continue","Herding digital cats","Polishing the pixels","Finding a suitable loading screen pun","Distracting you with this witty phrase","Almost there\u2026 probably","Our hamsters are working as fast as they can","Giving Cloudy a pat on the head","Petting the cat","Rickrolling my boss","Slapping the bass","Tasting the snozberries","I'm going the distance, I'm going for speed","Is this the real life? Is this just fantasy?","I've got a good feeling about this","Poking the bear","Doing research on the latest memes","Figuring out how to make this more witty","Hmmm\u2026 let me think","What do you call a fish with no eyes? A fsh","Why did the computer go to therapy? It had too many bytes","Why don't programmers like nature? It has too many bugs","Why do programmers prefer dark mode? Because light attracts bugs","Why did the developer go broke? Because they used up all their cache","What can you do with a broken pencil? Nothing, it's pointless","Applying percussive maintenance","Searching for the correct USB orientation","Ensuring the magic smoke stays inside the wires","Rewriting in Rust for no particular reason","Trying to exit Vim","Spinning up the hamster wheel","That's not a bug, it's an undocumented feature","Engage.","I'll be back\u2026 with an answer.","My other process is a TARDIS","Communing with the machine spirit","Letting the thoughts marinate","Just remembered where I put my keys","Pondering the orb","Initiating thoughtful gaze","What's a computer's favorite snack? Microchips.","Why do Java developers wear glasses? Because they don't C#.","Charging the laser\u2026 pew pew!","Dividing by zero\u2026 just kidding!","Looking for an adult superviso\u2026 I mean, processing.","Making it go beep boop.","Buffering\u2026 because even AIs need a moment.","Entangling quantum particles for a faster response","Polishing the chrome\u2026 on the algorithms.","Are you not entertained? (Working on it!)","Summoning the code gremlins\u2026 to help, of course.","Just waiting for the dial-up tone to finish","Recalibrating the humor-o-meter.","My other loading screen is even funnier.","Pretty sure there's a cat walking on the keyboard somewhere","Enhancing\u2026 Enhancing\u2026 Still loading.","It's not a bug, it's a feature\u2026 of this loading screen.","Have you tried turning it off and on again?","Constructing additional pylons","New line? That\u2019s Ctrl+J.","Releasing the HypnoDrones","Pushing the button, Frank.","Consulting with the Companion Cube","Testing for science. You monster.","Dispensing deadly neurotoxin just kidding, compiling.","Now thinking with portals","Wheatley is currently attempting to hack this prompt","Developing combustible lemons","Aperture Science Enrichment Center is processing your request.","SPAAAACE! Space! SPAAAACE!","The cake is not a lie, it just needs a few more seconds.","Praise the Sun! \u2600\uFE0F","Hey you, you're finally awake.","Stay a while and listen.","All your base are belong to us.","It's dangerous to go alone! Take this code.","Protocol 3: Protect the Pilot.","Finish Him! (The loading bar, that is)","War war never changes. But this prompt will.","Snake? Snake?! SNAAAAKE!","Got a selection of good things on sale, stranger!","Boy! Read the documentation.","Reticulating Minecraft splines","Feed the loading bar a quick snack","Converting dark mode to dark magic","Asking the rubber duck for advice","Dividing by zero wait, NO NO NO\u2014","Herding the 1s and 0s back into line","Bribing the server with cookies","Establishing contact with the Moon base","Calibrating astronaut suit thrusters","Drawing doodle on space helmet","Synthesizing Lunafilament","Deactivating runaway lunar defense bots","Calculating gravity offset watch your step!","Hacking the Delphi Corporation mainframe","What comes after dreaming? Loading screen, apparently.","Petting the holographic giant cat","Securing payload for Earth re-entry","Wort wort wort!","Did you touch my Warthog?","One small step for man, one giant leap for the loading bar.","The Halo array is charging or maybe just a fan.","Deploying Pelican dropship eventually.","Just cleaning my plasma pistol BRB.","Checking Master Chief's helmet for scratches.","Counting sheep wait, wrong game.","S-Tier loading screen incoming.","Alarm blaring it's just your internet connection.","Looking for a helicopter or just your patience.","Need a taxi? Just kidding, I'm loading.","This loading time is criminal.","Wish I had a cheat code for fast loading.","Polishing the loading bar until it shines","Training the server hamsters","Baking a fresh batch of witty comments","Aligning my existential dread with your request","Just doodling on the terminal","Searching for the wifi password in the cosmos","Trying to remember my CAPTCHA training","Deciphering ancient scrolls (aka documentation)","Brewing a perfect cup of code","Petting the cat that photobombed my code","Applying a digital glow-up to your request","Checking my reflection in the buffer... okay, I'm ready","Consulting my mood board for the perfect response","Wait, let me fix my crown first","Manifesting a bug-free masterpiece","Slaying this prompt in 3... 2... 1...","Just a sec, I'm curate-ing the vibes","Putting the 'art' in Artificial Intelligence","Evaluating if this prompt is worthy of my brilliance","Updating my mental wardrobe for this task"];import Ct,{useState as wd}from"react";import{Box as co,Text as To,useInput as Td}from"ink";function Es({prompts:t,onSelect:g,onClose:x,theme:S="Dark"}){let w=je(S),[p,i]=wd(0);Td((X,E)=>{E.escape&&x(),E.upArrow&&i(v=>Math.max(0,v-1)),E.downArrow&&i(v=>Math.min(t.length-1,v+1)),E.return&&t[p]&&g(t[p].id)});let D=qe(2),m=10,B=0;if(t.length>m){let X=Math.floor(m/2);B=p-X,B<0?B=0:B+m>t.length&&(B=t.length-m)}let M=t.slice(B,B+m);return Ct.createElement(co,{flexDirection:"column",borderStyle:"round",borderColor:w.borderMuted,padding:0,width:"100%"},Ct.createElement(co,{paddingX:1,marginBottom:1},Ct.createElement(To,{color:w.text,bold:!0},"CODEBASE TIME TRAVEL: SELECT UNDO POINT")),Ct.createElement(co,{paddingX:2,marginBottom:1},Ct.createElement(To,{color:w.text},"Select a prompt to revert the codebase back to the state ",Ct.createElement(To,{bold:!0,color:w.secondary||"cyan"},"immediately before")," it was executed:")),t.length===0?Ct.createElement(co,{paddingX:2,paddingY:1},Ct.createElement(To,{italic:!0,color:w.textMuted},"No prompt checkpoints found for this session.")):Ct.createElement(co,{flexDirection:"column",width:"100%"},B>0&&Ct.createElement(co,{paddingX:2,marginBottom:1},Ct.createElement(To,{color:w.textMuted},"\u25B2 (+",B," more prompts above)")),M.map((X,E)=>{let k=B+E===p,O=yd(X.timestamp),L=X.changes?X.changes.length:0;return Ct.createElement(co,{key:X.id,paddingX:1,backgroundColor:k?w.highlightBg:void 0,width:"100%"},Ct.createElement(co,{flexGrow:1},Ct.createElement(To,{color:k?w.text:w.textMuted,bold:k},k?"\u276F ":" ",'"',bd(X.prompt),'"',Ct.createElement(To,{color:w.textMuted}," [",O," \u2022 ",L," file(s) changed]"))))}),B+m<t.length&&Ct.createElement(co,{paddingX:2,marginTop:1},Ct.createElement(To,{color:w.textMuted},"\u25BC (+",t.length-(B+m)," more prompts below)"))),Ct.createElement(co,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:w.borderMuted},Ct.createElement(To,{color:w.textMuted,italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function bd(t){if(!t)return"";let x=(t.split(`
50
- `)[0]||"").replace(/@\[(.*?)\]/g,(S,w)=>{let p=w.replace(/\\/g,"/").split("/");return`[${p[p.length-1]}]`});return x.length>69?x.slice(0,67)+"...":t.includes(`
51
- `)?x+"...":x}function yd(t){if(!t)return"N/A";let g=new Date(t);if(isNaN(g.getTime()))return"N/A";let x=i=>String(i).padStart(2,"0"),S=x(g.getHours()),w=x(g.getMinutes()),p=x(g.getSeconds());return`${S}:${w}:${p}`}import Sd from"puppeteer";import{exec as Cd}from"child_process";import{promisify as Md}from"util";import il from"fs";var ll=Md(Cd),al=()=>{try{let t=Pi();if(t.executablePath&&il.existsSync(t.executablePath))return!0;let g=Sd.executablePath();if(g&&il.existsSync(g))return!0}catch{return!1}return!1},dl=async t=>{t&&t("\u{1F4E5} Downloading Chromium engine (chrome@148)...");try{try{await ll("pnpm exec puppeteer browsers install chrome@148")}catch{await ll("npx -y puppeteer browsers install chrome@148")}return await new Promise(g=>setTimeout(g,1e3)),{success:!0}}catch(g){return console.error("[SETUP ERROR]",g),{success:!1,error:g.message}}};import cl,{useState as ul,useEffect as ml}from"react";import{Text as gl}from"ink";var Bd=({text:t,baseColor:g="grey",glintColor:x="gray",speed:S=200,glintWidth:w=6,typeSpeed:p=30,...i})=>{let[D,m]=ul(-w),[B,M]=ul(t);return ml(()=>{let X=setInterval(()=>{m(E=>E>B.length+w?-w-40:E+1)},S);return()=>clearInterval(X)},[B.length,S,w]),ml(()=>{if(t&&(t.includes("Trying to reach")&&B&&B.includes("Trying to reach")||t.includes("Error Occurred")&&B&&B.includes("Error Occurred"))){M(t);return}if(B===t)return;let X=setTimeout(()=>{let E=0,v=Math.min(B.length,t.length);for(;E<v&&B[E]===t[E];)E++;B.length>E?M(k=>k.slice(0,-1)):B.length<t.length&&M(t.slice(0,B.length+1))},p);return()=>clearTimeout(X)},[t,B,p]),cl.createElement(gl,null,B.split("").map((X,E)=>{let k=Math.abs(E-D)<=w/2?x:g;return cl.createElement(gl,{key:E,color:k,...i},X)}))},_n=Bd;var Hn=t=>{let g=String(t);return g.startsWith("999")&&g.endsWith("9")},hn=t=>t==null||t===0||Hn(t)?"":String(t),Ko=()=>{let t=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let g=x=>{let S=x.toLowerCase();for(let[w,p]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(w)&&String(p).toLowerCase().includes(S))return!0;return!1};return t==="cursor"||process.env.CURSOR_SETTINGS_DIR||g("cursor")?"Cursor":t==="windsurf"||g("windsurf")?"Windsurf":g("antigravity")?"Antigravity":t==="trae"||g("trae")?"Trae":t==="codium"||g("codium")||g("vscode-oss")?"VSCodium":g("positron")?"Positron":t==="vscode-insiders"||g("insiders")?"VS Code Insiders":t==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||g("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||g("intellij")?"JetBrains":"Terminal"},Ld=t=>{switch(t){case"VS Code":return"Code";case"VS Code Insiders":return"Code - Insiders";case"Antigravity":return"Antigravity IDE";default:return t}},fl={Flux:"Workspace",Flow:"Studio",ICU:"Computer Use",FluxCU:"Omni"},Ds=t=>{if(!t)return"Workspace";let g=Object.keys(fl).find(x=>x.toLowerCase()===t.toLowerCase());return g?fl[g]:t},hl=t=>{let g=Ld(t),x=Is.homedir();if(process.platform==="win32"){let S=process.env.APPDATA;return S?It.join(S,g,"User","keybindings.json"):null}else return process.platform==="darwin"?It.join(x,"Library","Application Support",g,"User","keybindings.json"):It.join(x,".config",g,"User","keybindings.json")},xl=t=>{let g=t.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1");return JSON.parse(g)},Od=t=>Array.isArray(t)?t.some(g=>g&&typeof g.key=="string"&&g.key.toLowerCase().replace(/\s+/g,"")==="shift+enter"&&g.command==="workbench.action.terminal.sendSequence"&&g.args&&g.args.text==="\x1B[13;2u"&&typeof g.when=="string"&&g.when.includes("terminalFocus")):!1,wl=t=>{let g=t==="VS Code",x=[];return g?(x.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),x.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):x.push({label:`Download for ${t} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),x.push({label:"Continue to CLI only",action:"dismiss"}),x},Pd=({width:t,height:g,selectedIndex:x,aiProvider:S,theme:w="Dark"})=>{let p=Ko(),i=wl(p);return e.createElement(c,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:t,height:g},e.createElement(c,{marginBottom:1,width:Math.min(80,t-4),justifyContent:"flex-start"},e.createElement(s,null,dr(oo,S,w))),e.createElement(c,{flexDirection:"column",borderStyle:"double",borderColor:"grey",paddingX:3,paddingY:1,width:Math.min(80,t-4)},e.createElement(s,{bold:!0,color:"white",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),e.createElement(c,{marginY:1,flexDirection:"column",alignItems:"left"},e.createElement(s,null,"You're in ",e.createElement(s,{bold:!0,color:"cyan"},p),", but the ",e.createElement(s,{bold:!0,color:"white"},"FluxFlow-CLI Companion")," is not installed."),e.createElement(c,{flexDirection:"column",marginY:1},e.createElement(s,{color:"gray"}," \u2705 Real-time IDE context & Error Resolution"),e.createElement(s,{color:"gray"}," \u2705 Auto-open files created by agent"),e.createElement(s,{color:"gray"}," \u2705 Native DIFFing for AI edits"),e.createElement(s,{color:"gray"}," \u2705 Direct IDE context sharing"),e.createElement(s,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),e.createElement(s,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),e.createElement(s,{color:"gray"}," \u2705 Live Status in IDE"),e.createElement(s,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),e.createElement(c,{flexDirection:"column",marginTop:1},i.map((D,m)=>e.createElement(c,{key:m},e.createElement(s,{color:x===m?"yellow":"white",bold:x===m},x===m?" \u276F ":" ",D.label)))),e.createElement(c,{marginTop:1,alignItems:"center",justifyContent:"center"},e.createElement(s,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},vs=Date.now(),pl="https://fluxflow-cli.onrender.com/changelog",ks="https://fluxflow-cli.onrender.com/",Nd=It.join(It.dirname(Id(import.meta.url)),"../package.json"),Tl=JSON.parse(lt.readFileSync(Nd,"utf8")),oo=Tl.version,Fd=Tl.date||"2026-05-20";var Ud=({data:t,onResolve:g,onEdit:x,theme:S="Dark"})=>{let w=je(S);return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:w.borderMuted,padding:0,width:"100%"},e.createElement(c,{paddingX:1},e.createElement(s,{color:w.text,bold:!0,underline:!0},t.startsWith("/btw")?"QUESTION":"STEERING HINT"," RESOLUTION")),e.createElement(c,{paddingX:1,marginTop:1},e.createElement(s,{color:w.text},"The agent already finished the task before your ",t.startsWith("/btw")?"question":"hint"," was consumed.")),e.createElement(c,{marginTop:1,backgroundColor:w.cardBg||w.codeBg||"#222",paddingX:2,width:"100%"},e.createElement(s,{italic:!0,color:w.textMuted},'"',t.replace("/btw","").trim(),'"')),e.createElement(c,{paddingX:1,marginTop:1},e.createElement(s,{color:w.textDim||w.textMuted},"How would you like to proceed?")),e.createElement(c,{marginTop:0},e.createElement(ft,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:p=>{(typeof p=="object"&&p!==null?p.value:p)==="send"?g(t):x(t)},theme:S})))};var Xd=(()=>{let t=null,g=0;return x=>{let S=Date.now();if(t&&S-g<1e4)return t;let w=[],p=i=>{if(!(w.length>=2e3))try{let D=lt.readdirSync(i);for(let m of D){if(w.length>=2e3)return;if(["node_modules",".git",".gemini","dist","build",".next",".cache","out"].includes(m))continue;let B=It.join(i,m);lt.statSync(B).isDirectory()?p(B):w.push({name:ut(m),relativePath:ut(It.relative(process.cwd(),B))})}}catch{}};return p(x),t=w,g=S,w}})(),Br="Ctrl + Enter",$d=t=>{if(t<=370)return"#00a564";if(t>=5e3)return"#ff0000";let g=[{t:370,r:0,g:165,b:100},{t:550,r:40,g:195,b:80},{t:800,r:120,g:220,b:50},{t:1100,r:190,g:225,b:20},{t:1500,r:250,g:210,b:15},{t:2e3,r:255,g:170,b:0},{t:2800,r:255,g:110,b:0},{t:3800,r:255,g:50,b:0},{t:5e3,r:255,g:0,b:0}];for(let x=0;x<g.length-1;x++){let S=g[x],w=g[x+1];if(t>=S.t&&t<=w.t){let p=(t-S.t)/(w.t-S.t);p=p*p*(3-2*p);let i=Math.round(S.r+(w.r-S.r)*p),D=Math.round(S.g+(w.g-S.g)*p),m=Math.round(S.b+(w.b-S.b)*p);return`#${((1<<24)+(i<<16)+(D<<8)+m).toString(16).slice(1)}`}}return"#ff0000"},_d=e.memo(({sa:t,showTPMEstimate:g=!1})=>{let[x,S]=q("green"),[w,p]=q(0),i=Ve([]),D=Ve(370),m=Ve([]),B=Ve(t.lastChunkTime);return Qe(()=>{B.current=t.lastChunkTime},[t.lastChunkTime]),Qe(()=>{if(t.status!=="running"){m.current=[];return}if(t.wps>0){let M=m.current;M.push(t.wps),M.length>3&&M.shift(),p(Math.round(t.wps))}},[t.status,t.wps,t.lastChunkTime]),Qe(()=>{if(t.status!=="running"){p(0);return}let M=setInterval(()=>{let X=B.current,E=X>0?Date.now()-X:0;if(X>0&&E>1500)m.current=[],p(0);else if(X>0&&E>600){m.current.length>0&&m.current.shift();let v=m.current;if(v.length>0){let k=v.reduce((O,L)=>O+L,0);p(Math.round(k/v.length))}else p(0)}else{let v=m.current;if(v.length>0){let k=v.reduce((O,L)=>O+L,0);p(Math.round(k/v.length))}else t.wps>0&&p(Math.round(t.wps))}},750);return()=>clearInterval(M)},[t.status]),Qe(()=>{if(t.status!=="running"){i.current=[];return}let M=t.lastChunkTime;if(M>0){let v=i.current;(v.length===0||v[v.length-1]!==M)&&(v.push(M),v.length>10&&v.shift())}let X=()=>{if(!M){S("#00a564");return}let v=i.current,k=0;if(v.length>1){let Q=0;for(let K=1;K<v.length;K++)Q+=v[K]-v[K-1];k=Q/(v.length-1)}let O=Date.now()-M,$=O>=2500,te=!$&&k>0?Math.min(O,k*3):O,ae=Math.max(k,te),fe=$?.4:.2;D.current=D.current*(1-fe)+ae*fe,S($d(D.current))};X();let E=setInterval(X,100);return()=>clearInterval(E)},[t.status,t.lastChunkTime]),e.createElement(c,{justifyContent:"space-between",width:"100%"},e.createElement(s,{color:"white"}," \u2022 ",t.title," ",e.createElement(s,{color:"white",dimColor:!0},"(",t.id,")")),e.createElement(s,{color:"white"},e.createElement(s,{color:"white",dimColor:!0,bold:!0},t.currentTool||"Active"),e.createElement(s,{color:x}," \u25CF"),g&&e.createElement(s,{color:"white",dimColor:!0,bold:!0}," (",w," tps)")))});function Hd({args:t=[]}){let g=Ve(1),[x,S]=q(!1),[w,p]=q(10),{stdout:i}=Dd(),[D,m]=q(""),[B,M]=q(0),[X,E]=q(!1),[v,k]=q("Flux"),[O,L]=q(0),[$,te]=q({columns:i?.columns||80,rows:i?.rows||24}),[ae,fe]=q(0),[Q,K]=q(!1),[re,Ee]=q(!1),[ye,ke]=q(0),de=Ve(0),Pe=Ve(0),Te=Ve(null),G=Ve(null),he=Ve(0),[R,P]=q(0),ee=()=>P(o=>o+1),se=Ve([]),be=Ve(null),ve=()=>{let o=se.current;if(o.length>0&&G.current){let n=o.join("");o.length=0,G.current.text=ut(G.current.text+n),ee()}},Se=()=>{if(ve(),G.current){let o=ut(G.current.text);G.current.role==="think"&&(o=o.replace(/^\r?\n+/,"").replace(/\r?\n+$/,""));let n={...G.current,text:o,isStreaming:!1};N(a=>{let f=[...a,n];return V(f.length),f}),G.current=null}Ns.current=0,Pr.current={totalWords:0,startTime:0,wps:0,chunks:[]}},Ie=()=>{be.current&&clearInterval(be.current),se.current=[],be.current=setInterval(()=>{try{let o=se.current;if(o.length>0&&G.current){let n=1;o.length>85?n=30:o.length>80?n=25:o.length>75?n=20:o.length>65?n=16:o.length>50?n=12:o.length>35?n=8:o.length>15?n=6:o.length>5?n=4:o.length>3&&(n=2);let a="";for(let f=0;f<n&&o.length>0;f++)a+=o.shift();G.current.text=ut(G.current.text+a),ee()}}catch{}},80)},Re=async()=>{for(;ce.progressiveRendering&&se.current.length>0;)await new Promise(o=>setTimeout(o,10))},ot=o=>{if(ce.progressiveRendering&&be.current){let n=o.split(/(\s+)/).filter(Boolean);for(let a of n)se.current.push(a)}else G.current?G.current.text=ut(G.current.text+o):G.current={id:"agent-"+Date.now(),role:"agent",text:ut(o),isStreaming:!0},ee()};Qe(()=>{let o=Ko(),n=!["Terminal","Windows Terminal"].includes(o)||!!process.env.VSC_TERMINAL_URL,a=setTimeout(()=>{n&&!Vo()&&Ee(!0)},500),f=setInterval(()=>{Vo()&&Ee(!1)},1e3);g.current=Date.now();let u=setInterval(()=>{g.current&&(Date.now()-g.current||0)>3e4&&global.gc&&(async()=>{for(let d=0;d<1;d++)global.gc(),await new Promise(y=>setImmediate(y));g.current=Date.now()})()},3e3);return()=>{clearTimeout(a),clearInterval(f),clearInterval(u)}},[]),Qe(()=>{(async()=>{try{let n=await ts(),a=n?.systemSettings||{},f=a.CustomSubAgent,u=a.SubAgentModel;if(!f||!u||u==="Default")return;let T=process.env.SUBAGENT_MODEL?process.env.SUBAGENT_MODEL.trim():null,h=process.env.SUBAGENT_PROVIDER?process.env.SUBAGENT_PROVIDER.trim():null,d=["Google","DeepSeek","OpenRouter","NVIDIA","Mistral","Ollama","CrofAI","InferX","SenseNova","AIHubMix"],I=(J=>{if(!J)return null;let le=J.toLowerCase();return le==="google"?"Google":le==="deepseek"?"DeepSeek":le==="openrouter"?"OpenRouter":le==="nvidia"?"NVIDIA":le==="mistral"?"Mistral":le==="ollama"?"Ollama":le==="crofai"||le==="crof"?"CrofAI":le==="inferx"?"InferX":le==="sensenova"?"SenseNova":le==="aihubmix"||le==="aihub"?"AIHubMix":null})(h);if(T&&!I){let J=n.aiProvider||H||"Google";N(le=>(V(le.length+1),[...le,{id:"subagent-env-noprov-"+Date.now(),role:"system",text:`[SUBAGENT CONFIG] SUBAGENT_MODEL found in ENV but SUBAGENT_PROVIDER is missing/invalid. Active provider (${J}) will be used.`,isMeta:!0}]))}if(u==="ENV"){T||N(J=>(V(J.length+1),[...J,{id:"subagent-model-noenv-"+Date.now(),role:"system",text:"No SubAgent model is found in ENV, Using Deafult until changed",isMeta:!0}]));return}let _=n.aiProvider||H||"Google",j=n.apiTier||Je||"Free",ue=n.quotas||Ae||{},z=new Set;(vo(_,j)||[]).forEach(J=>{let le=typeof J=="string"?J:J.cmd||J.name||J.id||String(J);le&&z.add(le)});for(let J of d)try{if(await ln(J)){let rt=ue?.providerTiers?.[J]||"Free";(vo(J,rt)||[]).forEach(Xe=>{let tt=typeof Xe=="string"?Xe:Xe.cmd||Xe.name||Xe.id||String(Xe);tt&&z.add(tt)})}}catch{}let Oe=z.has(u);T?T!==u&&N(J=>(V(J.length+1),[...J,{id:"subagent-model-env-"+Date.now(),role:"system",text:"Current Seleted Sub-Agent model is not available in this provider. Using model from ENV unless changed.",isMeta:!0}])):Oe||N(J=>(V(J.length+1),[...J,{id:"subagent-model-err-"+Date.now(),role:"system",text:"Current Seleted Sub-Agent model is not available in this provider. Using Default until changed",isMeta:!0}]))}catch{}})()},[]);let De=fn(()=>{let o={};for(let n=0;n<t.length;n++)if(t[n]==="--key"&&t[n+1]){let f=t[n+1];if(o.key=f,f.includes("@")){let u=f.split("@"),T=u[0],h=u[1].toLowerCase();if(["google","deepseek","openrouter","nvidia","mistral","ollama","crof","crofai","inferx","sensenova","aihubmix","aihub"].includes(h)){let d="Google";h==="google"?d="Google":h==="deepseek"?d="DeepSeek":h==="openrouter"?d="OpenRouter":h==="nvidia"?d="NVIDIA":h==="mistral"?d="Mistral":h==="ollama"?d="Ollama":h==="crof"||h==="crofai"?d="CrofAI":h==="inferx"?d="InferX":h==="sensenova"?d="SenseNova":(h==="aihubmix"||h==="aihub")&&(d="AIHubMix"),o.key=T,o.provider=d}}}for(let n=0;n<t.length;n++){let a=t[n];if(a==="--key"){n++;continue}if(a==="--model"&&t[n+1])o.model=t[n+1],n++;else if(a==="--memory"&&t[n+1])o.memory=t[n+1].toLowerCase(),n++;else if(a==="--resume"&&t[n+1])o.resume=t[n+1],n++;else if(a==="--package"&&t[n+1]){let f=t[n+1].toLowerCase();["npm","pnpm","yarn","bun"].includes(f)&&(o.package=f),n++}else if(a==="--auto-del"&&t[n+1]){let f=t[n+1].toLowerCase();["1d","7d","30d"].includes(f)&&(o.autoDel=f),n++}else if(a==="--auto-exec"&&t[n+1])o.autoExec=t[n+1].toLowerCase(),n++;else if(a==="--yolo"&&t[n+1])o.autoExec=t[n+1].toLowerCase(),n++;else if(a==="--external-access"&&t[n+1])o.externalAccess=t[n+1].toLowerCase(),n++;else if(a==="--mode"&&t[n+1]){let u=t[n+1].toLowerCase();if(["flux","flow","icu","computer","fluxcu"].includes(u)){let T="Flux";u==="flux"?T="Flux":u==="flow"?T="Flow":u==="icu"||u==="computer"?T="ICU":u==="fluxcu"&&(T="FluxCU"),o.mode=T}n++}else if(a==="--thinking"&&t[n+1]){let u=t[n+1].toLowerCase();if(["fast","low","medium","high","xhigh","standard"].includes(u)){let T="Medium";u==="fast"?T="Fast":u==="low"?T="Low":u==="standard"?T="Standard":u==="medium"?T="Medium":u==="high"?T="High":u==="xhigh"&&(T="xHigh"),o.thinking=T}n++}else if(a==="--provider"&&t[n+1]){let f=t[n+1].toLowerCase();if(["google","deepseek","openrouter","nvidia","mistral","ollama","crof","crofai","inferx","sensenova","aihubmix","aihub"].includes(f)){let u="Google";f==="google"?u="Google":f==="deepseek"?u="DeepSeek":f==="openrouter"?u="OpenRouter":f==="nvidia"?u="NVIDIA":f==="mistral"?u="Mistral":f==="ollama"?u="Ollama":f==="crof"||f==="crofai"?u="CrofAI":f==="inferx"?u="InferX":f==="sensenova"?u="SenseNova":(f==="aihubmix"||f==="aihub")&&(u="AIHubMix"),o.provider=u}n++}else(a==="--resume"||a==="-r")&&t[n+1]?(o.resume=t[n+1],n++):a==="--playground"?o.playground=!0:(a==="--original-cwd"||a==="--orginal-cwd")&&t[n+1]&&(o.originalCwd=t[n+1],n++)}return o},[t]),oe=async(o=!1,n=null)=>{let a=n||ce;o&&N(f=>(V(f.length+1),[...f,{id:"check-"+Date.now(),role:"system",text:"\u2726 Checking for updates...",isMeta:!0}]));try{let u=await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json(),T=u["dist-tags"]?.latest,h=u["dist-tags"]?.stable;if(T&&qo(T),T&&T!==oo){let d=T===h?`v${T}`:`v${T}`;!o&&a.autoUpdate?Y("update"):N(y=>{let I=[...y],_=o?I.length:Math.min(I.length,3);return I.splice(_,0,{id:"update-"+Date.now(),role:"system",text:`A new version (${d}) is here.
52
-
53
- \u2022 Type \`/update latest\` to apply the update.
54
- \u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),I})}else o&&N(d=>{V(d.length+1);let y=T&&T===h?`${oo}`:oo;return[...d,{id:"uptodate-"+Date.now(),role:"system",text:`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Already up to date (${y}).
55
- \u2800`,isMeta:!0}]})}catch(f){o&&N(u=>(V(u.length+1),[...u,{id:"check-err-"+Date.now(),role:"system",text:`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Failed to check for updates: ${f.message}.
56
- \u2800`,isMeta:!0}]))}};Qe(()=>{let o=()=>{i.write("\x1B[2J\x1B[3J\x1B[H"),te({columns:i.columns,rows:i.rows})};return i.on("resize",o),()=>{i.off("resize",o)}},[i]);let[me,_e]=q("Medium"),[H,Mt]=q("Google"),[ct,Pt]=q(0),[Vt,qo]=q(null),[Ht,Er]=q(!1),[ne,ie]=q(no("Google","Free")||"gemma-4-31b-it"),[b,F]=q(!1),[Ce,$e]=q(bi("gemma_janitor_fallback_google")||"gemma-4-26b-a4b-it"),[nt,Ze]=q(!0),[Fe,jt]=q(!0),We=Ve(0),[bt,Kt]=q(null),[Dr,Qo]=q(""),vr=async o=>{let n=hl(o);if(n)try{await lt.ensureDir(It.dirname(n));let a=[];if(lt.existsSync(n)){let f=lt.readFileSync(n,"utf8").trim();if(f)try{a=xl(f)}catch{a=[]}}Array.isArray(a)||(a=[]),a.push({key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\x1B[13;2u"},when:"terminalFocus"}),lt.writeFileSync(n,JSON.stringify(a,null,4),"utf8"),Br="Shift + Enter",N(f=>(V(f.length+1),[...f,{id:"kb-success-"+Date.now(),role:"system",text:`\u2726 Successfully configured Shift+Enter in your ${o} keybindings!
57
- `,isMeta:!0}]))}catch(a){N(f=>(V(f.length+1),[...f,{id:"kb-error-"+Date.now(),role:"system",text:`\u2726 Failed to update keybindings: ${a.message}.
58
- \u2800`,isMeta:!0}]))}},[at,Y]=q("chat"),[Je,Fo]=q("Free"),[Ae,Ft]=q({limitMode:"Daily",agentLimit:99999999,tokenLimit:99999999999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0,providerBudgets:{}}),[bo,qt]=q(null),[yo,bl]=q("chat"),[zo,kr]=q("settings"),[Jo,yl]=q([]),[Wd,Sl]=q(0),[As,Wn]=q(0),[Ir,Ls]=q({}),[Ar,Lr]=q({}),[Gn,uo]=q(0),[ce,Bt]=q({memory:!0,theme:"Dark",compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:""}),l=fn(()=>je(ce.theme),[ce.theme]),[xn,Os]=q({name:null,nickname:null,instructions:null}),[So,Yn]=q({keyType:"Default",quality:"Low-High",apiKey:""}),[mo,Uo]=q({tokens:0}),[Ps,Or]=q(0),Ns=Ve(0),Pr=Ve({totalWords:0,startTime:0,wps:0,chunks:[]}),[Fs,Us]=q(0),[Xs,Cl]=q(0),[Qt,$s]=q(0),[Ml,pn]=q(0),wn=Ve(0),[Vn,_s]=q(0),[Zo,Hs]=q(0),[Gd,Bl]=q(0),[Yd,El]=q(0),[Vd,Dl]=q(0),[jn,vl]=q(0),[Kn,kl]=q(0),[qn,Il]=q(0),[Ws,Al]=q(0),[Tn,Nr]=q(null),[Qn,Fr]=q(null),[Ur,Gs]=q(null),[Ro,bn]=q("daily"),[Ll,Zt]=q(0),[yn,Sn]=q(""),Cn="flow-playground",[et,zn]=q(t.includes("--playground")?Cn:ls());Qe(()=>{if(Ho.current)return;let o=Qt-wn.current;pn(o),et&&Oi(et,o,mo.tokens).catch(()=>{})},[Qt,et,mo.tokens]),Qe(()=>{at==="apiTier"&&(async()=>{let n=await lr();Nr(n);let a=await ar();Fr(a);let f=await os(Ae.resetDay||1);Gs(f)})()},[at,Ae.resetDay]);let[Rt,Ys]=q(null),[en,tn]=q(""),[Mn,Vs]=q(!1),[Xr,Ol]=q([]),[jd,Kd]=q(0),js=Ve(!0),Ks=Ve(!0),$r=Ve(H),_r=Ve(!1),Hr=Ve(!0);Qe(()=>{b&&(F(!1),N(o=>(V(o.length+1),[...o,{id:Date.now(),role:"system",text:`\u2726 Wildcard Tooling:
59
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Status: Disabled.
60
- \u2800`,isMeta:!0}]))),process.env.forcedReasoning&&(N(o=>(V(o.length+1),[...o,{id:Date.now(),role:"system",text:`\u2726 Forced Reasoning:
61
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Status: Disabled.
62
- \u2800`,isMeta:!0}])),process.env.forcedReasoning=!1)},[ne]);let qs;Qe(()=>{if(Ks.current){qs=setTimeout(()=>{Ks.current=!1,$r.current=H},1e3);return}if($r.current!==H)if($r.current=H,H==="Mistral")_e("Fast");else{if(H==="SenseNova"){_e("High");return}_e(H==="DeepSeek"||H==="NVIDIA"||H==="CrofAI"||H==="InferX"||H==="Ollama"||H==="CroAI"||H==="OpenRouter"?"Standard":"Medium")}else H==="Google"&&me==="xHigh"&&ne&&ne.toLowerCase().startsWith("gemini-3")&&_e("High");return()=>{clearTimeout(qs)}},[H,ne]);let Qs;Qe(()=>{if(!bt)return;if(js.current){Qs=setTimeout(()=>{js.current=!1},1500);return}let o=no(H,Je),n=o;return o.includes("gemma")?n="Gemma":o.includes("deepseek")?n="DeepSeek Flash":o.includes("devstral")?n="Devstral":o.includes("mistral")?n="Mistral":o.includes("gemini")&&(n="Gemini Flash"),ie(o),Dt({apiTier:Je,activeModel:o}),()=>{clearTimeout(Qs)}},[Je,H,bt]);let Pl=fn(()=>{let o=Ko();return{isIDE:!["Terminal","Windows Terminal"].includes(o)||!!process.env.VSC_TERMINAL_URL||!!process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS,get shortcut(){return Br}}},[]),Jn=Ve(null),Wr=Ve("");Qe(()=>{Jn.current=Rt},[Rt]),Qe(()=>{Wr.current=en},[en]);let[Nl,Fl]=q(!1),[Co,on]=q(null),[Xo,Gr]=q(null),Zn=o=>{on(null),Y("chat")},zs=o=>{let n=Math.floor(o/3600),a=Math.floor(o%3600/60),f=o%60,u=[];return n>0&&u.push(`${n}h`),(a>0||n>0)&&u.push(`${a}m`),u.push(`${f}s`),u.join(" ")},$o=o=>o<1e3?`${o}ms`:zs(Math.floor(o/1e3)),[Bn,Yr]=q(null),[Vr,Js]=q(""),[Ul,Xl]=q(!1),[Zs,En]=q(0),Dn;Qe(()=>{let o;if(Bn&&ce.loadingPhrases!==!1){let n=()=>{let a=Bs[Math.floor(Math.random()*Bs.length)];Js(a)};Vr||n(),o=setInterval(n,1e4)}else Js("");return()=>{clearInterval(o)}},[Bn,ce]);let[qd,$l]=q(!0),[nn,jr]=q(!1),[Rn,Rs]=q(!1),[_l,Hl]=q(!1),[ei,Qd]=q(null),[ti,vn]=q(0),[Wl,oi]=q([]),_o=Ve(null),Ho=Ve(!1);Qe(()=>()=>{_o.current&&clearTimeout(_o.current)},[]);let Kr=Ve(!1),[zd,qr]=q(null),[Gl,Qr]=q(null),[Jd,Yl]=q(null);Qe(()=>vn(0),[D]);let[xt,Vl]=q(()=>{let o={id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0},n=process.cwd()===Is.homedir(),a=(()=>{let u=process.cwd().toLowerCase();if(process.platform==="win32"){let T=process.env.SystemRoot?.toLowerCase()||"c:\\windows",h=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",d=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return u.startsWith(T)||u.startsWith(h)||u.startsWith(d)}else return u==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(h=>u.startsWith(h))})(),f=[o];return a?f.push({id:"system-warning",role:"system",text:"[CRITICAL SECURITY ALERT] SYSTEM DIRECTORY DETECTED",subText:`You are currently in a PROTECTED SYSTEM DIRECTORY (${process.cwd()}). Operating here is EXTREMELY dangerous as the agent could accidentally corrupt your OS or installed applications. Open FluxFlow in project folder to work safely.`,isHomeWarning:!0}):n&&f.push({id:"home-warning",role:"system",text:"[SECURITY ALERT] HOME DIRECTORY DETECTED",subText:`You are currently in ${Is.homedir()}. Working here is high-risk as the agent may modify system-sensitive configurations. Please open FluxFlow in project folder.`,isHomeWarning:!0}),f}),N=o=>{Vl(n=>{let a=typeof o=="function"?o(n):o;if(a.length>1){let f=a[a.length-1],u=a[a.length-2];if(f?.text?.includes("Request Cancelled")&&u?.text?.includes("Request Cancelled"))return a.slice(0,-1)}return a})},Mo=Ve(null),[ni,jl]=q(""),[ri,si]=q(!1),ii=Ve(""),li=Ve(null);Qe(()=>{if(xt.length===0)return;let o=xt[xt.length-1];if(o&&(o.role==="agent"||o.role==="assistant")){let a=(o.text||"").match(/\[ANSWER\]([\s\S]*?)(?:\[\/ANSWER\]|$)/i);if(a){let f=a[1].trim();f&&f!==ii.current&&(jl(f),ii.current=f,li.current!==o.id&&si(!0))}}},[xt]);let[Bo,V]=q(xt.length),[Wo,zr]=q(0),Zd=Ve([]),Wt=Ve({completedIndex:0,columns:0,historicalBlocks:[],seenSelections:new Set,chatId:"",clearKey:0,theme:""}),ai=fn(()=>{let o=$.columns||80,n=/Selection: (.*)/,a=[],f=new Set,u=Wt.current.columns!==o,T=Bo<Wt.current.completedIndex,h=Wt.current.chatId!==et,d=Wt.current.clearKey!==Wo,y=Wt.current.theme!==ce.theme;if(u||T||h||d||y){let z=xt.slice(0,Bo);for(let Me=0;Me<z.length;Me++){let Oe=z[Me];if(Oe.isAskRecord&&Oe.text){let le=Oe.text.match(n);if(le&&le[1].trim()){let rt=le[1].trim();if(f.has(rt))continue;f.add(rt)}}let J=In(Oe,o);for(let le=0;le<J.completed.length;le++)a.push(J.completed[le]);for(let le=0;le<J.active.length;le++)a.push(J.active[le])}Wt.current={completedIndex:Bo,columns:o,historicalBlocks:a,seenSelections:new Set(f),chatId:et,clearKey:Wo,theme:ce.theme}}else if(a=Wt.current.historicalBlocks,f=Wt.current.seenSelections,Bo>Wt.current.completedIndex){a=[...a],f=new Set(f);let z=xt.slice(Wt.current.completedIndex,Bo);for(let Me=0;Me<z.length;Me++){let Oe=z[Me];if(Oe.isAskRecord&&Oe.text){let le=Oe.text.match(n);if(le&&le[1].trim()){let rt=le[1].trim();if(f.has(rt))continue;f.add(rt)}}let J=In(Oe,o);for(let le=0;le<J.completed.length;le++)a.push(J.completed[le]);for(let le=0;le<J.active.length;le++)a.push(J.active[le])}Wt.current={completedIndex:Bo,columns:o,historicalBlocks:a,seenSelections:f,chatId:et,clearKey:Wo}}let I=xt.slice(Bo),_=[],j=[];for(let z=0;z<I.length;z++){let Me=I[z];if(Me.isAskRecord&&Me.text){let J=Me.text.match(n);if(J&&J[1].trim()){let le=J[1].trim();if(f.has(le))continue}}let Oe=In(Me,o);for(let J=0;J<Oe.completed.length;J++)_.push(Oe.completed[J]);for(let J=0;J<Oe.active.length;J++)j.push(Oe.active[J])}if(G.current){let z=In(G.current,o);for(let Me=0;Me<z.completed.length;Me++)_.push(z.completed[Me]);for(let Me=0;Me<z.active.length;Me++)j.push(z.active[Me])}let ue=_.length===0?a:a.concat(_);return ue.length>=75e3&&(ue=[...ue],ue.push({key:`memory-warning-block-${ue.length}`,msg:{role:"system",text:"\u26A0\uFE0F MEMORY WARNING: CHAT IS GETTING VERY LONG",subText:`This session has reached ${ue.length} blocks. To maintain optimal performance and prevent high memory usage, it is highly recommended to save and start a clean chat with /clear.`,isHomeWarning:!0},type:"full-message"})),{completed:ue,active:j}},[xt,Bo,$.columns,Wo,et,R]),Kl=fn(()=>{if(!Rt||!en)return!1;let o=en.trim();return o.endsWith("?")||o.endsWith(":")||/\[[yYnN/]+\]\s*$/.test(o)||/\([yYnN]\)\s*$/.test(o)},[Rt,en]);Ed((o,n)=>{if(!(o==="\x1B[I"||o==="\x1B[O"||o==="[I"||o==="[O")){if(n.ctrl&&(o.toLowerCase()==="r"||o===""||o==="")){zi();return}if(at==="stats"){if(Ro==="dailyModelBreakdown"||Ro==="modelBreakdown"){if(n.tab&&!n.shift){bn(f=>f==="dailyModelBreakdown"?"modelBreakdown":"dailyModelBreakdown"),Zt(0);return}if(n.space||o===" "){bn(f=>f==="dailyModelBreakdown"?"daily":"monthly"),Zt(0),Sn("");return}if(n.escape){if(yn){Sn(""),Zt(0);return}Y("chat");return}if(n.upArrow){Zt(f=>Math.max(0,f-1));return}if(n.downArrow){Zt(f=>Math.min(Pe.current,f+1));return}if(n.backspace||n.delete){Sn(f=>f.slice(0,-1)),Zt(0);return}if(o&&o!==" "&&!n.space&&!n.ctrl&&!n.meta&&o.length===1&&o.charCodeAt(0)>=32){Sn(f=>f+o),Zt(0);return}return}if(n.tab&&!n.shift){bn(f=>f==="daily"?"monthly":"daily"),Zt(0);return}if(n.space||o===" "){bn(f=>f==="daily"?"dailyModelBreakdown":"modelBreakdown"),Zt(0),Sn("");return}if(n.upArrow){Zt(f=>Math.max(0,f-1));return}if(n.downArrow){Zt(f=>Math.min(Pe.current,f+1));return}}if(re){let a=Ko(),f=wl(a);if(n.upArrow)ke(u=>u>0?u-1:f.length-1);else if(n.downArrow)ke(u=>u<f.length-1?u+1:0);else if(n.return){let u=f[ye];if(u.action==="dismiss")Ee(!1);else if(u.url){let T=process.platform==="win32"?`start ${u.url}`:process.platform==="darwin"?`open ${u.url}`:`xdg-open ${u.url}`;Cr(T),Ee(!1)}}return}if(n.tab&&Rt){Vs(a=>!a);return}if(Mn&&Rt){if(n.return)if(an)Gt("\r");else{let a=process.platform==="win32";Gt(a?`\r
63
- `:`
64
- `),tn(f=>f+`
65
- `)}else if(n.backspace||n.delete)an?Gt("\x7F"):(Gt("\b \b"),tn(a=>a.slice(0,-1)));else if(n.upArrow)Gt(n.shift?"\x1B[1;2A":"\x1B[A");else if(n.downArrow)Gt(n.shift?"\x1B[1;2B":"\x1B[B");else if(n.rightArrow)Gt(n.shift?"\x1B[1;2C":"\x1B[C");else if(n.leftArrow)Gt(n.shift?"\x1B[1;2D":"\x1B[D");else if(n.escape)Gt("\x1B");else if(n.ctrl&&o){let a=o.toLowerCase().charCodeAt(0);a>=97&&a<=122?Gt(String.fromCharCode(a-96)):Gt(o)}else o&&(Gt(o),an||tn(a=>a+o));return}if(at==="providerBudgetSelect"){let a=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","CrofAI","InferX","SenseNova"];if(n.upArrow){Wn(f=>(f-1+a.length)%a.length);return}else if(n.downArrow){Wn(f=>(f+1)%a.length);return}else if(o===" "){let f=a[As];Ls(u=>({...u,[f]:!u[f]}));return}else if(n.return){let f=a.filter(T=>Ir[T]);if(f.length===0)return;let u={...Ae,providerBudgets:{...Ae.providerBudgets||{},__useProvider:!0}};Ft(u),yl(f),Sl(0),Wn(0),Y("providerBudgetFlow");return}else if(n.escape){Y("budgetTypeSelect");return}return}if(at==="providerBudgetFlow"){let a=Jo.length,f=a*2+1;if(n.upArrow){uo(u=>u===f-1?Math.max(0,(a-1)*2):u>=2?u-2:u);return}else if(n.downArrow){uo(u=>u===f-1?u:u+2<f-1?u+2:f-1);return}else if(n.leftArrow){uo(u=>u===f-1?u:u%2===1?u-1:u);return}else if(n.rightArrow||n.tab){uo(u=>u===f-1?u:u%2===0||u+1<f?u+1:u);return}else if(n.return){if(Gn===f-1){let u=Ae.providerBudgets||{},T={__useProvider:!0};for(let y of Jo){let I=Ar[y]||{};T[y]={agentLimit:9999999999,tokenLimit:parseInt(I.tokenLimit,10)||0,monthlyTokenLimit:parseInt(I.monthlyTokenLimit,10)||0}}let h={...Ae,providerBudgets:T};Ft(h),Dt({apiTier:Je,quotas:h}),Y(yo==="settings"?"resetMode":"budgetResetMode")}else uo(u=>Math.min(f-1,u+1));return}else if(n.escape){Y("providerBudgetSelect");return}return}if(n.escape){if(ri){if(si(!1),xt.length>0){let a=xt[xt.length-1];a&&(li.current=a.id)}return}if(He.length>0&&at==="chat"){K(!0);return}if(x){S(!1);return}if(nn||Rt||Co||Xo)Kr.current=!0,$i(),Ii(),Co&&(Co.resolve("deny"),on(null)),Xo&&(Xo.resolve(null),Gr(null)),Hl(!1),ei&&clearTimeout(ei);else if(at==="revert")Y("chat"),vn(0);else if(at!=="chat"&&at!=="settings")Y("chat");else{if(!bt&&ct===1){Pt(0),Qo("");return}vn(a=>{let f=a+1;return f===1?(_o.current&&clearTimeout(_o.current),_o.current=setTimeout(()=>vn(0),2e3)):f===2&&(_o.current&&clearTimeout(_o.current),vn(0),D.length>0?m(""):Ln.getChatHistory(et).then(u=>{u.length>0?(oi(u.reverse()),Y("revert")):N(T=>(V(T.length+1),[...T,{id:"revert-empty-"+Date.now(),role:"system",text:`\u2726 Nothing to revert to.
66
- \u2800`,isMeta:!0}]))})),f})}}if(He.length>0&&at==="chat"){if(n.upArrow){fe(a=>{let f=a>0?a-1:He.length-1,u=0;for(;f!==a&&u<He.length;){let T=He[f],h=T?.cmd||T||"";if(typeof h=="string"&&h.trimStart().startsWith("---"))f=f>0?f-1:He.length-1,u++;else break}return f});return}if(n.downArrow){fe(a=>{let f=a<He.length-1?a+1:0,u=0;for(;f!==a&&u<He.length;){let T=He[f],h=T?.cmd||T||"";if(typeof h=="string"&&h.trimStart().startsWith("---"))f=f<He.length-1?f+1:0,u++;else break}return f});return}if(n.return)return}if(n.tab&&at==="chat"){if(He.length>0){let a=He[ae]||He[0],f=D.split(" ");if(f.length===1)m(a.cmd+" ");else{let u=f.slice(0,-1);m(u.join(" ")+" "+a.cmd+" ")}fe(0),M(u=>u+1);return}else if(D.trim()===""){let a=Date.now();if(a-he.current<500)return;he.current=a;let f=["Flux","Flow","ICU","FluxCU"],u=(f.indexOf(v)+1)%f.length,T=f[u>=0?u:0];k(T),T==="Flow"?_e("Fast"):(T==="Flux"||T==="ICU"||T==="FluxCU")&&_e("High"),N(h=>[...h,{id:Date.now(),role:"system",text:`\u2726 Mode switched to ${Ds(T)}
67
- \u2800`,isMeta:!0}]);return}}if(n.ctrl&&o==="c"&&at!=="exit"){if(D.length>0){m("");return}if(n.shift){Y("exit"),S(!1);return}x?(Y("exit"),S(!1)):S(!0)}n.return&&(n.shift||n.ctrl||n.meta||n.leftAlt||n.rightAlt)&&m(a=>a.replace(/\\\r?$/,"").replace(/\r?$/,"")+`
68
- `)}}),Qe(()=>{process.stdout.write("\x1B[?1004h");let o=n=>{let a=n.toString();a.includes("\x1B[I")?(jt(!0),We.current=Date.now()):a.includes("\x1B[O")&&(jt(!1),We.current=Date.now())};return process.stdin.on("data",o),()=>{process.stdout.write("\x1B[?1004l"),process.stdin.off("data",o)}},[]);let er=Ve(ce.theme);Qe(()=>{er.current&&er.current!==ce.theme?(er.current=ce.theme,i&&(i.write("\x1B[2J\x1B[3J\x1B[H"),i.isTTY&&i.write("\x1B[?2004h")),zr(o=>o+1),ho()):er.current=ce.theme},[ce.theme,i]),Qe(()=>{async function o(){try{let I=JSON.parse(lt.readFileSync(It.join(process.cwd(),"package.json"),"utf8"));as(oo||I.version||"2.0.0")}catch{as("2.0.0")}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),al()||(N(I=>(V(I.length+1),[...I,{id:"setup-"+Date.now(),role:"system",text:"\u2726 Installing Required dependencies... (One-time setup)",isMeta:!0}])),await dl(),N(I=>(V(I.length+1),[...I,{id:"setup-done-"+Date.now(),role:"system",text:`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m All dependencies installed successfully.
69
- \u2800`,isMeta:!0}]))),await pi();let n=await ts();_r.current=n.systemSettings?.allowExternalAccess??!1,Hr.current=n.systemSettings?.memory??!0,De.mode?k(De.mode):k(n.mode),L(n.display??0),De.thinking?_e(De.thinking):_e(n.thinkingLevel);let a=De.provider||n.aiProvider||"Google";Mt(a);let u=(n.quotas?.providerTiers||{})[a]||n.apiTier||"Free";if(Te.current=n.activeModel,De.model)ie(De.model);else if(De.provider){let I=no(a,u);ie(I)}else ie(n.activeModel);Er(n.showFullThinking),Fo(u),Ft(n.quotas||{limitMode:"Daily",agentLimit:99999999,tokenLimit:99999999999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0,providerBudgets:{}});let T={memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:"",...n.systemSettings||{}};De.memory==="on"?T.memory=!0:De.memory==="off"&&(T.memory=!1),a==="NVIDIA"&&process.env.NVIDIA_BASE_URL&&(T.memory=!1,N(I=>[...I,{role:"system",text:`\u2726 MEMORY
70
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Currently not available.
71
- \u2800`,isMeta:!0}])),De.package&&(T.updateManager=De.package),De.autoDel&&(T.autoDeleteHistory=De.autoDel),De.autoExec==="on"?T.autoExec=!0:De.autoExec==="off"&&(T.autoExec=!1),De.externalAccess==="on"?T.allowExternalAccess=!0:De.externalAccess==="off"&&(T.allowExternalAccess=!1),De.playground&&(T.allowExternalAccess=!1,T.memory=!1),Bt(T),Os(n.profileData),Yn(n.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""});let h=De.key;if(h||(h=await ln(a)),h&&(Kt(h),On(h,{aiProvider:a,onIDEApproval:Zn})),n.systemSettings?.autoDeleteHistory&&Ai(n.systemSettings.autoDeleteHistory),Li(ir),De.playground||(cr(Cn).catch(()=>{}),lt.remove(It.join(fo,"playground")).catch(()=>{})),oe(!1,T),await Promise.all([Si(),Ln.recoverCrashedTransaction()]),De.resume){let I=await ko(),_=De.resume;if(I[_]){Ho.current=!0,zn(_);let j=await ur(_);wn.current=Qt-j.total,Ho.current=!1,pn(j.total),Uo({tokens:j.context});let ue=[...I[_].messages];ue[0]?.text?.includes("\u2591\u2591\u2591\u2588\u2588\u2588")||ue.unshift({id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}),N(ue),Y("chat"),N(Me=>{let Oe=[...Me,{id:"sys-"+Date.now(),role:"system",text:`\u2726 SESSION RESUMED
72
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m '${_}'.
73
- \u2800`,isMeta:!0}];return V(Oe.length),Oe})}else N(j=>[...j,{id:"sys-err-"+Date.now(),role:"system",text:`\u2726 Chat session [${_}] not found. Started new session.
74
- \u2800`,isMeta:!0}])}if(De.playground){let I=It.join(fo,"playground");try{lt.ensureDirSync(I),process.chdir(I)}catch{}let _=await ko();if(_[Cn]){let j=[..._[Cn].messages];j[0]?.isLogo||j.unshift({id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}),N(j),N(ue=>{let z=[...ue,{id:"playground-"+Date.now(),role:"system",text:`\u2726 PLAYGROUND Session restored
75
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m CWD locked to: '${I}'.
76
- \u2800`,isMeta:!0}];return V(z.length),z})}else N(j=>{let ue=[...j,{id:"playground-"+Date.now(),role:"system",text:`\u2726 PLAYGROUND Mode active
77
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m CWD locked to: 'FluxFlow/playground'.
78
- \u2800`,isMeta:!0}];return V(ue.length),ue})}let d=Ko();if(!["Terminal","Windows Terminal"].includes(d)){let I=hl(d);if(I)try{let _=[];if(lt.existsSync(I)){let j=lt.readFileSync(I,"utf8").trim();j&&(_=xl(j))}Od(_)?Br="Shift + Enter":Y("keybindingsPrompt")}catch{}}Ze(!1)}o()},[]),Qe(()=>{let o;return x&&(p(10),o=setInterval(()=>{p(n=>n<=1?(S(!1),0):n-1)},1e3)),()=>{o&&clearInterval(o)}},[x]),Qe(()=>{if(!nt){let o=De.model&&ne===De.model?Te.current:ne,n=ce;De.playground&&(n={...ce,allowExternalAccess:_r.current,memory:Hr.current}),Dt({mode:v,thinkingLevel:me,aiProvider:H,activeModel:o||ne,showFullThinking:Ht,systemSettings:n,profileData:xn,imageSettings:So,apiTier:Je})}},[v,me,H,ne,Ht,ce,xn,So,nt,De,Je]);let di=async o=>{let n=o.trim(),a={Google:{prefix:"AIzaSy",minLength:39},OpenRouter:{prefix:"sk-or-v1-",minLength:73},DeepSeek:{prefix:"sk-",minLength:35},Mistral:{prefix:"",minLength:32},NVIDIA:{prefix:"nvapi-",minLength:70},Ollama:{prefix:"",minLength:0},CrofAI:{prefix:"",minLength:0},InferX:{prefix:"",minLength:0},SenseNova:{prefix:"",minLength:0},AIHubMix:{prefix:"sk-",minLength:10}},{prefix:f,minLength:u}=a[H]??{prefix:"",minLength:0},T=H==="Ollama"&&(n.trim()==="LOCAL"||n.trim()===""),h=T?"LOCAL":n;if(T||n.startsWith(f)&&n.length>=u){await es(H,h),Kt(h),On(h,{aiProvider:H,onIDEApproval:Zn});let d="gemma-4-31b-it";H==="OpenRouter"?d="google/gemma-4-31b-it:free":H==="DeepSeek"?d="deepseek-v4-flash":H==="NVIDIA"?d="deepseek-ai/deepseek-v4-flash":H==="Ollama"?d=ne||"":(H==="CrofAI"||H==="InferX"||H==="SenseNova"||H==="AIHubMix")&&(d=no(H,Je)||""),ie(d);let y={...ce};T&&(y={...y,ollamaEndpoint:"Local"},Bt(y)),(H==="Ollama"||H==="CrofAI"||H==="InferX"||H==="SenseNova"||H==="AIHubMix")&&(y={...y,memory:!1},Bt(y)),Dt({aiProvider:H,activeModel:d,systemSettings:y}),N(I=>[...I,{role:"system",text:`\u2726 ${H} API Key saved successfully! ${d?`
79
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Model set to ${d}.`:""}${T?`
80
- \u2726 Ollama Endpoint switched to Local.
81
- \u2514\u2500\u2800`:`
82
-
83
- \u2726\u2800`}${H==="Ollama"||H==="CrofAI"||H==="InferX"||H==="SenseNova"||H==="AIHubMix"?`Memory is not available with ${H}.
84
- \u2514\u2500\u2800`:""}Initialization complete.
85
- \u2800`,isMeta:!0}])}else N(d=>[...d,{role:"system",text:`\u2726 INVALID KEY
86
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${H} API key must start with "${f}" and be at least ${u} characters long.`,isMeta:!0}]),Qo("")},tr=Ve(vs);Qe(()=>{if(at==="exit"){(async()=>{let a=Date.now(),f=Math.floor((a-tr.current)/1e3);f>=1&&(await Yo("duration",f),tr.current+=f*1e3),await Ci()})();let n=setTimeout(()=>{process.exit(0)},200);return()=>clearTimeout(n)}},[at]),Qe(()=>{let o=setInterval(async()=>{if(!nt){let n=Date.now(),a=Math.floor((n-tr.current)/1e3);a>=1&&(await Yo("duration",a),tr.current+=a*1e3)}},5e3);return()=>clearInterval(o)},[nt]);let ci=[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},...De.playground?[{cmd:"/move",desc:"Move playground directory to original CWD/playground-export"}]:[],{cmd:"/resume",desc:"Load previous session"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/compress",desc:"Summarize and compress chat history"},{cmd:"/truncate",desc:"Truncate tool results in chat history"},{cmd:"/revert",desc:"Revert codebase back to a checkpoint"},{cmd:"/gemini",desc:"Get a happy message from Gemini CLI"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat or error logs",subs:[{cmd:"chat",desc:"Export current active chat"},{cmd:"logs",desc:"Export error logs"}]},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/btw",desc:"Ask a question without intefering with ongoing tasks"},{cmd:"/thinking",desc:"Set AI reasoning depth",subs:H==="Ollama"||H==="DeepSeek"?[{cmd:"Fast",desc:"Reasoning Disabled"},{cmd:"Standard",desc:"Standard Reasoning"},{cmd:"High",desc:"Extended Reasoning"}]:H==="NVIDIA"?[{cmd:"Fast",desc:"Reasoning Disabled"},{cmd:"Standard",desc:"Balanced Reasoning"},{cmd:"High",desc:"Extended Reasoning"}]:H==="OpenRouter"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Standard",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:H==="Mistral"?[{cmd:"Fast",desc:"Reasoning Disabled"},{cmd:"xHigh",desc:"Deep Reasoning"}]:ne&&(ne.toLowerCase().startsWith("gemini-3")||H==="CrofAI"||H==="InferX"||H==="SenseNova")?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Standard",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"}]:[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]},{cmd:"/model",desc:"Select Agent Model",subs:H==="Ollama"&&(bt==="LOCAL"||!bt)?[]:v==="ICU"||v.toLowerCase()==="fluxcu"?vo(H,Je).filter(o=>Ti(o.cmd||o)):vo(H,Je)},{cmd:"/wildcard-tooling",desc:"Use if the model lacks Tooling Capability"},{cmd:"/provider",desc:"Select AI Provider"},{cmd:"/mode",desc:"Switch execution mode",subs:[{cmd:"flux",display:"workspace",desc:"Workspace, files & terminal tools"},{cmd:"flow",display:"studio",desc:"Creative studio, documents, PDF & conversation"},{cmd:"icu",display:"computer use",desc:"Interactive desktop & OS automation"},{cmd:"fluxcu",display:"omni",desc:"Autonomous tools & desktop execution"}]},{cmd:"/display",desc:"Select Active Display (Computer Use)",subs:[{cmd:"primary",desc:"Primary Display (Display 1)"},{cmd:"secondary",desc:"Secondary Display (Display 2)"}]},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/theme",desc:"Customize UI color theme"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/usage",desc:"Open graphical token usage & analytics dashboard in browser"},{cmd:"/reset",desc:"Wipe all project data"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/docs",desc:"View Documentation"},{cmd:"/fluxflow",desc:"Project management",subs:[{cmd:"init",desc:"Create empty FluxFlow.md template"}]},{cmd:"/budget",desc:"Set or View budget limits",subs:[{cmd:"view",desc:"View current usage budget bars"},{cmd:"web",desc:"Open graphical usage and budget dashboard in browser"},{cmd:"set",desc:"Configure budgets (Daily/Monthly limits)"},{cmd:"reset",desc:"Reset budgets to default limits"}]},{cmd:"/update",desc:"Check/Install updates",subs:[{cmd:"latest",desc:"Install latest release"},{cmd:"check",desc:"Check for new version"}]}],ui=async(o,n=!1)=>{if(!n&&He.length>0){let u=He[ae]||He[0],T=o.split(" ");if(T.length===1)m(u.cmd+" ");else{let h=T.slice(0,-1);m(h.join(" ")+" "+u.cmd+" ")}fe(0),M(h=>h+1);return}Kr.current=!1;let a=o.replace(/\r\n/g,`
87
- `).replace(/\r/g,`
88
- `).trimEnd();if(a.endsWith("\\")){m(a.slice(0,-1)+`
89
- `);return}let f=a.replace(/\\\s*\n/g,`
90
- `).split(/\r?\n/).map(u=>u.replace(/\\$/,"")).join(`
91
- `);if(f.trim()){if(nn){let u=f.trim();if(u.startsWith("/btw")){if(u.replace(/^\/btw\s*/,"").trim().length<=3){N(h=>(V(h.length+1),[...h,{id:"hint-err-"+Date.now(),role:"system",text:`\u2726 RESTRICTED
92
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Inquiry question must be more than 3 characters.
93
- \u2800`,isMeta:!0}])),m("");return}}else if(u.startsWith("/")){N(T=>(V(T.length+1),[...T,{id:"hint-err-"+Date.now(),role:"system",text:`\u2726 RESTRICTED
94
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Steering Hints cannot start with '/'.
95
- \u2800`,isMeta:!0}])),m("");return}qr(u),Mo.current=u,N(T=>{V(T.length+1);let h=u.startsWith("/btw"),d=h?u.replace(/^\/btw\s*/,""):u,y=h?"[QUESTION]":"[STEERING HINT]";return[...T,{id:"hint-"+Date.now(),role:"user",text:`${y}
96
- ${d}`,color:"magenta"}]}),m("");return}if(!bt){di(f),Qo("");return}if(f.startsWith("/")){m("");let u=f.split(" "),T=u[0]?.toLowerCase();switch(T){case"/quit":{Y("exit");break}case"/resume":{if(u[1]){let h=u[1];(async()=>{let y=await ko(),I=y[h]||Object.values(y).find(_=>_.name.toLowerCase()===h.toLowerCase());if(I){if(i.write("\x1B[2J\x1B[3J\x1B[H"),process.stdout.isTTY){let z=I?.name||"",Me=z&&!z.startsWith("flow-")&&!z.startsWith("Session ")?z:"FluxFlow | Resumed";process.stdout.write(`\x1B]0;${Me}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${Me}\x07`)}ho(),Ho.current=!0,zn(h);let _=await ur(h);wn.current=Qt-_.total,Ho.current=!1,pn(_.total),Uo({tokens:_.context});let j=[...I.messages];j[0]?.text?.includes("\u2591\u2591\u2591\u2588\u2588\u2588")||j.unshift({id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}),N(j),N(z=>[...z,{id:"sys-"+Date.now(),role:"system",text:`\u2726 SESSION RESUMED
97
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${h}.
98
- \u2800`,isMeta:!0}]),V(0)}else N(_=>[..._,{id:"err-"+Date.now(),role:"system",text:`\u2726 ERROR: Session [${h}] not found.
99
- \u2800`,isMeta:!0}])})()}else Y("resume");break}case"/move":{if(!De.playground){N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 RESTRICTED
100
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m '/move' is only available in playground mode.
101
- \u2800`,isMeta:!0}]));break}if(!De.originalCwd){N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 RESTRICTED
102
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Original CWD not found.
103
- \u2800`,isMeta:!0}]));break}let h=It.join(fo,"playground"),d=It.join(De.originalCwd,"playground-export");(async()=>{try{N(_=>(V(_.length+1),[..._,{id:Date.now(),role:"system",text:`\u2726 EXPORTING PLAYGROUND CONTENT
104
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${d}
105
- `,isMeta:!0}])),await lt.ensureDir(d);let I=["node_modules",".git",".venv","venv","env",".next","dist","build",".cache"];await lt.copy(h,d,{overwrite:!0,filter:_=>{let j=It.relative(h,_);return j?!j.split(It.sep).some(z=>I.includes(z)):!0}}),N(_=>(V(_.length+1),[..._,{id:Date.now(),role:"system",text:`\u2726 SUCCESS
106
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m playground content copied to ${d}
107
- `,isMeta:!0}]))}catch(I){N(_=>(V(_.length+1),[..._,{id:Date.now(),role:"system",text:`\u2726 FAILED TO MOVE CONTENT
108
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${I.message}
109
- `,isMeta:!0}]))}})();break}case"/clear":{if(i&&(i.write("\x1B[2J\x1B[3J\x1B[H"),i.isTTY&&(i.write("\x1B[?2004h"),process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07"))),N([{id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}]),V(1),zr(h=>h+1),ho(),Wt.current={completedIndex:0,columns:$.columns,historicalBlocks:[],seenSelections:new Set,chatId:et,clearKey:Wo+1},De.playground){if(De.playground=!1,cr(Cn).catch(()=>{}),De.originalCwd)try{process.chdir(De.originalCwd),N(h=>{let d=[...h,{id:"playground-"+Date.now(),role:"system",text:`\u2726 PLAYGROUND
110
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Restored Working Directory to ${De.originalCwd}
111
- \u2800`,isMeta:!0}];return V(d.length),d})}catch{}setTimeout(()=>{lt.emptyDir(It.join(fo,"playground")).catch(h=>{N(d=>{let y=[...d,{id:"playground-"+Date.now(),role:"system",text:`\u2726 PLAYGROUND
112
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Failed to clear session: ${fo+"/playground"}`,isMeta:!0}];return V(y.length),y})})},500),Bt(h=>({...h,allowExternalAccess:_r.current,memory:Hr.current}))}zn(ls()),Uo({tokens:0}),E(!1),pn(0),wn.current=Qt,setTimeout(()=>{global.gc&&(async()=>{for(let d=0;d<3;d++)global.gc(),await new Promise(y=>setImmediate(y));g.current=Date.now()})()},500);break}case"/revert":{Ln.getChatHistory(et).then(h=>{if(h.length>0)oi(h.reverse()),Y("revert");else{let d=qe(2);N(y=>(V(y.length+1),[...y,{id:"revert-empty-"+Date.now(),role:"system",text:`\u2726 Nothing to revert to.
113
- \u2800`,isMeta:!0}]))}}),setTimeout(()=>{global.gc&&(async()=>{for(let d=0;d<3;d++)global.gc(),await new Promise(y=>setImmediate(y));g.current=Date.now()})()},500);break}case"/mode":{if(u[1]){let h=u[1].toLowerCase(),d="Flux";h==="flow"?d="Flow":h==="icu"?d="ICU":h==="fluxcu"?d="FluxCU":h==="flux"&&(d="Flux"),k(d),d==="Flow"&&_e("Fast");let y=qe(2);N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 Mode switched to ${Ds(d)}.
114
- \u2800`,isMeta:!0}]))}else Y("mode");break}case"/display":{if(u[1]){let h=u[1].toLowerCase(),d=0;h==="secondary"||h==="1"||h==="2"?d=1:d=0,L(d),Dt({display:d}).catch(()=>{});let y=d===0?"Primary (Display 1)":"Secondary (Display 2)";N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 Active Computer Use display set to: ${y}.
115
- \u2800`,isMeta:!0}]))}else Y("display");break}case"/image_deprecated":{if(u[1]?.toLowerCase()==="stats"){let h=qe(2);if(So.keyType==="Custom")N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:"[SYSTEM] Key strategy is Custom. Redirecting to Pollinations dashboard (https://enter.pollinations.ai/#pollen)...",isMeta:!0}])),Cr("start https://enter.pollinations.ai/#pollen");else try{let d=await Mi();N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",isImageStats:!0,text:`\u2022 Hourly Limit: ${Number((d.limit*1e3).toFixed(0))} credits
116
- \u2022 Spent (Last 1hr): ${Number((d.totalSpent*1e3).toFixed(0))} credits
117
- \u2022 Remaining: ${Number((d.remaining*1e3).toFixed(0))} credits
118
- \u2022 Requests (Last 1hr): ${d.activeCallsCount} requests
119
- `+(d.nextResetMin>0?`\u2022 Refreshes in: ${d.nextResetMin}m`:""),isMeta:!0}]))}catch{N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:"[SYSTEM] Failed to load image quota stats.",isMeta:!0}]))}}else if(u[1]?.toLowerCase()==="setup")if(u[2]?.toLowerCase()==="key")if(u[3]){let h=["default","custom"].find(d=>d===u[3].toLowerCase());if(h){let d=h==="default"?"Default":"Custom";Yn(I=>({...I,keyType:d}));let y=qe(2);N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`[SYSTEM] Image key strategy set to ${d}`,isMeta:!0}])),d==="Custom"&&(qt({label:"Enter Pollinations API key (starting with sk_):",note:"Get a key from https://enter.pollinations.ai",key:"imageSettings",subKey:"apiKey",value:So.apiKey||"",returnView:"chat"}),Y("input"))}else{let d=qe(2);N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:"[SYSTEM] Invalid key option. Choose: Default or Custom.",isMeta:!0}]))}}else{let h=qe(2);N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup Key <Default|Custom>",isMeta:!0}]))}else if(u[2]?.toLowerCase()==="quality")if(u[3]){let h=["low","low-high","medium","medium-high","high","ultra","premium"].find(d=>d===u[3].toLowerCase());if(h){let y={low:"Low","low-high":"Low-High",medium:"Medium","medium-high":"Medium-High",high:"High",ultra:"Ultra",premium:"Premium"}[h];Yn(_=>({..._,quality:y}));let I=qe(2);N(_=>(V(_.length+1),[..._,{id:Date.now(),role:"system",text:`[SYSTEM] Image quality set to ${y}`,isMeta:!0}]))}else{let d=qe(2);N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:"[SYSTEM] Invalid quality level. Choose from: Low, Low-High, Medium, Medium-High, High, Ultra, Premium.",isMeta:!0}]))}}else{let h=qe(2);N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup Quality <Low|Low-High|Medium|Medium-High|High|Ultra>",isMeta:!0}]))}else{let h=qe(2);N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}else{let h=qe(2);N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:"[SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}break}case"/thinking":{let h;if(u[1]){let d=u[1].toLowerCase(),y=u.includes("--bypass"),I=u.includes("--force");h=d.charAt(0).toUpperCase()+d.slice(1),d==="xhigh"&&(h="xHigh");let _="";if(I&&(process.env.NVIDIA_BASE_URL,_=`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Enabled Forced Reasoning.
120
- \u2800`,process.env.forcedReasoning="true"),!y&&v==="Flow"&&h==="xHigh")N(j=>(V(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u2726 RESTRICTED
121
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m"${h}" is restricted in Flow mode. Switch to Flux to enable Higher Thinking Levels.
122
- \u2800${_}.`,isMeta:!0}]));else{_e(h);let j=qe(1);N(ue=>(V(ue.length+1),[...ue,{id:Date.now(),role:"system",text:`\u2726 ${H}
123
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${ne}.
124
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Thinking Level: ${h}.
125
- ${_} \u2800`,isMeta:!0}]))}}else Y("thinking");break}case"/model":{if(u[1]){let h=u.slice(1),d=!1,y=!1,I=[];for(let j of h)j==="--multimodal"||j==="-m"?H==="Ollama"?d=!0:y=!0:I.push(j);let _=I.join(" ");if(H==="Ollama"&&wi(d),y&&N(j=>(V(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u2726 ERROR
126
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Flag --multimodal / -m is unavailable for provider "${H}". Flag ignored.
127
- \u2800`,isMeta:!0}])),_){let j=no("Google","Free"),ue=no("Google","Paid");ie(_),N(z=>(V(z.length+1),[...z,{id:Date.now(),role:"system",text:`\u2726 ${H}
128
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${_}
129
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Thinking Level: ${me}${H==="Ollama"?`
130
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Multimodal: ${d?"ON":"OFF"}`:""}
131
- \u2800`,isMeta:!0}]))}}else Y("model");break}case"/wildcard-tooling":{F(h=>{let d=!h;return N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 Wildcard Tooling:
132
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Status: ${d?"Enabled":"Disabled"}
133
- \u2800`,isMeta:!0}])),d});break}case"/settings":{Y("settings");break}case"/provider":case"/providers":{kr("chat"),Y("selectProvider");break}case"/theme":{Y("theme");break}case"/key":{Y("key");break}case"/profile":{Y("profile");break}case"/stats":{(async()=>{let d=await lr(),y=await ar();Nr(d),Fr(y),bn("daily"),Y("stats")})();break}case"/usage":{(async()=>{try{let{url:d}=await ns();N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 Launching Token Analytics Dashboard
134
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Serving at ${d}
135
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Opening in your default browser...
136
- \u2800`,isMeta:!0}]))}catch(d){N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 ERROR
137
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Failed to launch dashboard: ${d.message}
138
- \u2800`,isMeta:!0}]))}})();break}case"/save":{let h,d=xt.find(I=>I.role==="user");if(d&&d.text){let I=d.text.replace(/\s*\n+\s*\[Prompted on:.*?\]/g,"").trim(),_=I.split(/\s+/),j;_.length>7?j=_.slice(0,7).join(" ")+"...":I.length>45?j=I.substring(0,45).trimEnd()+"...":j=I,h=j}let y=u.slice(1).join(" ")||h||`Session ${new Date().toLocaleTimeString()}`;dn(et,y,xt),N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 Saved
139
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m "${y}" (ID: ${et})
140
- \u2800`,isMeta:!0}]));break}case"/export":{(async()=>{try{let d=await Bi(u,{chatId:et,messages:xt});N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:d.message,isMeta:!0}]))}catch(d){N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`[EXPORT ERROR] Failed to export: ${d.message}`,isMeta:!0}]))}})();break}case"/chats":{(async()=>{let d=await ko(),y=Object.entries(d).sort((I,_)=>(_[1].updatedAt||0)-(I[1].updatedAt||0)).map(([I,_])=>`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${I}: ${_.name}${I===et?" (current)":""}`).join(`
141
- `);N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 Saved Chats:
142
- ${y||"\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No saved chats found."}
143
- \u2800`,isMeta:!0}]))})();break}case"/memory":{Y("memory");break}case"/reset":{(async()=>{try{N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:`\u2726 Initiating reset...
144
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Clearing logs, secrets, and settings.
145
- \u2800`,isMeta:!0}])),lt.existsSync(ir)&&lt.removeSync(ir),lt.existsSync(Zr)&&lt.removeSync(Zr),lt.existsSync(kn)&&lt.removeSync(kn);try{lt.readdirSync(sn).length===0&&lt.removeSync(sn)}catch{}setTimeout(()=>{Y("exit"),setTimeout(()=>process.exit(0),500)},500)}catch(d){N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 ERROR
146
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Failed to clear data: ${d.message}.
147
- \u2800`}]))}})();break}case"/about":{let h=qe(2),d=`\u2022 FluxFlow Version: v${oo}
148
- \u2022 Status: ${Vt&&Vt!==oo?`Update Available [v${Vt}]`:"Up to date"}
149
- \u2022 Released on: ${Fd}`;N(y=>(V(y.length+1),[...y,{id:"about-"+Date.now(),role:"system",text:d,isAboutRecord:!0,isMeta:!0}]));break}case"/changelog":{let h=process.platform;Cr(`${h==="win32"?"start":h==="darwin"?"open":"xdg-open"} ${pl}`),N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 Opening Changelog
150
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${pl}.`,isMeta:!0}]));break}case"/docs":{if(!ks){N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 ERROR
151
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Documentation URL is not configured.`,isMeta:!0}]));break}let h=process.platform;Cr(`${h==="win32"?"start":h==="darwin"?"open":"xdg-open"} ${ks}`),N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 Opening Documentation
152
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${ks}.
153
- \u2800`,isMeta:!0}]));break}case"/budget":{let h=u[1]?.toLowerCase();if(h==="web"||h==="gui"||h==="dashboard")(async()=>{try{let{url:y}=await ns();N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 Token Usage & Budget Dashboard
154
- \u2800\u2800\u2514\u2500 Opened at ${y}
155
- \u2800`,isMeta:!0}]))}catch(y){N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:`\u2726 ERROR: Failed to launch dashboard: ${y.message}
156
- \u2800`,isMeta:!0}]))}})();else if(h==="set")bl("chat"),Y("budgetTypeSelect");else if(h==="view")(async()=>{let y=await lr(),I=await ar(),_=await os(Ae.resetDay||1);Nr(y),Fr(I),Gs(_),Y("budgetView")})();else if(h==="reset"){let d={limitMode:"Daily",agentLimit:99999999,tokenLimit:99999999999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0,providerBudgets:{},providerTiers:{Google:"Free",DeepSeek:"Free",NVIDIA:"Free",OpenRouter:"Free",CrofAI:"Free",InferX:"Free",SenseNova:"Free",AIHubMix:"Free"}};Ft(d),Fo("Free"),Dt({apiTier:"Free",quotas:d}),N(y=>(V(y.length+1),[...y,{id:Date.now(),role:"system",text:`\u2726 Budgets reset successfully.
157
- \u2800`,isMeta:!0}]))}else N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:`\u2726 ERROR
158
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Usage: /budget <View|Web|Set|Reset>.
159
- \u2800`,isMeta:!0}]));break}case"/fluxflow":{if(u.slice(1)[0]==="init"){let d=`# FluxFlow Configuration
160
- # This file defines project-specific instructions for the Flux Flow Agent.
161
-
162
- # IDENTITY & TONE
163
- - Tone: Technical, precise, and highly efficient.
164
-
165
- # PROJECT CONTEXT
166
- - Goal: [Describe your project goal here]
167
- - Tech Stack: [List your technologies here]
168
-
169
- # CUSTOM RULES
170
- - [Add specific coding standards or rules here]
171
-
172
- # SKILLS & WORKFLOWS
173
- - [Define custom step-by-step recipes for this project here]
174
- `,y=It.join(process.cwd(),"FluxFlow.md");if(lt.pathExistsSync(y))N(I=>(V(I.length+1),[...I,{id:"init-err-"+Date.now(),role:"system",text:"ERROR: FluxFlow.md already exists in this directory.",isMeta:!0}]));else try{lt.writeFileSync(y,d),N(I=>(V(I.length+1),[...I,{id:"init-ok-"+Date.now(),role:"system",text:"[SUCCESS] FluxFlow.md has been initialized. You can now customize it for this project.",isMeta:!0}]))}catch(I){N(_=>(V(_.length+1),[..._,{id:"init-err-"+Date.now(),role:"system",text:`ERROR: Failed to initialize FluxFlow.md: ${I.message}`,isMeta:!0}]))}}else N(d=>(V(d.length+1),[...d,{id:"ff-err-"+Date.now(),role:"system",text:"Usage: /fluxflow init",isMeta:!0}]));break}case"/update":{if(u[1]?.toLowerCase()==="check"){oe(!0);break}let d=u.includes("--latest");Y("update");break}case"/gemini":{let h=Ms[Math.floor(Math.random()*Ms.length)];N(d=>(V(d.length+1),[...d,{id:Date.now(),role:"system",text:`\u2728 GEMINI CLI
175
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${h}
176
- \u2800`}])),m("");break}case"/compress":{m("");let h=xt.filter(I=>(I.role==="user"||I.role==="agent"||I.role==="system")&&!String(I.id).startsWith("welcome")&&!I.isMeta).length,d=mo?.tokens||0;if(h<64||d<16384){let I=qe(2);N(_=>(V(_.length+1),[..._,{id:Date.now(),role:"system",text:`\u2726 Compression skipped
177
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m History requires at least 64 messages and 16k tokens
178
- \u2800\u2800 \u2514\u2500 Current: ${h}/64 msgs, ${d}/16384 tokens.
179
- \u2800`,isMeta:!0}]));break}(async()=>{Rs(!0);let I=qe(2);N(_=>(V(_.length+1),[..._,{id:Date.now(),role:"system",text:"\u2726 Compacting session history...",isMeta:!0}]));try{if(await Hi({chatId:et,aiProvider:H,apiKey:bt,thinkingLevel:me,mode:v,janitorModel:Ce,systemSettings:ce,sessionStats:mo},xt)){let ue=qe(2);N(z=>{let Me=[...z,{id:Date.now(),role:"system",text:`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Chat History compacted saving tokens.
180
- \u2800`,isMeta:!0}];return V(Me.length),Me})}else N(ue=>(V(ue.length+1),[...ue,{id:Date.now(),role:"system",text:`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Compaction failed.
181
- \u2800`,isMeta:!0}]))}catch(_){N(j=>(V(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Error during compaction: ${_.message}
182
- \u2800`,isMeta:!0}]))}finally{Rs(!1)}})();break}case"/truncate":{m("");let h=0;N(d=>{let I=[...d.map(_=>{let j=_.fullText||_.text||"";return!j.startsWith("[TOOL RESULT]:")||j.startsWith("[TOOL RESULT]: ERROR")||j.startsWith("[TOOL RESULT]: DENIED")||j.includes("...SUCCESS Results Truncated by System on User Command")||j.startsWith("[TOOL RESULT]: Skill:")||j.includes("Skill: [")?_:(h++,j.startsWith("[TOOL RESULT]: SUCCESS")?{..._,fullText:"[TOOL RESULT]: SUCCESS: ...SUCCESS Results Truncated by System on User Command"}:{..._,fullText:"[TOOL RESULT]: ...SUCCESS Results Truncated by System on User Command"})}),{id:Date.now(),role:"system",text:`\u2726 Tool Truncation...
183
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Truncated ${h} tool result(s).
184
- \u2800`,isMeta:!0}];return dn(et,null,I),V(I.length),I});break}case"/help":{N(h=>(V(h.length+1),[...h,{id:Date.now(),role:"system",isHelpRecord:!0,isMeta:!0}]));break}case"/btw":{N(h=>(V(h.length+1),[...h,{id:Date.now(),role:"system",text:`\u2726 RESTRICTED
185
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m '/btw' only available when agent is working
186
- \u2800`,isMeta:!0}]));break}default:N(h=>(V(h.length+1),[...h,{id:Date.now(),role:"system",text:`\u2726 ERROR
187
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Unknown command: '${T}'
188
- \u2800`,isMeta:!0}]))}}else{let u=`[Prompted on: ${new Date().toLocaleString(void 0,{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"})}]`,T={id:"user-"+Date.now(),role:"user",text:`${f}
189
-
190
- ${u}`};N(d=>(V(d.length+1),[...d,T])),(async()=>{let d=!1,y=()=>{d||(d=!0,N(ue=>{let z=ue[ue.length-1];if(z&&z.text&&z.text.includes("Request Cancelled"))return ue;let Oe=[...ue.map(J=>J.isStreaming?{...J,isStreaming:!1}:J),{id:"cancel-"+Date.now(),role:"agent",text:`
191
-
192
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`,isMeta:!1}];return V(Oe.length),Oe}))},I=!1;jr(!0),Or(Date.now()),E(!1);let _=Date.now(),j=!0;try{let ue=[...xt,T].filter(U=>U.role!=="think"&&!U.isVisualFeedback&&!U.isMeta&&!U.isTerminalRecord&&!(U.text&&U.text.includes("[TERMINAL_RECORD]"))&&!String(U.id).startsWith("welcome")),z=[],Me=ue.map((U,xe)=>{let Be=U.fullText||U.text||"";if(U.role==="user"&&xe<ue.length-1)if(Be.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let we=Be.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(we!==-1){let Ke=Be.substring(0,we).lastIndexOf("[SYSTEM METADATA]");Ke!==-1?Be=Be.substring(Ke).trim():Be=Be.substring(we).trim()}}else{let we=Be.lastIndexOf("[USER]"),Ge=Be.lastIndexOf("[USER PROMPT]");we!==-1?Be=Be.substring(we+6).trim():Ge!==-1&&(Be=Be.substring(Ge).trim())}return{...U,text:Be}}),Oe=0;for(;Oe<Me.length;){let U=Me[Oe];if(U.role==="user")z.push(U),Oe++;else{let xe=[];for(;Oe<Me.length&&Me[Oe].role!=="user";)xe.push(Me[Oe]),Oe++;let Be=[],we=[],Ge=null,Ke=!1,Ut=()=>{Be.length>0&&(z.push({role:"agent",text:Be.join(`
193
- `).trim()}),Be=[]),we.length>0&&(z.push({role:"system",text:we.join(`
194
-
195
- `),...Ge?{binaryPart:Ge}:{}}),we=[],Ge=null),Ke=!1};xe.forEach(it=>{let Go=it.role==="system"&&(it.text?.startsWith("[TOOL RESULT]")||it.text?.startsWith("SUCCESS:")||it.text?.startsWith("ERROR:")||it.fullText?.startsWith("[TOOL RESULT]")||it.fullText?.startsWith("SUCCESS:")||it.fullText?.startsWith("ERROR:")),pe=it.fullText||it.text||"",ge=pe.trim();if(!(!ge&&!it.binaryPart)){if(Go){let Ne=ge.startsWith("[TOOL RESULT]")?ge:`[TOOL RESULT]: ${ge}`;we.push(Ne),it.binaryPart&&(Ge=it.binaryPart)}else if(it.role==="agent"){!Ke&&we.length>0&&Ut();let Ne=pe.endsWith(`
196
- `),Ye=ge.toLowerCase().includes("tool:functions.")||ge.toLowerCase().includes("agent:generalist.");Be.push(ge),Ye&&Ne?Ke=!0:Ke=!1}}}),Ut()}}let J=Gi(ne,z,{profile:xn,thinkingLevel:me,mode:v,systemSettings:ce,janitorModel:Ce,sessionStats:mo,chatId:et,isPlayground:!!De.playground,aiProvider:H,apiKey:bt,apiTier:Je,wildcardTooling:b,cols:$.columns-6,rows:30,onTokenChunk:(U,xe)=>{let Be=Date.now();if(Or(Be),typeof xe=="number"){Ns.current=xe;let we=Pr.current;we.startTime||(we.startTime=Be,we.totalWords=0,we.chunks=[]),we.totalWords+=xe,we.chunks||(we.chunks=[]),we.chunks.push({time:Be,words:xe});let Ke=Be-400;if(we.chunks=we.chunks.filter(Ut=>Ut.time>=Ke),we.chunks.length>0){let Ut=we.chunks.reduce((pe,ge)=>pe+ge.words,0),it=we.chunks[0].time,Go=Math.max(.4,(Be-it)/1e3);we.wps=Math.round(Ut/Go*10)/10}}},onVisualFeedback:U=>{N(xe=>[...xe.map(we=>we.isStreaming?{...we,isStreaming:!1}:we),{id:"visual-"+Date.now()+"-"+Math.random().toString(36).substring(2,9),role:"system",text:U,isVisualFeedback:!0}])},onSubagentUpdate:()=>{Ol(Xi.map(U=>({...U})))},onExecStart:U=>{ve(),Se(),Ys(U),tn("")},onExecChunk:U=>{tn(xe=>xe+U)},onExecEnd:()=>{N(U=>{if(!Jn.current)return U;let xe=Wr.current||"",Be=ki(xe),we=`[TERMINAL_RECORD]
197
- COMMAND: ${Jn.current}
198
- PTY: ${an}
199
- OUTPUT: ${Be.replace(/\n{3,}/g,`
200
-
201
- `)}`,Ke=[...U.map(Ut=>Ut.isStreaming?{...Ut,isStreaming:!1}:Ut),{id:"term-"+Date.now(),role:"system",text:we,isTerminalRecord:!0}];return V(Ke.length),Ke}),Ys(null),Vs(!1),tn(""),Jn.current=null,Wr.current=""},onToolResult:(U,xe)=>{if(U==="success"){if(Bl(Be=>Be+1),xe==="generate_image"){Il(Ge=>Ge+1);let we={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[So.quality]||.002;Al(Ge=>Ge+we)}}else U==="denied"?Dl(Be=>Be+1):El(Be=>Be+1)},onToolApproval:async(U,xe)=>{let Be=Nl||ce.autoExec;if(U==="exec_command"){let{command:we}=An(xe||"{}");return Be||we&&/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i.test(we.trim())?"allow":new Promise(Ke=>{on({tool:U,args:xe,resolve:Ke}),Y("terminalApproval")})}return Be?"allow":new Promise(we=>{on({tool:U,args:xe,resolve:we}),Y("approval")})},onAskUser:async(U,xe)=>(ve(),Se(),new Promise(Be=>{let we=!1;Gr({question:U,options:xe,resolve:Ge=>{we||(we=!0,N(Ke=>{if(Ke.some(Go=>Go.isAskRecord&&Go.text?.includes(`Selection: ${Ge}`)))return Ke;let it=[...Ke,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
202
- Question: ${U}
203
- Selection: ${Ge}`,isAskRecord:!0}];return V(it.length),it}),Be(Ge))}}),Y("ask")})),onUsage:U=>{let xe=U.totalTokenCount||0,Be=U.cachedContentTokenCount||0,we=U.candidatesTokenCount||0;Uo({tokens:xe}),$s(Ge=>Ge+xe),Be>0&&_s(Ge=>Ge+Be),we>0&&Hs(Ge=>Ge+we),Us(Ge=>Ge+1)}},async()=>{if(Mo.current){let U=Mo.current;return qr(null),Mo.current=null,N(xe=>{let Be=[...xe].reverse().findIndex(we=>we.text?.includes("[STEERING HINT: QUEUED]")||we.text?.includes("[QUESTION: QUEUED]"));if(Be!==-1){let we=xe.length-1-Be,Ge=[...xe],Ke=Ge[we].text;return Ke.includes("[STEERING HINT: QUEUED]")?Ke=Ke.replace("[STEERING HINT: QUEUED]","[STEERING HINT: INJECTED]"):Ke.includes("[QUESTION: QUEUED]")&&(Ke=Ke.replace("[QUESTION: QUEUED]","[QUESTION: ASKED]")),Ge[we]={...Ge[we],text:Ke,color:"cyan"},Ge}return xe}),U}return null},oo),le=!1,rt=null,Ue=null,Xe=!1,tt=!1,At=!1,st=!1,ht=0,Et=null,Eo=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let U of J){if(await new Promise(pe=>setTimeout(pe,3)),U.type==="text"&&Or(Date.now()),j&&U.type==="text"&&(_=Date.now(),j=!1,ce.progressiveRendering&&Ie()),U.type==="status"){U.content?.includes("[start]")||Yr(U.content),U.content?.includes("[start]")?(clearInterval(Dn),En(0),Dn=setInterval(()=>{En(pe=>pe+1)},1e3)):U.content?.includes("[end]")&&(En(0),clearInterval(Dn)),Vo()&&mr(U.content),U.content==="Request Cancelled"&&(ve(),Se(),y());continue}if(U.type==="status_history"){Yr(U.content),Vo()&&mr(U.content),N(pe=>[...pe,{id:"condense-"+Date.now(),role:"system",text:`\u2726 ${U.content}
204
- \u2800`,isMeta:!0}]);continue}if(U.type==="summary_injected"){N(pe=>pe.map(ge=>ge.id===U.content.id?{...ge,fullText:U.content.text}:ge));continue}if(U.type==="spinner"){$l(U.content);continue}if(U.type==="model_update"){Yl(U.content);continue}if(U.type==="turn_reset"){if(ve(),Se(),rt=null,Ue=null,le=!1,Xe=!1,tt=!1,st=!1,At=!1,N(pe=>{let ge=pe.map(Ne=>{if(Ne.isStreaming){let Ye=Ne.text?ut(Ne.text):Ne.text,Xt=Ne.fullText?ut(Ne.fullText):Ne.fullText;return{...Ne,isStreaming:!1,text:Ye,fullText:Xt}}return Ne});return V(ge.length),ge}),ho(),global.gc){for(let pe=0;pe<2;pe++)global.gc(),await new Promise(ge=>setImmediate(ge));g.current=Date.now()}continue}if(U.type==="interactive_turn_finished"){jr(!1),En(0),clearInterval(Dn),Vo()&&mr(null),I=!0,ho(),ce?.autoTruncateResults&&N(pe=>{let ge=pe.map(Ne=>{let Ye=Ne.fullText||Ne.text||"";return!Ye.startsWith("[TOOL RESULT]:")||Ye.startsWith("[TOOL RESULT]: ERROR")||Ye.startsWith("[TOOL RESULT]: DENIED")||Ye.includes("...SUCCESS Results Truncated by System on User Command")||Ye.startsWith("[TOOL RESULT]: Skill:")||Ye.includes("Skill: [")?Ne:Ye.startsWith("[TOOL RESULT]: SUCCESS")?{...Ne,fullText:"[TOOL RESULT]: SUCCESS: ...SUCCESS Results Truncated by System on User Command"}:{...Ne,fullText:"[TOOL RESULT]: ...SUCCESS Results Truncated by System on User Command"}});return dn(et,null,ge),V(ge.length),ge}),_i({profile:xn,thinkingLevel:me,mode:v,janitorModel:Ce,chatId:et,systemSettings:ce,sessionStats:mo,aiProvider:H,apiKey:bt},U.data.agentText,U.data.fullAgentTextRaw,U.data.history,{onMemoryUpdated:()=>N(pe=>{let ge=[...pe];return ge.length>0&&(ge[ge.length-1].memoryUpdated=!0),ge}),onBackgroundIncrement:()=>Cl(pe=>pe+1)});continue}if(U.type==="visual_feedback"){ve(),Se(),N(pe=>{let ge=[...pe,{id:"feedback-"+Date.now()+"-"+Math.random().toString(36).substring(2,9),role:"system",text:ut(U.content),isVisualFeedback:!0}];return V(ge.length),ge});continue}if(U.type==="exec_start"){ve(),Se();continue}if(U.type==="liveTokens"){Uo({tokens:U.content});continue}if(U.type==="usage"){let pe=U.content.totalTokenCount||0,ge=U.content.cachedContentTokenCount||0,Ne=U.content.candidatesTokenCount||0;Uo({tokens:pe}),$s(Ye=>Ye+pe),ge>0&&_s(Ye=>Ye+ge),Ne>0&&Hs(Ye=>Ye+Ne),Us(Ye=>Ye+1);continue}if(U.type==="tool_time"){kl(pe=>pe+U.content);continue}if(U.type==="tool_result"){if(Se(),N(pe=>{let ge=[...pe,{id:"tool-"+Date.now()+"-"+Math.random().toString(36).substring(2,7),role:"system",text:ut(U.content),fullText:ut(U.aiContent),binaryPart:U.binaryPart,toolName:U.toolName}];return V(ge.length),ge}),U.toolName==="update_file"&&U.aiContent){let pe=U.aiContent.split(`
205
- `),ge=0,Ne=0,Ye=!1;for(let Xt of pe){if(Xt.includes("[DIFF_START]")){Ye=!0;continue}if(Xt.includes("[DIFF_END]")){Ye=!1;continue}Ye&&(/^\+\d+/.test(Xt)?ge++:/^\-\d+/.test(Xt)&&Ne++)}Yo("linesAdded",ge),Yo("linesRemoved",Ne)}else if(U.toolName==="write_file"&&U.aiContent){let pe=U.aiContent.match(/- Stats: \[(\d+) lines/),ge=pe?parseInt(pe[1]):0,Ne=0;if(U.aiContent.includes("Old File contents:")){let Ye=U.aiContent.split(`
206
- `),Xt=!1;for(let go of Ye){if(go.includes("Old File contents:")){Xt=!0;continue}Xt&&(go.trim()===""?Xt=!1:/^\d+ \|/.test(go)&&Ne++)}}Yo("linesAdded",ge),Yo("linesRemoved",Ne)}continue}let xe=U.content;if(U.type==="text"&&xe.includes("Request Cancelled")){if(global.gc){for(let pe=0;pe<3;pe++)global.gc(),await new Promise(ge=>setImmediate(ge));g.current=Date.now()}continue}let Be=xe.toLowerCase();if(xe.includes("```")&&(Xe=!Xe),(Be.includes("tool:functions.")||Be.includes("agent:generalist."))&&(tt=!0,ht=0,Et=null,(xe.includes("[tool:functions.")||xe.includes("[agent:generalist."))&&(ht=0)),tt){for(let pe=0;pe<xe.length;pe++){let ge=xe[pe];!Et&&(ge==="'"||ge==='"'||ge==="`")?Et=ge:Et&&ge===Et&&xe[pe-1]!=="\\"&&(Et=null),Et||(ge==="("||ge==="["?ht++:(ge===")"||ge==="]")&&ht--)}ht<=0&&!Et&&(tt=!1)}let we=/^\s*(?:<(think|thought|thoughts)[^>]*>|<\|channel>thought|\[(think|thought|thoughts)\])/i,Ge=(pe,ge)=>{let Ne=!1;for(let Ye=0;Ye<ge;Ye++)pe[Ye]==="`"&&(Ne=!Ne);return Ne},Ke=pe=>{let ge=/(?:<\/(think|thought|thoughts)>|<channel\|>|\[\/(think|thought|thoughts)\])/gi,Ne;for(;(Ne=ge.exec(pe))!==null;)if(!(Xe||Ge(pe,Ne.index)))return{index:Ne.index,length:Ne[0].length};return{index:-1,length:0}},Ut=G.current?.role==="agent"&&G.current.text||"",it=Ut+xe;if(!le&&!At&&it.trim().length>0&&!we.test(it)&&(At=!0),!le&&!Xe&&!tt&&!At&&(we.test(xe)||we.test(it))){let pe=we.test(it)?it:xe,ge=pe===it&&Ut.length>0,Ne=pe.match(we),Ye=Ne.index,Xt=Ne[0].length,go=pe.substring(0,Ye),rr=pe.substring(Ye+Xt);go&&go.trim()?(ge&&G.current?G.current.text=ut(go):!G.current||G.current.role!=="agent"?G.current={id:"agent-"+Date.now(),role:"agent",text:ut(go),isStreaming:!0}:G.current.text=ut(G.current.text+go),ve(),Se()):(ve(),G.current=null),le=!0,At=!0,rt="think-"+Date.now(),G.current={id:rt,role:"think",text:"",isStreaming:!0,startTime:Date.now()};let sr=Ke(rr);if(sr.index!==-1){let Ql=rr.substring(0,sr.index).replace(/^\r?\n+/,"").replace(/\r?\n+$/,""),gi=rr.substring(sr.index+sr.length);G.current.text=ut(Ql);let zl=G.current.startTime||Date.now();G.current.duration=Date.now()-zl,Se(),le=!1,Ue="agent-"+Date.now(),G.current={id:Ue,role:"agent",text:"",isStreaming:!0},gi&&ot(gi)}else{let Jr=rr.replace(/^\r?\n+/,"");Jr&&ot(Jr)}continue}if(le&&G.current?.role==="think"){ve();let pe=G.current.text+xe,ge=Ke(pe);if(ge.index!==-1){let Ne=pe.substring(0,ge.index),Ye=pe.substring(ge.index+ge.length);G.current.text=ut(Ne);let Xt=G.current.startTime||Date.now();G.current.duration=Date.now()-Xt,Se(),le=!1,Ue="agent-"+Date.now(),G.current={id:Ue,role:"agent",text:"",isStreaming:!0},Ye&&ot(Ye)}else ot(xe);continue}else if(!le){let pe=xe.toLowerCase();!st&&(pe.includes("tool:functions.")||pe.includes("agent:generalist."))&&(st=!0),!G.current||G.current.role!=="agent"?(Ue="agent-"+Date.now(),G.current={id:Ue,role:"agent",text:ut(xe),isStreaming:!0},ee()):ot(xe)}}let Do=Date.now();vl(U=>U+(Do-_))}catch(ue){N(z=>(V(z.length+1),[...z,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${ue.message}`}]))}finally{let ue=Date.now()-_;if(G.current&&(G.current.workedDuration=ue),be.current&&(await Re(),clearInterval(be.current),be.current=null),jr(!1),Yr(null),En(0),clearInterval(Dn),Se(),Kr.current&&y(),ho(),global.gc)try{for(let z=0;z<3;z++)global.gc(),await new Promise(Me=>setImmediate(Me));g.current=Date.now()}catch{}if(I||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),Mo.current){Qr(Mo.current),qr(null);let z=Mo.current;Mo.current=null,N(Me=>{let Oe=[...Me],J=Oe.reverse().find(le=>le.text?.includes("[STEERING HINT: QUEUED]")||le.text?.includes("[QUESTION: QUEUED]"));return J&&(J.text.includes("[STEERING HINT: QUEUED]")?J.text=J.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]"):J.text.includes("[QUESTION: QUEUED]")&&(J.text=J.text.replace("[QUESTION: QUEUED]","[QUESTION: FINISHED_TURN]"))),Oe.reverse()}),Y("resolution")}N(z=>{let Me=Date.now()-_,Oe=!1,J=[...z].reverse().map(Ue=>{let Xe=Ue.isStreaming?{...Ue,isStreaming:!1}:Ue;return Xe.text&&(Xe.text=(" "+Xe.text).slice(1)),!Oe&&Xe.role==="agent"&&(Oe=!0,Xe={...Xe,workedDuration:Me}),Xe}).reverse();if(!J.some(Ue=>Ue.role==="agent"&&Ue.text?.trim().length>0)){let Ue=[...J].reverse().find(Xe=>Xe.role==="think"&&Xe.text?.trim().length>0);Ue&&J.push({id:"agent-fallback-"+Date.now(),role:"agent",text:Ue.text,isStreaming:!1,workedDuration:Me})}let rt=J.filter(Ue=>!String(Ue.id).startsWith("welcome")&&(!Ue.isMeta||Ue.text&&Ue.text.includes("Request Cancelled")));return dn(et,null,rt),V(J.length),J})}})()}m(""),E(!1)}},He=fn(()=>{if(D.startsWith("/")&&!Q){let u=D.split(" "),T=u[u.length-1].toLowerCase();if(u.length===1){let d=T.startsWith("/")?T.slice(1):T;return ci.filter(y=>(y.cmd.startsWith("/")?y.cmd.slice(1):y.cmd).toLowerCase().includes(d))}let h=ci;for(let d=0;d<u.length-1;d++){let y=u[d].toLowerCase(),I=h.find(_=>_.cmd.toLowerCase()===y);if(I&&I.subs)h=I.subs;else return[]}return h.filter(d=>d.cmd.toLowerCase().includes(T))}let o=D.split(" "),n=o[o.length-1],a=n&&n.startsWith("\\@");if((n&&n.startsWith("@")||a)&&!Q){let u=n.indexOf("#"),T=u!==-1,h=a?2:1,d=T?n.substring(h,u).toLowerCase():n.slice(h).toLowerCase(),y=T?n.substring(u):"";return Xd(process.cwd()).filter(j=>j.name.toLowerCase().includes(d)).map(j=>{let ue=j.relativePath.replace(/\\/g,"/"),z=ue.startsWith(".")?ue:"./"+ue;return{cmd:(a?"\\@":"@")+"["+z+y+"]",desc:j.relativePath}})}return[]},[D,Q]);Qe(()=>{let o=0;for(;o<He.length;){let n=He[o],a=n?.cmd||n||"";if(typeof a=="string"&&a.trimStart().startsWith("---"))o++;else break}fe(o<He.length?o:0)},[He]);let[or,nr]=q(0),mi=Ve(0);Qe(()=>{let o=mi.current>0,n=He.length>0;if(mi.current=He.length,!n){nr(0);return}if(!o){nr(1);return}nr(He.length)},[He]),Qe(()=>{if(or>0&&or<He.length){let o=setTimeout(()=>{nr(n=>Math.min(n+1,He.length))},5);return()=>clearTimeout(o)}},[or,He.length]),Qe(()=>{if(at!=="providerBudgetSelect")return;let o=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","CrofAI","InferX","SenseNova","AIHubMix"],n=Ae.providerBudgets||{},a=o.reduce((f,u)=>(f[u]=!!(n[u]&&(n[u].agentLimit||n[u].tokenLimit)),f),{});Ls(a),Wn(0)},[at]),Qe(()=>{if(at!=="providerBudgetFlow")return;let o={},n=Ae.providerBudgets||{};for(let a of Jo){let f=n[a]||{};o[a]={agentLimit:hn(f.agentLimit),tokenLimit:hn(f.tokenLimit),monthlyTokenLimit:hn(f.monthlyTokenLimit)}}Lr(o),uo(0)},[at,Jo]);let Rd=({label:o,isSelected:n})=>{let a=o==="Cancel"||o==="Back"||o.toLowerCase().includes("exit")||o.toLowerCase().includes("back");return e.createElement(c,{marginTop:a?1:0,backgroundColor:n?"#2a2a2a":void 0,paddingX:1,width:"100%"},e.createElement(s,{color:n?"white":"gray",bold:n},n?"\u276F ":" ",o))},rn=(o,n,a,f=10,u=2,T=9)=>{let h=a>0?Math.min(100,n/a*100):0,d=Math.round(h),y=Math.round(d/100*f),I="\u2588".repeat(y)+"\u2591".repeat(Math.max(0,f-y)),_=l.success||"green";d>=40&&d<=80?_=l.warning||"yellow":d>80&&(_=l.danger||"red");let j=o.toLowerCase().includes("token")||o.toLowerCase().includes("daily")||o.toLowerCase().includes("monthly"),ue=Hn(a)?"\u221E":j?mt(a):a,z=j?mt(n):n,Me;return h===0?Me="0%":h>0&&h<1?Me="<1%":Me=`${d}%`,e.createElement(c,{flexDirection:"row",paddingLeft:u,key:o},e.createElement(c,{width:T},e.createElement(s,{color:l.textMuted},o,": ")),e.createElement(s,{color:_},I),e.createElement(s,{color:l.textMuted}," ",Me," (",z,"/",ue,")"))},ql=()=>{switch(at){case"settings":return e.createElement(Tr,{systemSettings:ce,setSystemSettings:Bt,apiTier:Je,setActiveView:Y,setInputConfig:qt,saveSettings:Dt,quotas:Ae,setMessages:N,aiProvider:H,setProviderReturnView:kr});case"theme":return e.createElement(Tr,{systemSettings:ce,setSystemSettings:Bt,apiTier:Je,setActiveView:Y,setInputConfig:qt,saveSettings:Dt,quotas:Ae,setMessages:N,aiProvider:H,initialSelectingTheme:!0,onCloseTheme:()=>Y("chat"),setProviderReturnView:kr});case"selectProvider":return e.createElement(ft,{title:"SELECT AI PROVIDER",searchable:!0,items:[{label:"Google",value:"Google"},{label:"Nvidia",value:"NVIDIA"},{label:"DeepSeek",value:"DeepSeek"},{label:"InferX",value:"InferX"},{label:"SenseNova",value:"SenseNova"},{label:"CrofAI",value:"CrofAI"},{label:"Ollama",value:"Ollama"},{label:"AIHubMix [EXPERIMENTAL]",value:"AIHubMix"},{label:"Mistral [EXPERIMENTAL]",value:"Mistral"},{label:"OpenRouter [EXPERIMENTAL]",value:"OpenRouter"},{label:"Back",value:zo}],theme:ce.theme,onSelect:async o=>{if(o.value===zo||o.value==="settings"||o.value==="Back"){Y(zo);return}let n=o.value,a=await ln(n);if(a){Mt(n),Kt(a),On(a,{aiProvider:n,onIDEApproval:Zn});let f=(Ae.providerTiers||{})[n]||"Free",u=no(n,f);ie(u),Fo(f),n==="NVIDIA"&&process.env.NVIDIA_BASE_URL||n==="Ollama"||n==="CrofAI"||n==="InferX"||n==="SenseNova"?(Bt(T=>({...T,memory:!1})),Dt({aiProvider:n,activeModel:u,apiTier:f,quotas:Ae,systemSettings:{...ce,memory:!1}})):Dt({aiProvider:n,activeModel:u,apiTier:f,quotas:Ae}),N(T=>[...T,{role:"system",text:`\u2726 Switched to ${n} (cached)!${u?`
207
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Model: ${u}.`:""}${(n==="Ollama"||n==="CrofAI"||n==="InferX"||n==="SenseNova"||n==="AIHubMix")&&ce.memory?`
208
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available with ${n}.`:""}${n==="NVIDIA"&&process.env.NVIDIA_BASE_URL&&ce.memory?`
209
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available with Custom Endpoints.`:""}
210
- \u2800`,isMeta:!0}]),Y(zo)}else qt({label:`Enter ${n} API Key:`,key:"providerKey",provider:n,value:"",returnView:zo}),Y("input")},onClose:()=>Y(zo)});case"apiTier":return e.createElement(ft,{title:`Show Paid models from ${H.toUpperCase()}?`,subtitle:"Curated model list. Can use anything if typed manually.",items:[{label:"No (For Free APIs) [Shows Free model list]",value:"Free"},{label:`Yes (For Billing APIs) [Shows Paid model list] ${Je==="Paid"?"\u25CF":""}`,value:"Paid"},{label:"Back",value:"settings"}],theme:ce.theme,onSelect:o=>{if(o.value==="settings"||o.value==="Back"){Y("settings");return}let n=o.value;Fo(n);let a={...Ae.providerTiers||{},[H]:n},f={...Ae,providerTiers:a};Ft(f),Dt({apiTier:n,quotas:f}),Y("settings")}});case"resetMode":return e.createElement(ft,{title:"SELECT MONTHLY RESET MODE",items:[{label:"Default (Rolling 30-Day Window)",value:"Rolling"},{label:"Custom (Set reset day of month)",value:"Custom"},{label:"Back",value:"apiTier"}],theme:ce.theme,onSelect:o=>{if(o.value==="apiTier"||o.value==="Back"){Y("apiTier");return}let n=o.value,a={...Ae,resetMode:n};Ft(a),n==="Custom"?(qt({label:"Enter monthly reset day (1-30):",key:"quotas",subKey:"resetDay",value:String(Ae.resetDay||1),returnView:"settings"}),Y("input")):(Dt({apiTier:Je,quotas:a}),Y("settings"))},onClose:()=>Y("apiTier")});case"budgetTypeSelect":return e.createElement(ft,{title:"SELECT BUDGET TYPE",items:[{label:`Global Budget (single limit for all providers) ${Je==="Paid"&&!Ae.providerBudgets?.__useProvider?"\u25CF":""}`,value:"global"},{label:`Provider Budgets (set limits per provider individually) ${Ae.providerBudgets?.__useProvider?"\u25CF":""}`,value:"provider"},{label:"Back",value:yo}],theme:ce.theme,onSelect:o=>{if(o.value===yo||o.value==="Back"){Y(yo);return}if(o.value==="global"){let n={...Ae,agentLimit:99999999,tokenLimit:99999999999999,monthlyTokenLimit:99999999999999,providerBudgets:{__useProvider:!1}};Ft(n);let a=yo==="settings"?"resetMode":"budgetResetMode";qt({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:hn(n.agentLimit),returnView:yo,next:f=>({label:"Enter Agent daily budget (tokens used):",key:"quotas",subKey:"tokenLimit",value:hn(f.tokenLimit),returnView:yo,next:u=>({label:"Enter Agent monthly budget (tokens used):",key:"quotas",subKey:"monthlyTokenLimit",value:hn(u.monthlyTokenLimit),returnView:a})})}),Y("input")}else if(o.value==="provider"){let n={...Ae,agentLimit:99999999,tokenLimit:99999999999999,monthlyTokenLimit:99999999999999,providerBudgets:{...Ae.providerBudgets||{},__useProvider:!0}};Ft(n),Y("providerBudgetSelect")}},onClose:()=>Y(yo)});case"providerBudgetSelect":{let o=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","CrofAI","InferX","SenseNova"],n=o.some(a=>Ir[a]);return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,padding:0,width:"100%"},e.createElement(c,{paddingX:1,marginBottom:1},e.createElement(s,{color:l.text,bold:!0},"SELECT PROVIDERS TO SET LIMMITS FOR")),o.map((a,f)=>{let u=f===As,T=!!Ir[a];return e.createElement(c,{key:a,backgroundColor:u?l.highlightBg||"#2a2a2a":void 0,paddingX:1,width:"100%",flexDirection:"row"},e.createElement(s,{color:u?l.text:l.textMuted,bold:u},u?"\u276F ":" "),e.createElement(s,{color:T?l.success||"green":l.textMuted},T?"\u2611":"\u2610"),e.createElement(s,{color:u?l.text:l.textMuted,bold:u}," ",a),T&&Ae.providerBudgets?.[a]?.agentLimit?e.createElement(s,{color:l.primary||"cyan"}," (budget set)"):null)}),e.createElement(c,{paddingX:1,marginTop:1,flexDirection:"column"},e.createElement(s,{color:l.textMuted,italic:!0},"\u2191\u2193 Navigate \u2022 Space to toggle \u2022 Enter to confirm \u2022 ESC to go back"),!n&&e.createElement(s,{color:l.warning||"yellow",italic:!0}," Select at least one provider to continue")))}case"providerBudgetFlow":{let o=Jo.length,n=o*2;return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,padding:0,width:"100%"},e.createElement(c,{paddingX:1,marginBottom:0,justifyContent:"space-between",flexDirection:"row"},e.createElement(s,{color:l.text,bold:!0},"PROVIDER BUDGET CONFIGURATION"),e.createElement(s,{color:l.textMuted,italic:!0},"(0 or blank = unlimited)")),e.createElement(c,{paddingX:1,marginTop:1,flexDirection:"row"},e.createElement(c,{width:14},e.createElement(s,{color:l.textMuted,bold:!0},"PROVIDER")),e.createElement(c,{width:30,paddingLeft:1},e.createElement(s,{color:l.textMuted,bold:!0},"DAILY TOKENS (/day)")),e.createElement(c,{width:30,paddingLeft:1},e.createElement(s,{color:l.textMuted,bold:!0},"MONTHLY TOKENS (/month)"))),e.createElement(c,{paddingX:1},e.createElement(s,{color:l.borderMuted},"\u2500".repeat(74))),Jo.map((a,f)=>{let u=f*2,T=f*2+1,h=Gn===u,d=Gn===T,y=h||d,I=Ar[a]?.tokenLimit??"",_=Ar[a]?.monthlyTokenLimit??"";return e.createElement(c,{key:a,flexDirection:"row",paddingX:1,marginY:0,backgroundColor:y?l.highlightBg||"#2a2a2a":void 0},e.createElement(c,{width:14,flexDirection:"row"},e.createElement(s,{color:y?l.primary||"cyan":l.text,bold:y},y?"\u276F ":" ",a)),e.createElement(c,{width:30,paddingLeft:1,flexDirection:"row"},h?e.createElement(c,{flexDirection:"row"},e.createElement(s,{color:l.primary||"cyan",bold:!0},"[ "),e.createElement(Mr,{value:I,onChange:j=>{Lr(ue=>({...ue,[a]:{...ue[a]||{},tokenLimit:j}}))},onSubmit:()=>{uo(T)}}),e.createElement(s,{color:l.primary||"cyan",bold:!0}," ]")):e.createElement(s,{color:I?l.text:l.textMuted},"[ ",I||"0 (Unlimited)"," ]")),e.createElement(c,{width:30,paddingLeft:1,flexDirection:"row"},d?e.createElement(c,{flexDirection:"row"},e.createElement(s,{color:l.primary||"cyan",bold:!0},"[ "),e.createElement(Mr,{value:_,onChange:j=>{Lr(ue=>({...ue,[a]:{...ue[a]||{},monthlyTokenLimit:j}}))},onSubmit:()=>{f+1<o?uo((f+1)*2):uo(n)}}),e.createElement(s,{color:l.primary||"cyan",bold:!0}," ]")):e.createElement(s,{color:_?l.text:l.textMuted},"[ ",_||"0 (Unlimited)"," ]")))}),e.createElement(c,{paddingX:1,marginTop:1},Gn===n?e.createElement(c,{backgroundColor:l.highlightBg||"#2a2a2a",paddingX:1},e.createElement(s,{color:l.success||"green",bold:!0},"\u276F [ Save & Apply Budgets ]")):e.createElement(s,{color:l.textMuted}," [ Save & Apply Budgets ]")),e.createElement(c,{paddingX:1,marginTop:1,flexDirection:"column"},e.createElement(s,{color:l.textMuted,italic:!0},"\u2191\u2193/\u2190\u2192 Navigate \u2022 Enter next / save \u2022 ESC to go back")))}case"budgetResetMode":return e.createElement(ft,{title:"SELECT MONTHLY RESET MODE",items:[{label:"Default (Rolling 30-Day Window)",value:"Rolling"},{label:"Custom (Set reset day of month)",value:"Custom"},{label:"Back",value:"chat"}],theme:ce.theme,onSelect:o=>{if(o.value==="chat"||o.value==="Back"){Y("chat");return}let n=o.value,a={...Ae,resetMode:n};Ft(a),n==="Custom"?(qt({label:"Enter monthly reset day (1-30):",key:"quotas",subKey:"resetDay",value:String(Ae.resetDay||1),returnView:"chat"}),Y("input")):(Dt({apiTier:Je,quotas:a}),Y("chat"))},onClose:()=>Y("chat")});case"budgetView":{let o=Tn?.agent||0,n=Ae.agentLimit||99999999,a=Tn?.tokens||0,f=Ae.tokenLimit||99999999999999,u=Ae.resetMode==="Custom"?Ur?.tokens||0:Qn?.tokens||0,T=Ae.monthlyTokenLimit||99999999999999,h=Je!=="Paid",d=!!Ae.providerBudgets?.__useProvider,y=Ae.providerBudgets||{},I=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","CrofAI","InferX","SenseNova"].filter(z=>y[z]&&(y[z].agentLimit||y[z].tokenLimit||y[z].monthlyTokenLimit)),_=!d&&(Hn(n)||Hn(f)||Hn(T)),j="",ue="";if(Ae.resetMode==="Custom"){let z=new Date,Me=Ae.resetDay||1,Oe=z.getFullYear(),J=z.getMonth();z.getDate()>=Me&&(J+=1,J>11&&(J=0,Oe+=1));let le=new Date(Oe,J,Me,0,0,0);j=`${le.toLocaleString("default",{month:"short"}).toUpperCase()}-${Me}`;let Ue=Math.max(0,le.getTime()-z.getTime()),Xe=Math.floor(Ue/(1e3*60*60)),tt=Math.floor(Xe/24),At=Xe%24;ue=`(${tt} days: ${At} hrs left)`}return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,padding:1,paddingBottom:0,paddingTop:0,width:"100%"},e.createElement(c,{marginBottom:1,justifyContent:"space-between",width:"100%"},e.createElement(s,{color:l.text,bold:!0,underline:!0},"USAGE LIMITS"),e.createElement(s,{color:l.textMuted},"[ ESC to Close ]")),_?e.createElement(c,{padding:1,justifyContent:"center",alignItems:"center",width:"100%"},e.createElement(s,{color:l.text,bold:!0},"LIMITS NOT SET")):d&&I.length>0?e.createElement(c,{flexDirection:"column",gap:0,width:"100%"},(()=>{let z=i?.columns||$?.columns||80;if(z<115){let J=Math.max(5,Math.min(30,z-50));return I.map(le=>{let rt=y[le],Ue=0,Xe=Tn?.models?.[le]||{};for(let ht in Xe)Ue+=Xe[ht]?.tokens||0;let tt=0,st=(Ae.resetMode==="Custom"?Ur:Qn)?.models?.[le]||{};for(let ht in st)tt+=st[ht]?.tokens||0;return e.createElement(c,{key:le,flexDirection:"column",borderStyle:"single",borderColor:l.borderMuted,paddingX:1,width:"100%"},e.createElement(c,{marginBottom:0},e.createElement(s,{color:l.primary,bold:!0},"\u25C6 ",le)),rn("Daily",Ue,rt.tokenLimit||99999999999999,J,2,9),rn("Monthly",tt,rt.monthlyTokenLimit||99999999999999,J,2,9))})}let Oe=[];for(let J=0;J<I.length;J+=2)Oe.push(I.slice(J,J+2));return Oe.map((J,le)=>e.createElement(c,{key:le,flexDirection:"row",width:"100%"},J.map(rt=>{let Ue=y[rt],Xe=0,tt=Tn?.models?.[rt]||{};for(let U in tt)Xe+=tt[U]?.tokens||0;let At=0,ht=(Ae.resetMode==="Custom"?Ur:Qn)?.models?.[rt]||{};for(let U in ht)At+=ht[U]?.tokens||0;let Et=J.length===1,Eo=Et?z:Math.floor(z/2),Do=Math.max(5,Math.min(25,Eo-36));return e.createElement(c,{key:rt,flexDirection:"column",borderStyle:"single",borderColor:l.borderMuted,paddingX:1,width:Et?"100%":"50%"},e.createElement(c,{marginBottom:0},e.createElement(s,{color:l.primary,bold:!0},"\u25C6 ",rt)),rn("Daily",Xe,Ue.tokenLimit||99999999999999,Do,2,9),rn("Monthly",At,Ue.monthlyTokenLimit||99999999999999,Do,2,9))})))})(),j?e.createElement(c,{marginLeft:2,marginTop:1},e.createElement(s,{color:l.textMuted},"Monthly Reset: "),e.createElement(s,{color:l.accent||"magenta",bold:!0},j),ue?e.createElement(s,{color:l.textMuted},` ${ue}`):null):e.createElement(c,{marginLeft:2,marginTop:1},e.createElement(s,{color:l.textMuted},"Monthly Reset: "),e.createElement(s,{color:l.secondary||"blue",bold:!0},"Rolling 30-Day Window"))):e.createElement(c,{flexDirection:"column",borderStyle:"single",borderColor:l.borderMuted,paddingX:1,width:"100%"},rn("Daily Tokens",a,f,"green"),rn("Monthly Tokens",u,T,"yellow"),j?e.createElement(c,{marginLeft:4,marginTop:1},e.createElement(s,{color:l.textMuted},"Monthly Reset: "),e.createElement(s,{color:l.accent||"magenta",bold:!0},j),ue?e.createElement(s,{color:l.textMuted},` ${ue}`):null):e.createElement(c,{marginLeft:4,marginTop:1},e.createElement(s,{color:l.textMuted},"Monthly Reset: "),e.createElement(s,{color:l.secondary||"blue",bold:!0},"Rolling 30-Day Window"))))}case"input":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,padding:0,width:"100%"},e.createElement(c,{paddingX:1},e.createElement(s,{color:l.text,bold:!0},"DATA CONFIGURATION")),bo?.note&&e.createElement(c,{paddingX:1,marginBottom:1},e.createElement(s,{color:l.textMuted,italic:!0},bo.note)),e.createElement(c,{paddingX:1,flexDirection:"row"},e.createElement(s,{color:l.text,bold:!0},bo?.label," "),e.createElement(Mr,{value:bo?.value||"",onChange:o=>qt(n=>({...n,value:o})),onSubmit:async o=>{let{key:n,subKey:a,next:f,onDone:u}=bo,T={...Ae},h={};if(n==="quotas"){let d=a.toLowerCase().includes("limit")||a==="resetDay"?parseInt(o)||0:o;a==="resetDay"&&(d=Math.max(1,Math.min(30,d))),T[a]=d,Ft(T),h.quotas=T}else if(n==="providerBudgets"){let d=bo.providerKey,y=a.toLowerCase().includes("limit")?parseInt(o)||0:o,I=T.providerBudgets||{};T.providerBudgets={...I,[d]:{...I[d]||{},[a]:y}},Ft(T),h.quotas=T}else if(n==="activeModel")ie(o),h.activeModel=o;else if(n==="janitorModel")$e(o),h.janitorModel=o;else if(n==="autoApproveCommands"||n==="autoDisallowCommands"||n==="alwaysAskCommands"){let d={...ce,[n]:o.trim(),sandboxPreset:"Custom"};Bt(d),h.systemSettings=d}else if(n==="externalDataPath"){let d={...ce,useExternalData:!0,externalDataPath:o.trim()};Bt(d),h.systemSettings=d,N(y=>[...y,{id:Date.now(),role:"system",text:"[EXTERNAL STORAGE] Flux Flow will use "+o.trim()+" for data after restart."}])}else if(n==="imageSettings"){let d=o.trim();if(d.startsWith("sk_")){let y={...So,apiKey:d};Yn(y),h.imageSettings=y,N(I=>(V(I.length+1),[...I,{id:Date.now(),role:"system",text:"[IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}}else if(n==="providerKey"){let d=o.trim(),y=bo.provider;y==="Ollama"&&(d==="LOCAL"||d==="")&&(d="LOCAL",Bt(j=>({...j,ollamaEndpoint:"Local"})),h.systemSettings={...ce,ollamaEndpoint:"Local"}),await es(y,d),Mt(y),Kt(d),On(d,{aiProvider:y,onIDEApproval:Zn});let I=(Ae.providerTiers||{})[y]||"Free",_=no(y,I);ie(_),Fo(I),h.aiProvider=y,h.activeModel=_,h.apiTier=I,(y==="NVIDIA"&&process.env.NVIDIA_BASE_URL||y==="Ollama"||y==="CrofAI"||y==="InferX"||y==="SenseNova")&&(Bt(j=>({...j,memory:!1})),h.systemSettings={...ce,memory:!1}),N(j=>(V(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u2726 ${y} API Key saved successfully! ${_?`
211
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Model: ${_}`:""}${y==="Ollama"&&d==="LOCAL"?`
212
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Ollama Endpoint automatically switched to Local`:""}${y==="Ollama"||y==="CrofAI"||y==="InferX"||y==="SenseNova"?`
213
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available with ${y}`:""}${y==="NVIDIA"&&process.env.NVIDIA_BASE_URL?`
214
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available`:""}
215
- \u2800\u2800`,isMeta:!0}]))}if(f){let d=f(n==="quotas"||n==="providerBudgets"?T:o);qt(d)}else u?(Dt({...h,apiTier:Je,quotas:T,imageSettings:h.imageSettings||So}),qt(null),u(T)):(Dt({...h,apiTier:Je,quotas:T,imageSettings:h.imageSettings||So}),qt(null),Y(bo?.returnView||"settings"))}})),e.createElement(c,{paddingX:1,marginTop:1},e.createElement(s,{color:l.textMuted,dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":{let o=Ro==="modelBreakdown"||Ro==="dailyModelBreakdown",n=Ro==="daily"||Ro==="dailyModelBreakdown",a=n?Tn:Qn,f=n?"TODAY's USAGE":"LAST 30 DAYS USAGE",u=n?"TODAY'S MODEL TOKEN BREAKDOWN":"30-DAY MODEL TOKEN BREAKDOWN",T="Wall Time:",h="Tokens Used:",d="Images Made:",y="Image Credits:",I="Code Changes:",_="Tool Calls:",j=Math.max(4,(i?.rows||$?.rows||24)-15),ue=(Ue,Xe,tt,At,st,ht=0,Et=!1)=>{let Eo=i?.columns||$?.columns||80,Do=Math.min(125,Eo-2),U=Math.max(20,Do-6),xe=Math.max(5,U-ht-tt.length-5),Be=Xe;Be.length>xe&&(Be=Be.substring(0,xe-1)+"\u2026");let we=Math.max(2,U-ht-Be.length-tt.length-2),Ge=" "+".".repeat(we)+" ",Ke=" ".repeat(ht);return e.createElement(c,{key:Ue,width:U},e.createElement(s,{wrap:"truncate"},e.createElement(s,null,Ke),e.createElement(s,{color:At,bold:Et},Be),e.createElement(s,{color:l.textMuted,dimColor:!0},Ge),e.createElement(s,{color:st,bold:Et},tt)))},z=[],Me=a?.models;if(!Me||Object.keys(Me).length===0)z.push(e.createElement(c,{key:"empty",marginTop:1},e.createElement(s,{color:l.textMuted,italic:!0},"No model token usage recorded for ",n?"today":"the last 30 days",".")));else{let Ue=(yn||"").trim(),Xe="",tt="";if(Ue.includes(":")){let st=Ue.indexOf(":");Xe=Ue.substring(0,st).trim().toLowerCase(),tt=Ue.substring(st+1).trim().toLowerCase()}else Xe=Ue.toLowerCase();let At=Object.entries(Me).sort(([st],[ht])=>st.localeCompare(ht,void 0,{sensitivity:"base"})).filter(([st,ht])=>Xe&&!st.toLowerCase().includes(Xe)?!1:tt?Object.keys(ht).some(Et=>Et.toLowerCase().includes(tt)):!0);At.length===0?z.push(e.createElement(c,{key:"no-matches",marginTop:1},e.createElement(s,{color:l.textMuted,italic:!0},'No results found matching "',yn,'".'))):At.forEach(([st,ht],Et)=>{let Eo=Object.entries(ht).sort(([U],[xe])=>U.localeCompare(xe,void 0,{sensitivity:"base"})).filter(([U])=>!tt||U.toLowerCase().includes(tt));if(Eo.length===0)return;let Do=Eo.reduce((U,[,xe])=>U+(xe.tokens||0),0);Et>0&&z.length>0&&z.push(e.createElement(c,{key:`space-prov-${st}`},e.createElement(s,null," "))),z.push(ue(`prov-${st}`,`${st}:`,mt(Do),l.primary,l.text,0,!0)),Eo.forEach(([U,xe],Be)=>{Be>0&&z.push(e.createElement(c,{key:`space-mod-${st}-${U}`},e.createElement(s,null," "))),z.push(ue(`mod-${st}-${U}`,`\xBB ${U}:`,mt(xe.tokens||0),l.secondary,l.text,2,!0)),z.push(ue(`in-${st}-${U}`,"\xBB Input Tokens:",mt((xe.tokens||0)-(xe.candidateTokens||0)),l.textMuted,l.text,5,!1)),(xe.cachedTokens||0)>0&&z.push(ue(`cache-${st}-${U}`,"\xBB Cached:",mt(xe.cachedTokens),l.textMuted,l.text,7,!1)),z.push(ue(`out-${st}-${U}`,"\xBB Output Tokens:",mt(xe.candidateTokens||0),l.textMuted,l.text,5,!1))})})}let Oe=z.length,J=Math.max(0,Oe-j);Pe.current=J;let le=Math.min(Ll,J),rt=z.slice(le,le+j);return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:3,paddingY:1,paddingBottom:0,width:Math.min(125,(i?.columns||100)-2)},o?e.createElement(c,{flexDirection:"column"},e.createElement(c,{justifyContent:"space-between"},e.createElement(s,{color:l.text,bold:!0,underline:!0},u),Oe>j&&e.createElement(s,{color:l.textMuted,dimColor:!0},"[",le+1,"-",Math.min(Oe,le+j)," of ",Oe,"] \u25B2\u25BC")),e.createElement(c,{marginTop:1},e.createElement(s,{color:l.secondary,bold:!0},"Filter (provider:model): "),e.createElement(s,{color:l.text},yn),e.createElement(s,{color:l.primary,bold:!0},"\u258A"),yn.length>0&&e.createElement(s,{color:l.textMuted,dimColor:!0,italic:!0}," (Type to search, Esc/Backspace to clear)")),e.createElement(c,{flexDirection:"column",height:j,marginTop:1},rt)):e.createElement(e.Fragment,null,e.createElement(c,{marginBottom:1},e.createElement(s,{color:l.text,bold:!0,underline:!0},"SESSION TELEMETRY")),e.createElement(c,{flexDirection:"column"},e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Session Duration:")),e.createElement(s,{color:l.text},$o(Date.now()-vs))),Fs>0&&e.createElement(e.Fragment,null,e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Model Requests:")),e.createElement(s,{color:l.text},Fs)),e.createElement(c,{marginLeft:2},e.createElement(c,{width:23},e.createElement(s,{color:l.textMuted},"\xBB API Time:")),e.createElement(s,{color:l.text},$o(jn))),e.createElement(c,{marginLeft:2},e.createElement(c,{width:23},e.createElement(s,{color:l.textMuted},"\xBB Tool Time:")),e.createElement(s,{color:l.text},$o(Kn)))),Xs>0&&e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Memory Agent:")),e.createElement(s,{color:l.text},Xs)),Qt>0&&e.createElement(e.Fragment,null,e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Tokens Consumed:")),e.createElement(s,{color:l.text},mt(Qt))),e.createElement(c,{marginLeft:2},e.createElement(c,{width:23},e.createElement(s,{color:l.textMuted},"\xBB Input Tokens:")),e.createElement(s,{color:l.text},mt(Qt-Zo))),Vn>0&&e.createElement(c,{marginLeft:4},e.createElement(c,{width:21},e.createElement(s,{color:l.textMuted},"\xBB Cached:")),e.createElement(s,{color:l.text},mt(Vn))),Zo>0&&e.createElement(c,{marginLeft:2},e.createElement(c,{width:23},e.createElement(s,{color:l.textMuted},"\xBB Output Tokens:")),e.createElement(s,{color:l.text},mt(Zo)))),mo?.tokens>0&&e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Active Context:")),e.createElement(s,{color:l.text},mt(mo.tokens))),qn>0&&e.createElement(e.Fragment,null,e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Images Made:")),e.createElement(s,{color:l.text},qn)),e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Image Credits:")),e.createElement(s,{color:l.text},Number(((Ws||0)*1e3).toFixed(0))," credits"))),e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Code Changes (Sess):")),e.createElement(s,{color:l.text},e.createElement(s,{color:l.success||"green"},"+",yt.linesAdded)," ",e.createElement(s,{color:l.danger||"red"},"-",yt.linesRemoved))),e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Tool Calls (Sess):")),e.createElement(s,{color:l.text},yt.toolSuccess+yt.toolFailure+yt.toolDenied," ( "),e.createElement(s,{color:l.success||"green"},"\u2714 ",yt.toolSuccess),e.createElement(s,{color:l.text}," "),e.createElement(s,{color:l.warning||"yellow"},"\u{1F6C7} ",yt.toolDenied),e.createElement(s,{color:l.text}," "),e.createElement(s,{color:l.danger||"red"},"\u2718 ",yt.toolFailure),e.createElement(s,{color:l.text}," )"))),e.createElement(c,{flexDirection:"column",marginTop:1},e.createElement(s,{color:l.text,bold:!0,underline:!0},f),e.createElement(c,{marginTop:1},e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},T)),e.createElement(s,{color:l.text},zs(a?.duration||0))),(a?.agent||0)>0&&e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Model Requests:")),e.createElement(s,{color:l.text},a?.agent||0)),(a?.background||0)>0&&e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},"Memory Agent:")),e.createElement(s,{color:l.text},a?.background||0)),(a?.tokens||0)>0&&e.createElement(e.Fragment,null,e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},h)),e.createElement(s,{color:l.text},mt(a?.tokens||0))),e.createElement(c,{marginLeft:2},e.createElement(c,{width:23},e.createElement(s,{color:l.textMuted},"\xBB Input Tokens:")),e.createElement(s,{color:l.text},mt((a?.tokens||0)-(a?.candidateTokens||0)))),(a?.cachedTokens||0)>0&&e.createElement(c,{marginLeft:4},e.createElement(c,{width:21},e.createElement(s,{color:l.textMuted},"\xBB Cached:")),e.createElement(s,{color:l.text},mt(a.cachedTokens))),(a?.candidateTokens||0)>0&&e.createElement(c,{marginLeft:2},e.createElement(c,{width:23},e.createElement(s,{color:l.textMuted},"\xBB Output Tokens:")),e.createElement(s,{color:l.text},mt(a.candidateTokens)))),(a?.imageCalls?.length||0)>0&&e.createElement(e.Fragment,null,e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},d)),e.createElement(s,{color:l.text},a.imageCalls.length)),e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},y)),e.createElement(s,{color:l.text},Number(((a.imageCalls.reduce((Ue,Xe)=>Ue+Xe.cost,0)||0)*1e3).toFixed(0))," credits"))),e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},I)),e.createElement(s,{color:l.text},e.createElement(s,{color:l.success||"green"},"+",a?.linesAdded||0)," ",e.createElement(s,{color:l.danger||"red"},"-",a?.linesRemoved||0))),e.createElement(c,null,e.createElement(c,{width:25},e.createElement(s,{color:l.secondary},_)),e.createElement(s,{color:l.text},(a?.toolSuccess||0)+(a?.toolFailure||0)+(a?.toolDenied||0)," ( "),e.createElement(s,{color:l.success||"green"},"\u2714 ",a?.toolSuccess||0),e.createElement(s,{color:l.text}," "),e.createElement(s,{color:l.warning||"yellow"},"\u{1F6C7} ",a?.toolDenied||0),e.createElement(s,{color:l.text}," "),e.createElement(s,{color:l.danger||"red"},"\u2718 ",a?.toolFailure||0),e.createElement(s,{color:l.text}," )")))),e.createElement(s,{color:l.textMuted,dimColor:!0,italic:!0},`
216
- `,"(Press TAB to toggle Today/30-Day views, SPACE to toggle Model Breakdown, ESC to return)"))}case"dynamicDirDanger":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:l.warning||"yellow",bold:!0,underline:!0},"DYNAMIC DIRECTORY AWARENESS"),e.createElement(s,{marginTop:1,color:l.text},"Enabling this keeps the agent aware of filesystem state in real time, but may reduce prompt cache efficiency."),e.createElement(s,{color:l.text},`
217
- `,"RECOMMENDED SCENARIOS TO TURN ON:"),e.createElement(s,{color:l.textMuted},"\u2022 Repo is small."),e.createElement(s,{color:l.textMuted},"\u2022 The task benefits from real-time filesystem awareness."),e.createElement(s,{color:l.textMuted},"\u2022 Files are often created, renamed, or deleted."),e.createElement(s,{color:l.textMuted},"\u2022 You know exactly what you're signing up for."),e.createElement(s,{color:l.textMuted},"\u2022 You don't have conflicting decisions regarding token bills."),e.createElement(s,{color:l.textMuted},"\u2022 You want to see your wallet crying at 3am."),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Confirm Intent",theme:ce.theme,items:[{label:"Turn On Dynamic Directory Awareness",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:o=>{o.value==="on"&&Bt(n=>{let a={...n,dynamicDirAwareness:!0};return Dt({systemSettings:a,apiTier:Je,quotas:Ae}),a}),Y("settings")}})));case"dynamicDirHelp":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:l.text,bold:!0,underline:!0},"DYNAMIC DIRECTORY AWARENESS \u2014 HELP & EXPLANATION"),e.createElement(s,{color:l.text,bold:!0},`
218
- `,"OFF (Default):"),e.createElement(s,{color:l.textMuted},"\u2022 Takes a static directory snapshot at conversation/session start and places it in System Context."),e.createElement(s,{color:l.textMuted},"\u2022 Prompt cache remains stable across user turns, saving tokens and money."),e.createElement(s,{color:l.text,bold:!0},`
219
- `,"ON:"),e.createElement(s,{color:l.textMuted},"\u2022 Rescans and updates the directory's state dynamically on every single user turn."),e.createElement(s,{color:l.textMuted},"\u2022 Provides real-time filesystem awareness if files are continuously created, renamed, or removed."),e.createElement(s,{color:l.textMuted},"\u2022 Changes Prompt Context on each turn, invalidating part of prompt caches and increasing token usage."),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Actions",theme:ce.theme,items:[{label:"Back to Settings",value:"back"}],onSelect:()=>Y("settings")})));case"autoExecDanger":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:l.warning||"yellow",bold:!0,underline:!0},"SECURITY WARNING: YOLO MODE"),e.createElement(s,{marginTop:1,color:l.text},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),e.createElement(s,{marginTop:1,color:l.text,bold:!0},"RISKS INVOLVED:"),e.createElement(s,{color:l.textMuted},"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake unless specified in sandbox rules."),e.createElement(s,{color:l.textMuted},"\u2022 Unintended system changes if the agent hallucinates a path or command."),e.createElement(s,{color:l.textMuted},"\u2022 Reduced control over the agent's step-by-step decision making."),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Confirm Intent",theme:ce.theme,items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:o=>{o.value==="on"&&Bt(n=>({...n,autoExec:!0})),Y("settings")}})));case"advanceRollbackDanger":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:1,paddingTop:0,width:"100%"},e.createElement(s,{color:l.warning||"yellow",bold:!0},"\u26A0 Emergency Rollback Notice"),e.createElement(s,{marginTop:1,color:l.text},"When enabled, full repo snapshots exist only during active AI turns."),e.createElement(s,{marginTop:1,color:l.text},"If catastrophic changes occur during a turn, avoid abruptly stopping the agent unless absolutely necessary (external damages out of codebase)."),e.createElement(s,{color:l.textMuted},"The agent may be able to automatically restore the repo to a safe state."),e.createElement(s,{marginTop:1,color:l.textMuted},"Once the turn ends, emergency snapshots are deleted and standard /revert takes over which may not retain full repo content."),e.createElement(s,{marginTop:1,color:l.textMuted},"(Requires Restart to take effect)"),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Confirm",theme:ce.theme,items:[{label:"I understand and wish to enable",value:"on"},{label:"Keep Off",value:"off"}],onSelect:o=>{o.value==="on"&&Bt(n=>({...n,advanceRollback:!0})),Y("settings")}})));case"externalDanger":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:l.warning||"yellow",bold:!0,underline:!0},"SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),e.createElement(s,{marginTop:1,color:l.text},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),e.createElement(s,{marginTop:1,color:l.text,bold:!0},"RISKS INVOLVED:"),e.createElement(s,{color:l.textMuted},"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),e.createElement(s,{color:l.textMuted},"\u2022 Potential for accidental or malicious deletion of OS-critical files."),e.createElement(s,{color:l.textMuted},"\u2022 Unauthorized script execution across your entire file system."),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Confirm Intent",theme:ce.theme,items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:o=>{o.value==="on"&&Bt(n=>({...n,allowExternalAccess:!0})),Y("settings")}})));case"doubleDanger":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:l.danger||"red",bold:!0,underline:!0},"CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),e.createElement(s,{marginTop:1,color:l.text},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),e.createElement(s,{marginTop:1,color:l.danger||"red",bold:!0},"THIS IS NOT RECOMMENDED."),e.createElement(s,{marginTop:1,color:l.text,bold:!0},"THE CRITICAL RISK:"),e.createElement(s,{color:l.textMuted},"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),e.createElement(s,{color:l.danger||"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Final Confirmation",theme:ce.theme,items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:o=>{o.value==="on"&&Bt(n=>({...n,autoExec:!0,allowExternalAccess:!0})),Y("settings")}})));case"key":return e.createElement(ft,{title:"API KEY MANAGEMENT",items:[{label:"Edit Current Key (Update)",value:"edit"},{label:"Remove Current Key (Delete)",value:"remove"},{label:"Cancel",value:"Cancel"}],onSelect:o=>{if(o.value==="edit"){Kt(null),Y("chat");let n=qe(2);N(a=>[...a,{id:Date.now(),role:"system",text:`\u2726 Flux waiting for new API Key...
220
- \u2800`}])}else o.value==="remove"?Y("deleteKey"):Y("chat")}});case"deleteKey":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1},(()=>{let o=qe(2);return e.createElement(s,{color:"white",bold:!0},"DANGER: CLEAR CREDENTIALS")})(),e.createElement(s,{marginTop:1},"This will permanently delete all saved API keys in credential cache. You will need to enter it again to use Flux."),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Are you sure?",items:[{label:"YES, CLEAR CREDENTIALS",value:"yes"},{label:"NO, GO BACK",value:"no"}],onSelect:async o=>{if(o.value==="yes"){await yi(),Kt(null),Y("chat");let n=qe(2);N(a=>[...a,{id:Date.now(),role:"system",text:"[CREDENTIAL CLEARED] API Key removed successfully."}])}else Y("key")},theme:ce.theme})));case"exit":return null;case"ask":return e.createElement(c,{width:"100%"},e.createElement(el,{question:Xo?.question,options:Xo?.options,onResolve:o=>{Xo?.resolve&&Xo.resolve(o),Gr(null),Y("chat")},theme:ce.theme}));case"revert":return e.createElement(c,{width:"100%",alignItems:"center",justifyContent:"center"},e.createElement(Es,{prompts:Wl,onSelect:async o=>{i&&(i.write("\x1B[2J\x1B[3J\x1B[H"),i.isTTY&&i.write("\x1B[?2004h"));try{let n=await Ln.rollbackToBefore(o);if(n.success){let{targetPrompt:a}=n;Wi(et),zr(d=>d+1),ho(),Wt.current={completedIndex:0,columns:$.columns,historicalBlocks:[],seenSelections:new Set,chatId:et,clearKey:Wo+1};let f=xt.findLastIndex(d=>d.role==="user"&&d.text&&(d.text.startsWith(a)||d.text.includes(a))),u=[...xt];f!==-1&&(u=xt.slice(0,f)),N(u),V(u.length),m(a),E(a.split(`
221
- `).length>2);let T=u.filter(d=>!String(d.id).startsWith("welcome")&&(!d.isMeta||d.text&&d.text.includes("Request Cancelled")));await dn(et,null,T);let h=qe(2);N(d=>{let y=[...d,{id:"revert-ok-"+Date.now(),role:"system",text:`\u2726 Rollback Successful
222
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Reverted prompt loaded to input box.
223
- \u2800`,isMeta:!0}];return V(y.length),y}),Y("chat")}}catch(n){let a=qe(2);N(f=>{let u=[...f,{id:"revert-err-"+Date.now(),role:"system",text:`\u2726 ERROR
224
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${n.message}
225
- \u2800`,isMeta:!0}];return V(u.length),u}),Y("chat")}},onClose:()=>Y("chat"),theme:ce.theme}));case"resume":return e.createElement(c,{width:"100%",alignItems:"center",justifyContent:"center"},e.createElement(bs,{onSelect:async o=>{let n=await ko();if(n[o]){if(i.write("\x1B[2J\x1B[3J\x1B[H"),process.stdout.isTTY){let T=n[o]?.name||"",h=T&&!T.startsWith("flow-")&&!T.startsWith("Session ")?T:"FluxFlow | Resumed";process.stdout.write(`\x1B]0;${h}\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=${h}\x07`)}ho(),Ho.current=!0,zn(o);let a=await ur(o);wn.current=Qt-a.total,Ho.current=!1,pn(a.total),Uo({tokens:a.context});let f=[...n[o].messages];f[0]?.text?.includes("\u2591\u2591\u2591\u2588\u2588\u2588")||f.unshift({id:"logo-"+Date.now(),role:"system",isLogo:!0,isMeta:!0}),N(f),Y("chat"),N(T=>{let h=[...T,{id:"sys-"+Date.now(),role:"system",text:`\u2726 SESSION RESUMED
226
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${o}
227
- \u2800`,isMeta:!0}];return V(h.length),h})}},onDelete:async o=>await cr(o),onClose:()=>Y("chat"),theme:ce.theme}));case"keybindingsPrompt":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:"grey",paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:"white",bold:!0,underline:!0},"\u2328 CONFIGURE SHIFT+ENTER NEWLINE"),e.createElement(s,{marginTop:1},"To support multi-line inputs with ",e.createElement(s,{bold:!0,color:"white"},"Shift + Enter")," for newline, a terminal sequence keybinding needs to be added to your IDE configuration."),e.createElement(s,{marginTop:1},"Would you like FluxFlow to automatically add this to your ",Ko()," keybindings?"),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Add Keybinding?",items:[{label:"Yes, configure automatically",value:"yes"},{label:"No, skip",value:"no"}],onSelect:async o=>{o.value==="yes"?await vr(Ko()):Br="\\ + Enter",Y("chat")},theme:ce.theme})));case"memory":return e.createElement(c,{width:"100%",alignItems:"center",justifyContent:"center"},e.createElement(Ss,{onClose:()=>Y("chat"),theme:ce.theme}));case"parserDownload":return e.createElement(c,{width:"100%",alignItems:"center",justifyContent:"center"},e.createElement(Cs,{onClose:()=>Y("settings")}));case"profile":return e.createElement(ps,{initialData:xn,onSave:o=>{Os(o),N(n=>[...n,{id:Date.now(),role:"system",text:`${o.name.length>0||o.nickname.length>0?`\u2726 Profile Updated${o.name.length>0?`
228
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Name: ${o.name} `:""}${o.nickname.length>0?`
229
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Nickname: ${o.nickname}`:""}`:`\u2726 Profile
230
- \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Nothing to Update`}
231
-
232
- \u2726 Custom Instructions
233
- ${o.instructions.length>0?`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m ${o.instructions.substring(0,30)}${o.instructions.length>30?"...":""}`:"\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No Instructions Provided."}
234
- \u2800`,isMeta:!0}]),Y("chat")},onCancel:()=>Y("chat"),theme:ce.theme});case"resolution":return e.createElement(c,{width:"100%",alignItems:"center",justifyContent:"center"},e.createElement(Ud,{data:Gl,theme:ce.theme,onResolve:o=>{Qr(null),Y("chat"),setTimeout(()=>{ui(o,!0)},500)},onEdit:o=>{Qr(null),Y("chat"),m(o)}}));case"approval":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:"white",bold:!0,underline:!0},"FILE WRITE PERMISSION"),e.createElement(s,{marginTop:1},"The agent is attempting to modify: ",e.createElement(s,{color:"cyan"},An(Co?.args||"{}").path||"Unknown File")),Vo()?e.createElement(c,{marginTop:1,paddingX:1},e.createElement(s,{color:"cyan",italic:!0},"FluxFlow Companion is active. Review the changes in your editor.")):e.createElement(c,{marginTop:1,borderStyle:"single",borderColor:"#333",paddingX:1,flexDirection:"column"},e.createElement(s,{color:"gray"},"--- PROPOSED CONTENT ---"),(()=>{let o=An(Co?.args||"{}"),n=[],a=new Set;if(Object.keys(o).forEach(T=>{let h=T.match(/^(searchContent|replaceContent|newContent|content_to_replace|content_to_add|TargetContent|ReplacementContent|replacementContent)(\d+)?$/);if(h){let d=h[2]?parseInt(h[2]):1;a.add(d)}}),Array.from(a).sort((T,h)=>T-h).forEach(T=>{let h,d;T===1?(h=o.searchContent1??o.searchContent??o.replaceContent1??o.content_to_replace1??o.replaceContent??o.content_to_replace??o.TargetContent??null,d=o.newContent1??o.content_to_add1??o.newContent??o.content_to_add??o.ReplacementContent??o.replacementContent??null):(h=o[`searchContent${T}`]??o[`replaceContent${T}`]??o[`content_to_replace${T}`]??null,d=o[`newContent${T}`]??o[`content_to_add${T}`]??null),(h!==null||d!==null)&&n.push({replace:h,new:d})}),n.length>0)return e.createElement(c,{flexDirection:"column",marginTop:1},n.map((T,h)=>{let d=T.replace!==null,y=T.new!==null;return e.createElement(c,{key:h,flexDirection:"column",marginTop:h>0?1:0},n.length>1&&e.createElement(s,{color:"gray"},"Block ",h+1,":"),d&&e.createElement(c,null,e.createElement(s,{color:"red",wrap:"anywhere",bold:!0},"- ",T.replace)),y&&e.createElement(c,{marginTop:0},e.createElement(s,{color:"green",wrap:"anywhere",bold:!0},"+ ",T.new.replace(/\[\/n\]?/g,"\\n"))))}));let u=o.content||o.ReplacementContent||o.content_to_add||o.replacementContent||o.newContent||null;return e.createElement(s,{color:"white",wrap:"anywhere"},(u?u.replace(/\[\/n\]?/g,"\\n"):null)||"Updating file content...")})()),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Action Required",items:[{label:"Accept this time",value:"allow"},{label:"Accept for this session",value:"always"},{label:"Don't accept",value:"deny"}],onSelect:o=>{o.value==="always"&&Fl(!0);let n=o.value==="deny"?"deny":"allow";Co.resolve(n),on(null),Y("chat")},theme:ce.theme})));case"mode":return e.createElement(ft,{title:"SELECT EXECUTION MODE",items:[{label:`Flux (Dev Toolset Mode) ${v==="Flux"?"\u25CF":""}`,value:"Flux"},{label:`Flow (Chat / Conversation Mode) ${v==="Flow"?"\u25CF":""}`,value:"Flow"},{label:`ICU (Interactive Computer Use) ${v==="ICU"?"\u25CF":""}`,value:"ICU"},{label:`FluxCU (Autonomous Flux Computer Use) ${v==="FluxCU"?"\u25CF":""}`,value:"FluxCU"},{label:"Back",value:"chat"}],theme:ce.theme,onSelect:o=>{if(o.value==="chat"||o.value==="Back"){Y("chat");return}let n=o.value;k(n),_e(n==="Flow"?"Fast":"High"),N(a=>(V(a.length+1),[...a,{id:Date.now(),role:"system",text:`\u2726 Mode switched to ${Ds(n)}
235
- \u2800`,isMeta:!0}])),Y("chat")},onClose:()=>Y("chat")});case"display":return e.createElement(ft,{title:"SELECT ACTIVE DISPLAY FOR COMPUTER USE",items:[{label:`Primary Display (Display 1) ${O===0?"\u25CF":""}`,value:0},{label:`Secondary Display (Display 2) ${O===1?"\u25CF":""}`,value:1},{label:"Back",value:"chat"}],theme:ce.theme,onSelect:o=>{if(o.value==="chat"||o.value==="Back"){Y("chat");return}let n=Number(o.value);L(n),Dt({display:n}).catch(()=>{});let a=n===0?"Primary (Display 1)":"Secondary (Display 2)";N(f=>(V(f.length+1),[...f,{id:Date.now(),role:"system",text:`\u2726 Active Computer Use display set to: ${a}`,isMeta:!0}])),Y("chat")},onClose:()=>Y("chat")});case"updateManager":return e.createElement(ft,{title:"Select Preferred Update Manager",subtitle:"NOTE: If you are unsure about these, go with NPM",items:[{label:"NPM (Standard)",value:"npm"},{label:"PNPM (Recommended)",value:"pnpm"},{label:"BUN (Ultra Fast)",value:"bun"},{label:"YARN (Classic)",value:"yarn"},{label:"Custom Command",value:"custom"},{label:"Back",value:"settings"}],onSelect:o=>{if(o.value==="settings"||o.value==="Back"){Y("settings");return}o.value==="custom"?(qt({label:"Enter Custom Update Command (Global install recommended):",key:"customUpdateCommand",value:ce.customUpdateCommand,next:n=>(Bt(a=>({...a,updateManager:"custom",customUpdateCommand:n})),null)}),Y("input")):(Bt(n=>({...n,updateManager:o.value})),Y("settings"))},theme:ce.theme});case"update":return e.createElement(rl,{latest:Vt,current:oo,settings:ce,onClose:()=>Y("chat"),onSuccess:()=>{N(o=>(V(o.length+1),[...o,{id:"update-success-"+Date.now(),role:"system",text:`**[UPDATE COMPLETED]** Flux Flow successfully updated to v${Vt}.
236
- **Restart to see changes.**`,isMeta:!0}])),Y("chat")},onUpdateSettings:o=>{Y("updateManager")}});case"terminalApproval":return e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:"white",paddingX:2,paddingY:1,width:"100%"},e.createElement(s,{color:"white",bold:!0,underline:!0},"TERMINAL COMMAND OVERSIGHT"),e.createElement(c,{marginTop:1},e.createElement(s,null,"Agent requested to run: ",e.createElement(s,{color:"yellow",bold:!0},An(Co?.args||"{}").command||"Unknown Command"))),e.createElement(c,{marginTop:1},e.createElement(ft,{title:"Risk Assessment Required",items:[{label:"Run",value:"allow"},{label:"Deny",value:"deny"}],onSelect:o=>{Co.resolve(o.value),on(null),Y("chat")},theme:ce.theme})));default:return e.createElement(c,{flexDirection:"column",marginTop:1,flexShrink:0,width:"100%"},ri&&ni&&e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:1,width:"100%",marginBottom:1},e.createElement(c,{justifyContent:"space-between",width:"100%"},e.createElement(s,{color:l.text,bold:!0,underline:!0},"INQUIRY RESPONSE"),e.createElement(s,{color:l.textMuted},"[ ESC to Close ]")),e.createElement(c,{marginTop:1,width:"100%"},e.createElement(Nn,{text:ni,columns:$.columns-6,theme:ce.theme}))),Xr.filter(o=>o.status==="running").length>0&&e.createElement(c,{flexDirection:"column",borderStyle:"round",borderColor:l.borderMuted,paddingX:2,paddingY:0,width:"100%",marginBottom:1},e.createElement(c,{justifyContent:"space-between",width:"100%"},e.createElement(s,{color:l.text,bold:!0},"ACTIVE SUBAGENTS")),e.createElement(c,{flexDirection:"column",marginTop:1,width:"100%"},Xr.filter(o=>o.status==="running").map(o=>e.createElement(_d,{key:o.id,sa:o,showTPMEstimate:ce.showTPMEstimate})))),e.createElement(c,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},e.createElement(c,null,Bn?e.createElement(c,{gap:1},e.createElement(kd,null),e.createElement(_n,{text:Bn.trimEnd(),baseColor:l.textExclusive||l.text,glintColor:l.textMutedExclusive||l.textMuted,speed:60,italic:!0,glintWidth:2,typeSpeed:10}),e.createElement(s,{color:l.textMuted},Zs>0?`(${Zs.toFixed(0)}s)`:"")):e.createElement(s,{color:l.textMuted,italic:!0},D.length>0&&ti?"Press ESC again to clear input":Ul?"Press CTRL + O to expand":"Waiting for input...")),e.createElement(c,null,(()=>{let o=Bn?.toLowerCase()??"";return nn&&Date.now()-Ps>15e3&&Xr.length===0&&(o.includes("connecting")||o.includes("working")||o.includes("queue"))?e.createElement(c,null,e.createElement(_n,{text:"Waiting for API",baseColor:l.text,glintColor:l.textMuted,glintWidth:4,speed:80}),e.createElement(s,{color:l.textMuted,dimColor:!0}," \u2503 ")):Vr?e.createElement(c,null,e.createElement(_n,{text:Vr,baseColor:l.text,glintColor:l.textMuted,italic:!0,speed:80,typeSpeed:15}),e.createElement(s,{color:l.textMuted,dimColor:!0}," \u2503 ")):null})(),e.createElement(_n,{text:ne.split("/")[1]||(ne.length>1?ne:"Use '/model model-id' to select model"),baseColor:l.text,glintColor:l.textMuted,glintWidth:3}),e.createElement(s,{color:l.textMuted}," ",ne.length>0?`(${me})`:""))),e.createElement(c,{flexDirection:"column",width:"100%"},e.createElement(c,{width:"100%",height:1,overflow:"hidden"},e.createElement(s,{color:l.inputBorder},"\u2584".repeat(Math.max(1,$.columns)))),e.createElement(c,{backgroundColor:l.inputBg,paddingX:1,paddingY:0,width:"100%",flexDirection:"column"},e.createElement(c,{flexDirection:"column",width:"100%"},e.createElement(c,{flexDirection:"row",width:"100%",paddingY:0},e.createElement(c,{flexShrink:0,width:4},e.createElement(s,{color:l.inputPrompt,bold:!0},nn||Rn?"\u2726 ":" \u276F ")),e.createElement(c,{flexGrow:1},e.createElement(c,{flexGrow:1,position:"relative"},D===""&&e.createElement(c,{position:"absolute",paddingLeft:0},Rt&&!Mn?e.createElement(s,{color:"yellow"},Kl?" Terminal is waiting for user input. Press TAB to interact":" Press TAB to interact with terminal..."):Rt&&Mn?e.createElement(s,{color:"yellow",bold:!0}," [ TERMINAL FOCUSED ] Type to interact, press TAB to exit..."):ti===1?e.createElement(s,{color:l.inputPrompt,bold:!0}," Press ESC again to ",D.length>0?"clear input":"revert codebase to checkpoint","..."):e.createElement(s,{color:l.inputPlaceholder},_l?" Press ESC again to cancel the request.":Rn?" Compacting session history, please wait...":nn?" Enter a prompt to steer the agent.":` Send message, @file or /cmd ... (${Pl.shortcut} for newline)`)),e.createElement(Yi,{key:`input-${B}`,onPasteStateChange:Xl,focus:!Mn&&!Rn,showCursor:Fe&&!Rn,cursorColor:l.inputText,lastFocusEventTime:We.current,value:D,textStyle:{bold:!0,color:l.inputText},columns:$.columns,onChange:o=>{let n=o.replace(/\r\n/g,`
237
- `).replace(/\r/g,`
238
- `).replace(/\\\s*\n/g,`
239
- `);m(n),K(!1)},onSubmit:ui,rows:1,maxRows:10,keyBindings:{submit:o=>o.return&&!o.shift&&!o.ctrl,newline:o=>o.return&&o.shift||o.return&&o.ctrl}})))))),e.createElement(c,{width:"100%",height:1,overflow:"hidden"},e.createElement(s,{color:l.inputBorder},"\u2580".repeat(Math.max(1,$.columns))))))}};return e.createElement(c,{flexDirection:"column",width:"100%"},nt?null:re?e.createElement(Pd,{width:i?.columns||80,height:i?.rows||24,selectedIndex:ye,aiProvider:H,theme:ce.theme}):e.createElement(e.Fragment,null,e.createElement(c,{paddingX:1,flexDirection:"column",width:"100%"},e.createElement(vd,{key:`static-${Wo}-${et}-${$.columns}-${$.rows}-${ce.theme}`,items:ai.completed},o=>e.createElement(xr,{key:o.key,block:o,columns:(i?.columns||80)-2,showFullThinking:Ht,aiProvider:H,version:oo,theme:ce.theme}))),e.createElement(c,{flexDirection:"column",paddingX:1,paddingBottom:0,width:"100%"},(at==="chat"||["ask","approval","terminalApproval"].includes(at))&&e.createElement(c,{flexDirection:"column",width:"100%"},ai.active.map(o=>e.createElement(xr,{key:o.key,block:o,columns:Math.max(20,(i?.columns||80)-2),showFullThinking:Ht,aiProvider:H,version:oo,theme:ce.theme})),Rt&&e.createElement(c,{marginTop:1},e.createElement(hr,{command:Rt,output:en,isFocused:Mn,isPty:an,terminalHeight:$.rows,columns:$.columns}))),nt?e.createElement(c,{borderStyle:"double",borderColor:"grey",padding:1,flexShrink:0},e.createElement(s,{color:"white"},"Starting Flux Flow...")):bt?ql():e.createElement(c,{borderStyle:"round",borderColor:"white",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},e.createElement(c,{paddingX:1,marginBottom:1},e.createElement(s,{color:"gray",bold:!0},"API KEY REQUIRED")),e.createElement(c,{paddingX:1,flexDirection:"column"},ct===0?e.createElement(e.Fragment,null,e.createElement(s,{color:"white"},"Select your Preferred Provider:"),e.createElement(c,{marginTop:1},e.createElement(ft,{searchable:!0,items:[{label:"Google",value:"Google"},{label:"Nvidia",value:"NVIDIA"},{label:"DeepSeek",value:"DeepSeek"},{label:"InferX",value:"InferX"},{label:"SenseNova",value:"SenseNova"},{label:"CrofAI",value:"CrofAI"},{label:"Ollama",value:"Ollama"},{label:"AIHubMix [EXPERIMENTAL]",value:"AIHubMix"},{label:"Mistral [EXPERIMENTAL]",value:"Mistral"},{label:"OpenRouter [EXPERIMENTAL]",value:"OpenRouter"}],onSelect:o=>{Mt(o.value),Pt(1)}}))):e.createElement(e.Fragment,null,e.createElement(s,{color:"white"},H==="Ollama"?"Enter Ollama API Key (or type LOCAL to use local host):":`Enter your ${H} API Key:`),e.createElement(c,{marginTop:1},e.createElement(s,{color:"gray",bold:!0}," ",">"," "),e.createElement(Mr,{value:Dr,onChange:Qo,onSubmit:di,mask:"*"})))),e.createElement(c,{paddingX:1,marginTop:1},e.createElement(s,{color:"gray",italic:!0},ct===0?"(Use arrows to select and Enter to confirm, ESC to go back)":"(Press Enter to confirm and initialize, ESC to go back)"))),x&&e.createElement(c,{borderStyle:"round",borderColor:l.borderMuted,paddingX:1,marginY:0,width:"100%"},e.createElement(s,null,e.createElement(s,{color:"red",bold:!0},"\u{1F534} EXIT: "),e.createElement(s,{color:l.text},"Press "),e.createElement(s,{color:l.text,bold:!0},"CTRL+C"),e.createElement(s,{color:l.text}," again to exit (",w,"s) \u2022 Press "),e.createElement(s,{color:l.textMuted,bold:!0},"ESC"),e.createElement(s,{color:l.text}," to cancel"))),He.length>0&&(()=>{let n=de.current,a=0;for(;a<He.length;){let T=He[a],h=T?.cmd||T||"";if(typeof h=="string"&&h.trimStart().startsWith("---"))a++;else break}ae<=a?n=0:ae<n?n=ae:ae>=n+5&&(n=ae-5+1),n=Math.max(0,Math.min(n,Math.max(0,He.length-5))),de.current=n;let f=He.slice(n,n+5),u=He.length-(n+f.length);return e.createElement(c,{flexDirection:"column",width:"100%",marginBottom:1},e.createElement(c,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},e.createElement(s,{color:l.text,bold:!0},He[0]?.cmd?.startsWith("@")||He[0]?.cmd?.startsWith("\\@")?"FILE SUGGESTIONS":"COMMAND SUGGESTIONS"),He[0]?.cmd?.startsWith("@")||He[0]?.cmd?.startsWith("\\@")?e.createElement(s,{color:l.textMuted,italic:!0},"(Use #Lstart-Lend to specify line numbers)"):D.startsWith("/model")&&Je==="Free"?(()=>{let T="https://aistudio.google.com/billing",h="billing";H==="DeepSeek"?(T="https://platform.deepseek.com/usage",h="billing"):H==="OpenRouter"?(T="https://openrouter.ai/settings/profile",h="profile"):H==="NVIDIA"?(T="https://build.nvidia.com/settings/api-keys",h="billing"):H==="CrofAI"&&(T="https://crof.ai",h="account")})():null),f.slice(0,or).map((T,h)=>{let y=n+h===ae,I=typeof T.cmd=="string"&&T.cmd.trimStart().startsWith("---"),_=T.cmd===no("Google","Free")&&Je!=="Free";return e.createElement(c,{key:T.cmd,flexDirection:"row",backgroundColor:y?l.highlightBg:void 0,paddingX:1},e.createElement(c,{width:3},e.createElement(s,{color:y?l.text:l.textMuted,bold:y},y?" \u276F":" ")),e.createElement(c,{width:55},e.createElement(s,{color:I?l.textDim:_?l.textMuted:y?l.text:l.textDim,bold:!1},T.display||(T.cmd&&(T.cmd.startsWith("@[")||T.cmd.startsWith("\\@["))&&T.cmd.endsWith("]")?(()=>{let ue=(T.cmd.startsWith("\\@[")?T.cmd.slice(3,-1):T.cmd.slice(2,-1)).split(/[/\\]/);return ue[ue.length-1]})():T.cmd&&T.cmd.includes("/")?T.cmd.split("/").pop():T.cmd))),e.createElement(c,{flexGrow:1},e.createElement(s,{color:y?l.text:l.textMuted,italic:!0},T.desc)))}),He.length>5&&e.createElement(c,{paddingX:1,height:1},u>0?e.createElement(s,{color:l.textMuted,dimColor:!0,italic:!0}," ... (",u," more commands available)"):e.createElement(s,{color:l.textMuted,dimColor:!0,italic:!0}," (End of list)")))})(),e.createElement(c,{flexShrink:0,width:"100%"},e.createElement(Ji,{mode:v,thinkingLevel:me,tokens:mo.tokens,tokensTotal:Ml,chatId:et,isMemoryEnabled:ce.memory,apiTier:Je,aiProvider:H,activeModel:ne,isProcessing:nn,lastChunkTime:Ps,theme:ce.theme,wps:Pr.current.wps,showTPMEstimate:ce.showTPMEstimate})),at==="exit"&&(()=>{let o=Date.now()-vs,n=yt.toolSuccess+yt.toolFailure,a=n>0?(yt.toolSuccess/n*100).toFixed(1):"0.0",f=jn+Kn,u=f>0?(jn/f*100).toFixed(1):"0.0",T=f>0?(Kn/f*100).toFixed(1):"0.0";return e.createElement(c,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:l.borderMuted,width:Math.min(100,(i?.columns||100)-2),marginTop:0,marginBottom:0},e.createElement(c,{marginBottom:1},e.createElement(s,{bold:!0},Ad(l.logoGradient||["blue","purple"])("Agent powering down. Goodbye!"))),e.createElement(c,{flexDirection:"column"},e.createElement(s,{color:l.text,bold:!0,underline:!0},"Interaction Summary"),e.createElement(c,{marginTop:1},e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Session ID:")),e.createElement(s,{color:l.text},et)),e.createElement(c,null,e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Tool Calls:")),e.createElement(s,{color:l.text},yt.toolSuccess+yt.toolFailure+yt.toolDenied," ( ",e.createElement(s,{color:"green"},"\u2714 ",yt.toolSuccess)," ",e.createElement(s,{color:"yellow"},"\u{1F6C7} ",yt.toolDenied)," ",e.createElement(s,{color:"red"},"\u2718 ",yt.toolFailure)," )")),e.createElement(c,null,e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Success Rate:")),e.createElement(s,{color:l.text},a,"%")),e.createElement(c,null,e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Code Changes:")),e.createElement(s,{color:l.text},e.createElement(s,{color:"green"},"+",yt.linesAdded)," ",e.createElement(s,{color:"red"},"-",yt.linesRemoved))),Qt>0&&e.createElement(e.Fragment,null,e.createElement(c,null,e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Tokens Consumed:")),e.createElement(s,{color:l.text},mt(Qt))),e.createElement(c,{marginLeft:2},e.createElement(c,{width:18},e.createElement(s,{color:l.textMuted},"\xBB Input Tokens:")),e.createElement(s,{color:l.text},mt(Qt-Zo))),Vn>0&&e.createElement(c,{marginLeft:4},e.createElement(c,{width:16},e.createElement(s,{color:l.textMuted},"\xBB Cached:")),e.createElement(s,{color:l.text},mt(Vn))),Zo>0&&e.createElement(c,{marginLeft:2},e.createElement(c,{width:18},e.createElement(s,{color:l.textMuted},"\xBB Output Tokens:")),e.createElement(s,{color:l.text},mt(Zo)))),qn>0&&e.createElement(e.Fragment,null,e.createElement(c,null,e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Images Made:")),e.createElement(s,{color:l.text},qn)),e.createElement(c,null,e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Image Credits:")),e.createElement(s,{color:l.text},Number(((Ws||0)*1e3).toFixed(0))," credits")))),e.createElement(c,{flexDirection:"column",marginTop:1},e.createElement(s,{color:l.text,bold:!0,underline:!0},"Performance"),e.createElement(c,{marginTop:1},e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Wall Time:")),e.createElement(s,{color:l.text},$o(o))),e.createElement(c,null,e.createElement(c,{width:20},e.createElement(s,{color:l.secondary},"Agent Active:")),e.createElement(s,{color:l.text},$o(f))),e.createElement(c,{marginLeft:2},e.createElement(c,{width:18},e.createElement(s,{color:l.textMuted},"\xBB API Time:")),e.createElement(s,{color:l.text},$o(jn)," (",u,"%)")),e.createElement(c,{marginLeft:2},e.createElement(c,{width:18},e.createElement(s,{color:l.textMuted},"\xBB Tool Time:")),e.createElement(s,{color:l.text},$o(Kn)," (",T,"%)"))))})())))}export{Hd as default};