fluxflow-cli 5.4.1 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/dist/chunks/{ai-TVKJMVCH.js → ai-6AZZQUJJ.js} +1 -1
  3. package/dist/chunks/answerSubagent-LFLPQQSS.js +1 -0
  4. package/dist/chunks/{app-HBLCJLMN.js → app-SKIGDYWL.js} +14 -14
  5. package/dist/chunks/ask_user-4KTNP4MZ.js +1 -0
  6. package/dist/chunks/{auto_completion-SGFPH6MP.js → auto_completion-ZYVGXNQC.js} +1 -1
  7. package/dist/chunks/{awaitSubagent-JKQ2EHVY.js → awaitSubagent-ZXLUWTW7.js} +1 -1
  8. package/dist/chunks/cancel-C2BQ3FGV.js +1 -0
  9. package/dist/chunks/chat-34HLGFEJ.js +1 -0
  10. package/dist/chunks/{chunk-BNKY5QOA.js → chunk-5KBOEKGE.js} +6 -6
  11. package/dist/chunks/chunk-H2EXH5PL.js +898 -0
  12. package/dist/chunks/chunk-JWNCKRN6.js +4 -0
  13. package/dist/chunks/{chunk-4PTLFXTU.js → chunk-O74INBF3.js} +3 -3
  14. package/dist/chunks/{chunk-RINQH4H4.js → chunk-YI3O7C3D.js} +6 -6
  15. package/dist/chunks/{click-WWAFZ4BZ.js → click-M5D2RARW.js} +2 -2
  16. package/dist/chunks/computer_action-N7WIG3L4.js +1 -0
  17. package/dist/chunks/drag-K5ITERVW.js +1 -0
  18. package/dist/chunks/{emergency_rollback-J3SMQXBP.js → emergency_rollback-X55BPJ7Q.js} +1 -1
  19. package/dist/chunks/{exec_command-SQB5LU5X.js → exec_command-QBBSYF2H.js} +1 -1
  20. package/dist/chunks/{file_map-U6SWDUPK.js → file_map-3YMVODEE.js} +8 -8
  21. package/dist/chunks/find_file-RBJ4LKPD.js +4 -0
  22. package/dist/chunks/generate_image-53KQ3EDL.js +1 -0
  23. package/dist/chunks/{getProgress-J34K43Y7.js → getProgress-4D67AF3H.js} +2 -2
  24. package/dist/chunks/invoke-GUW4734N.js +6 -0
  25. package/dist/chunks/invokeSync-2PXPUJSJ.js +7 -0
  26. package/dist/chunks/key_press-RQ32VDHR.js +1 -0
  27. package/dist/chunks/keyboard_typing-BH4JHUQO.js +1 -0
  28. package/dist/chunks/{read_folder-UWFC5DNX.js → read_folder-OJ7UWWOR.js} +1 -1
  29. package/dist/chunks/recapture_screen-YJNK64KL.js +1 -0
  30. package/dist/chunks/scroll-IQUZ3QLU.js +1 -0
  31. package/dist/chunks/search_keyword-2JQ75HEQ.js +9 -0
  32. package/dist/chunks/steerSubagent-UNAOFQZJ.js +1 -0
  33. package/dist/chunks/{todo-ZFQ6BQVI.js → todo-OX7SMIKN.js} +2 -2
  34. package/dist/chunks/update_file-2EZILIMQ.js +15 -0
  35. package/dist/chunks/view_file-XYWGDYAY.js +1 -0
  36. package/dist/chunks/wait-RQSCCCXW.js +1 -0
  37. package/dist/chunks/{web_search-MOI3CNWS.js → web_search-B2XM4T5D.js} +11 -11
  38. package/dist/chunks/write_docx-BMIF6ZDY.js +13 -0
  39. package/dist/chunks/{write_file-MNAF43T6.js → write_file-O3LLIRLR.js} +1 -1
  40. package/dist/chunks/write_pdf-CTBFENCU.js +31 -0
  41. package/dist/cli.js +4 -4
  42. package/dist/package.json +2 -2
  43. package/package.json +2 -2
  44. package/dist/chunks/answerSubagent-BPNNJXPC.js +0 -1
  45. package/dist/chunks/ask_user-K2DLZF6H.js +0 -1
  46. package/dist/chunks/cancel-F3ZOEBKW.js +0 -1
  47. package/dist/chunks/chat-V5FZDYET.js +0 -1
  48. package/dist/chunks/chunk-AUXKQKSZ.js +0 -888
  49. package/dist/chunks/chunk-Y5JU726N.js +0 -4
  50. package/dist/chunks/computer_action-B6QH77NT.js +0 -1
  51. package/dist/chunks/drag-3VRYDGVU.js +0 -1
  52. package/dist/chunks/find_file-GBEBP5NZ.js +0 -4
  53. package/dist/chunks/generate_image-2JIYAW5L.js +0 -1
  54. package/dist/chunks/invoke-JSHBXNXZ.js +0 -6
  55. package/dist/chunks/invokeSync-NP7Z3LUE.js +0 -3
  56. package/dist/chunks/key_press-J2ZSWOT2.js +0 -1
  57. package/dist/chunks/keyboard_typing-FFC7OTDM.js +0 -1
  58. package/dist/chunks/recapture_screen-P7YVVVSF.js +0 -1
  59. package/dist/chunks/scroll-GBV6YRQT.js +0 -1
  60. package/dist/chunks/search_keyword-KE5VBMVA.js +0 -9
  61. package/dist/chunks/steerSubagent-UETXH2CB.js +0 -1
  62. package/dist/chunks/update_file-C5HRYCQN.js +0 -15
  63. package/dist/chunks/view_file-PEZ7HS36.js +0 -1
  64. package/dist/chunks/wait-TJR6LAR4.js +0 -1
  65. package/dist/chunks/write_docx-A3GAUZEW.js +0 -13
  66. package/dist/chunks/write_pdf-YQ3JTZ5U.js +0 -31
@@ -1,4 +1,4 @@
1
- import{a as Ca}from"./chunk-UEV335RW.js";import{b as ma,c as fa,d as xa}from"./chunk-FMKFTJB3.js";import{c as na,e as er,f as bo,g as ra}from"./chunk-RINQH4H4.js";import{B as wa,C as Ta,D as Mo,F as ya,a as oa,b as gt,c as At,d as Sr,e as pi,f as la,g as Ln,h as ls,i as bi,j as wi,k as as,l as aa,t as ha,v as pa,z as ba}from"./chunk-AUXKQKSZ.js";import{a as co,b as sa,c as ia}from"./chunk-UM5SNZ6X.js";import"./chunk-NJTM7OYZ.js";import{a as ga}from"./chunk-56EJGQU3.js";import"./chunk-4PTLFXTU.js";import{a as Yt,b as Nt,d as Rl,e as Ft,f as ea,k as xi,l as gi,m as Mr,n as hi,o as ta,p as Jo}from"./chunk-JMMO76HS.js";import"./chunk-BNKY5QOA.js";import{a as ua}from"./chunk-YX4X2ZTX.js";import{a as Br,b as Zo,c as Pn,e as cs,f as Ti,g as ca,h as da,i as Er}from"./chunk-VOUGMIAJ.js";import{a as vr}from"./chunk-2RTYI6K3.js";import{a as fn}from"./chunk-Y5JU726N.js";import{b as mn,c as di}from"./chunk-3HGLLXBK.js";import{A as Xl,C as Gl,D as Kl,E as Vl,H as jl,c as Pl,e as ii,g as Ol,k as Nl,l as Fl,m as $l,n as Ul,o as _l,q as Hl,r as Wl,u as li,v as ai,w as ci}from"./chunk-IWIVGFAT.js";import{a as ql,b as Ql,i as zl,j as ss,k as is,m as It,n as Jl,p as mi,q as fi,w as Zl}from"./chunk-5MJKHQVE.js";import{a as Yl,b as ui,c as zt}from"./chunk-KQNW7DK5.js";import{d as Bl,e as si,f as El,g as kl,h as Dl,i as Il,j as Al,l as ns,n as un,o as po,p as rs,q as Cr,r as Ll}from"./chunk-Y6O7SAPD.js";import{c as ts,d as vl,e as os}from"./chunk-ZGORMZE5.js";import{a as Po,b as An,c as Co,d as ni,e as ri,k as yr,y as Sl}from"./chunk-NPXJIGAI.js";import Es from"os";import hu from"crypto";import e,{useState as Z,useEffect as ut,useRef as Re,useMemo as rr}from"react";import{Box as u,Text as i,useInput as pu,useStdout as bu,Static as wu}from"ink";import Tu from"ink-spinner";import at from"fs-extra";import{minimatch as oc}from"minimatch";import wt from"path";import{exec as jo}from"child_process";import{fileURLToPath as yu}from"url";import ro,{useState as ds,useEffect as yi,useMemo as kr,useCallback as Hc,useRef as Ro}from"react";import{Box as Wc,Text as Oo,useInput as Xc}from"ink";function Gc(t,m){return t.replace(/\t/g," ".repeat(m))}function us(t){return t==null?"":t.replace(/\r\n/g,`
1
+ import{a as Ca}from"./chunk-UEV335RW.js";import{b as ma,c as fa,d as xa}from"./chunk-FMKFTJB3.js";import{c as na,e as er,f as bo,g as ra}from"./chunk-YI3O7C3D.js";import{B as wa,C as Ta,D as Mo,F as ya,a as oa,b as gt,c as At,d as Sr,e as pi,f as la,g as Ln,h as ls,i as bi,j as wi,k as as,l as aa,t as ha,v as pa,z as ba}from"./chunk-H2EXH5PL.js";import{a as co,b as sa,c as ia}from"./chunk-UM5SNZ6X.js";import"./chunk-NJTM7OYZ.js";import{a as ga}from"./chunk-56EJGQU3.js";import"./chunk-O74INBF3.js";import{a as Yt,b as Nt,d as Rl,e as Ft,f as ea,k as xi,l as gi,m as Mr,n as hi,o as ta,p as Jo}from"./chunk-JMMO76HS.js";import"./chunk-5KBOEKGE.js";import{a as ua}from"./chunk-YX4X2ZTX.js";import{a as Br,b as Zo,c as Pn,e as cs,f as Ti,g as ca,h as da,i as Er}from"./chunk-VOUGMIAJ.js";import{a as vr}from"./chunk-2RTYI6K3.js";import{a as fn}from"./chunk-JWNCKRN6.js";import{b as mn,c as di}from"./chunk-3HGLLXBK.js";import{A as Xl,C as Gl,D as Kl,E as Vl,H as jl,c as Pl,e as ii,g as Ol,k as Nl,l as Fl,m as $l,n as Ul,o as _l,q as Hl,r as Wl,u as li,v as ai,w as ci}from"./chunk-IWIVGFAT.js";import{a as ql,b as Ql,i as zl,j as ss,k as is,m as It,n as Jl,p as mi,q as fi,w as Zl}from"./chunk-5MJKHQVE.js";import{a as Yl,b as ui,c as zt}from"./chunk-KQNW7DK5.js";import{d as Bl,e as si,f as El,g as kl,h as Dl,i as Il,j as Al,l as ns,n as un,o as po,p as rs,q as Cr,r as Ll}from"./chunk-Y6O7SAPD.js";import{c as ts,d as vl,e as os}from"./chunk-ZGORMZE5.js";import{a as Po,b as An,c as Co,d as ni,e as ri,k as yr,y as Sl}from"./chunk-NPXJIGAI.js";import Es from"os";import hu from"crypto";import e,{useState as Z,useEffect as ut,useRef as Re,useMemo as rr}from"react";import{Box as u,Text as i,useInput as pu,useStdout as bu,Static as wu}from"ink";import Tu from"ink-spinner";import at from"fs-extra";import{minimatch as oc}from"minimatch";import wt from"path";import{exec as jo}from"child_process";import{fileURLToPath as yu}from"url";import ro,{useState as ds,useEffect as yi,useMemo as kr,useCallback as Hc,useRef as Ro}from"react";import{Box as Wc,Text as Oo,useInput as Xc}from"ink";function Gc(t,m){return t.replace(/\t/g," ".repeat(m))}function us(t){return t==null?"":t.replace(/\r\n/g,`
2
2
  `).replace(/\r/g,`
3
3
  `)}function On(t,m,d){let S=t,y=[...m].sort((r,C)=>r.start-C.start),p=0;for(let r of y){let C=r.start-p,w=us(r.text).split(`
4
4
  `).length,M=r.text.length,P=(w>3?`[Pasted ${w} lines]`:`[Pasted ${M} chars]`).length,F=C+P;if(t<=C)break;if(t<F){S=r.end;break}else{let k=r.text.length-P;S+=k,p+=k}}return Math.min(S,d.length)}function Ci(t,m,d,S,y=[]){let p=(t||"").slice(0,m),r=S(p).length,C=S(t||""),w=[...y].sort((j,H)=>H.start-j.start);for(let j of w){let H=S(t.slice(0,j.start)).length,W=S(j.text),X=H+W.length,ie=us(j.text).split(`
@@ -39,9 +39,9 @@ import{a as Ca}from"./chunk-UEV335RW.js";import{b as ma,c as fa,d as xa}from"./c
39
39
  `).map((W,X)=>l.createElement(D,{key:X,flexDirection:"row",width:"100%"},l.createElement(D,{flexShrink:0,width:2},l.createElement(de,{bold:!0,color:r.userMsgText},X===0?">":" ")),l.createElement(D,{flexGrow:1,marginLeft:1},l.createElement(so,{text:W,color:t.color||r.userMsgText,theme:p}))))),l.createElement(D,{width:d-1,height:1,overflow:"hidden"},l.createElement(de,{color:r.userMsgBorder},"\u2580".repeat(Math.max(1,d-1))))):t.role==="think"?l.createElement(D,{flexDirection:"column",marginTop:0,marginBottom:0,paddingX:0,width:"100%"},t.isStreaming&&!t.duration?l.createElement(de,{bold:!0,color:r.text},"\u2727 Thinking..."):l.createElement(de,{bold:!0,color:r.text},"\u2726 Thought",t.duration?l.createElement(de,{color:r.textMuted}," for ",l.createElement(de,{bold:!0,color:r.text},xs(t.duration))):"s..."),l.createElement(D,{borderStyle:"single",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:r.borderMuted,paddingLeft:2,paddingTop:0,paddingBottom:0,flexDirection:"column",width:"100%"},qc(H,d))):l.createElement(D,{flexDirection:"column",paddingX:1,marginTop:0,width:"100%"},l.createElement(fs,{text:H.replace(/ \|\n\n/g,` |
40
40
  `),columns:d,theme:p}),t.memoryUpdated&&l.createElement(D,{marginTop:1,width:"100%"},l.createElement(de,{color:r.text,italic:!0},"[Memory Updated]")),t.role==="agent"&&t.workedDuration?l.createElement(D,{marginTop:1,marginBottom:2,width:"100%"},l.createElement(de,{color:r.textMuted},"["),l.createElement(de,{color:r.textMuted},"Worked for ",l.createElement(de,{bold:!0,color:r.text},xs(t.workedDuration))),l.createElement(de,{color:r.textMuted},"]")):null))}),gs=l.memo(({block:t,columns:m=80,showFullThinking:d,aiProvider:S,version:y,theme:p="Dark"})=>{let r=gt(p),{msg:C,type:w,text:M,isStreamingMsg:P,workedDuration:F}=t;if((w==="think-header"||w==="think-line"||w==="think-footer-padding")&&!ka())return null;if(w==="chunk")return l.createElement(D,{flexDirection:"column",width:"100%"},t.blocks.map(k=>l.createElement(gs,{key:k.key,block:k,columns:m,showFullThinking:d,aiProvider:S,version:y,theme:p})));if(w==="full-message")return l.createElement(Aa,{msg:C,showFullThinking:d,columns:m,aiProvider:S,version:y,theme:p});if(w==="think-header")return l.createElement(D,{flexDirection:"column",paddingX:1,width:"100%",marginTop:0,marginBottom:0},(()=>{let k=t.duration||C?.duration||F;return P&&!k?l.createElement(de,{bold:!0,color:r.text},"\u2727 Thinking..."):l.createElement(de,{bold:!0,color:r.text},"\u2726 Thought",k?l.createElement(de,{color:r.textMuted}," for ",l.createElement(de,{bold:!0,color:r.text},xs(k)),"..."):"s...")})(),d&&l.createElement(D,{flexDirection:"row",width:"100%"},l.createElement(de,{color:r.textMuted},"\u2502 ")));if(w==="think-line"){if(!d)return null;if(!M||M.trim()==="")return l.createElement(D,{flexDirection:"row",width:"100%",paddingX:1},l.createElement(de,{color:r.textMuted},"\u2502 "));let k=va(M,P,t.isActiveBlock)?.replaceAll(" "," ")||"";return l.createElement(D,{flexDirection:"row",width:"100%",paddingX:1},l.createElement(de,{color:r.textMuted},"\u2502 "),l.createElement(D,{flexGrow:1,marginLeft:1},l.createElement(so,{text:k,color:r.textMuted,italic:!0,theme:p})))}if(w==="think-footer-padding")return d?l.createElement(D,{flexDirection:"row",width:"100%",paddingX:1},l.createElement(de,{color:r.textMuted},"\u2502 ")):null;if(w==="agent-line"){if(!M||M.trim()==="")return l.createElement(D,{height:1});let k=va(M,P,t.isActiveBlock)?.replaceAll(" "," ")||"",O=k.trim();if(O==="---"||O==="***"||O==="___")return l.createElement(D,{flexDirection:"column",paddingX:1,width:"100%",marginY:0},l.createElement(D,{borderStyle:"single",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%",borderColor:r.borderMuted}));let K=O.match(Zc);if(K){let W=K[1].length,X=K[2],ue=["yellow",r.secondary||"magenta",r.info||"cyan","green","blue",r.text][W-1]||r.text;return l.createElement(D,{flexDirection:"column",paddingX:1,width:"100%",marginTop:0,marginBottom:0},l.createElement(de,{bold:!0,color:ue,underline:!0},l.createElement(so,{text:X,color:ue,theme:p})))}if(O.startsWith(">")){let W=O.replace(/^>\s*/,"");return l.createElement(D,{flexDirection:"column",paddingX:1,width:"100%"},l.createElement(D,{borderStyle:"bold",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:r.borderMuted,paddingLeft:1,marginY:0},l.createElement(so,{text:W,color:r.textMuted,italic:!0,theme:p})))}let j=/^[\*\-\+]\s/.test(O),H=/^\d+\.\s/.test(O);if(j||H){let W=j?" \u2022 ":O.match(/^\d+\.\s/)[0],X=O.replace(/^[\*\-\+\d+\.]+\s*/,"");return l.createElement(D,{flexDirection:"row",paddingX:1,width:"100%"},l.createElement(de,{color:r.info||r.textMuted},W),l.createElement(D,{flexGrow:1},l.createElement(so,{text:X,color:r.text,theme:p})))}return l.createElement(D,{flexDirection:"column",paddingX:1,width:"100%"},l.createElement(so,{text:k,color:r.text,theme:p}))}if(w==="table-header"||w==="table-row"){let k=w==="table-header",O=r.codeText||r.secondary||r.info||"cyan",K=t.colHeaders||[],j=k?K:t.cells||[],H=Math.max(1,t.colCount||K.length||j.length||1),W=Array.from({length:H},(Se,xe)=>j[xe]||""),X=Math.max(20,(m||80)-8),ie=H>=4,ue=/^(#|no\.?|num\.?|status|state|type|ok|done|✔|✘|active)$/i,te=[],_=0,be=0;for(let Se=0;Se<H;Se++){let xe=(K[Se]||"").trim();if(ie&&(ue.test(xe)||xe==="#")){let Me=Math.max(xe.length+4,8);te.push(Me),_+=Me}else te.push(null),be++}let Pe=Math.max(be*12,X-_),Ae=be>0?Math.max(10,Math.floor(Pe/be)):10;for(let Se=0;Se<H;Se++)te[Se]===null&&(te[Se]=Ae);let tt=te.reduce((Se,xe)=>Se+xe,0);return k?l.createElement(D,{flexDirection:"column",paddingX:1,width:"100%",marginTop:0,marginBottom:1},l.createElement(D,{flexDirection:"row",borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:r.borderMuted,paddingBottom:0,width:tt},K.map((Se,xe)=>{let Me=te[xe]||6;return l.createElement(D,{key:xe,width:Me,paddingRight:1,flexDirection:"column"},l.createElement(so,{text:Nt(Se,Math.max(2,Me-1)),color:O,theme:p}))}))):l.createElement(D,{flexDirection:"row",paddingX:1,width:"100%",marginBottom:1},W.map((Se,xe)=>{let Me=te[xe]||6;return l.createElement(D,{key:xe,width:Me,paddingRight:1,flexDirection:"column"},l.createElement(so,{text:Nt(Se,Math.max(2,Me-1)),color:r.text,theme:p}))}))}if(w==="table-close")return l.createElement(D,{height:0});if(w==="table")return l.createElement(D,{flexDirection:"column",paddingX:1,width:"100%"},l.createElement(Da,{buffer:M.split(`
41
41
  `),terminalWidth:m,theme:p}));if(w==="diff-line"){let{isFirstLine:k,isLastLine:O}=t,K=(j=!1)=>l.createElement(D,{backgroundColor:r.codeBg,paddingX:1,width:m,marginBottom:j?1:0},l.createElement(D,{width:3,flexShrink:0}),l.createElement(D,{width:1,flexShrink:0,marginLeft:1}),l.createElement(D,{flexGrow:1,marginLeft:1},l.createElement(de,null," ")));return l.createElement(D,{flexDirection:"column"},k&&K(!1),l.createElement(Ia,{line:M,pairContent:t.pairContent,parentText:void 0,columns:m,theme:p}),O&&K(!0))}if(w==="code-fence-open"){let k={paddingLeft:2,width:"100%"};return l.createElement(D,{flexDirection:"column",marginTop:0,marginBottom:0,width:"100%"},l.createElement(D,{flexDirection:"row",...k},l.createElement(de,null," ")),l.createElement(D,{flexDirection:"row",...k},l.createElement(de,{color:"gray",bold:!0},"\u25B6_ ",(M||"TEXT").toUpperCase())))}if(w==="code-line"){let{lineNum:k,lang:O}=t,K=m-12,j=(M||"").replaceAll(" "," "),W=Nt(j,Math.max(10,K)).split(`
42
- `);return l.createElement(D,{flexDirection:"column",width:"100%"},W.map((X,ie)=>l.createElement(D,{key:ie,flexDirection:"row",borderColor:r.codeBorder,paddingLeft:2,width:"100%"},l.createElement(D,{width:5,flexShrink:0},l.createElement(de,{color:"gray",dimColor:!0},ie===0?String(k).padStart(4," ")+" ":" ")),l.createElement(D,{flexGrow:1},kt(X,O,r.text)))))}if(w==="code-fence-close")return l.createElement(D,{flexDirection:"row",paddingLeft:2,marginBottom:1,width:"100%"},l.createElement(de,null," "));if(w==="write-header")return l.createElement(D,{flexDirection:"column",paddingX:1,width:m},l.createElement(or,{text:M,columns:m,theme:p}));if(w==="write-line"){let{gutterWidth:k,lineNum:O,isFirstLine:K,isLastLine:j,extension:H,wrappedLines:W}=t,X=(ie=!1)=>l.createElement(D,{flexDirection:"row",width:m,borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:r.codeBorder,paddingLeft:2,paddingRight:0,backgroundColor:r.codeBg,marginBottom:ie?1:0},l.createElement(D,{width:k+2,flexShrink:0},l.createElement(de,null," ".repeat(k+2))),l.createElement(D,{flexGrow:1},l.createElement(de,null," ")));return l.createElement(D,{flexDirection:"column"},K&&X(!1),l.createElement(D,{flexDirection:"row",width:m,borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:r.codeBorder,paddingLeft:2,paddingRight:0,backgroundColor:r.codeBg},l.createElement(D,{width:k+2,flexShrink:0},l.createElement(de,{color:"gray",dimColor:!0},String(O).padStart(k," ")," ")),l.createElement(D,{flexGrow:1,flexDirection:"column"},(W||[M]).map((ie,ue)=>l.createElement(D,{key:ue},kt((ie||"").replaceAll(" "," "),H,r.text))))),j&&X(!0))}return w==="write-footer"?l.createElement(D,{flexDirection:"column",paddingX:1,width:m,marginTop:1,marginBottom:1},l.createElement(or,{text:M,columns:m,theme:p})):w==="worked-duration"?l.createElement(D,{marginTop:1,marginBottom:2,paddingX:1,width:"100%"},l.createElement(de,{color:r.textMuted},"["),l.createElement(de,{color:r.textMuted},"Worked for ",l.createElement(de,{bold:!0,color:r.text},xs(F))),l.createElement(de,{color:r.textMuted},"]")):null}),bm=l.memo(({messages:t,showFullThinking:m,columns:d=80,aiProvider:S,version:y,theme:p="Dark"})=>l.createElement(D,{flexDirection:"column",width:"100%"},t.map((r,C)=>l.createElement(Aa,{key:r.id||C,msg:r,showFullThinking:m,columns:d,aiProvider:S,version:y,theme:p}))));import $t from"react";import{Box as xn,Text as Ho}from"ink";import{useState as Ir,useEffect as Ar,useRef as hs}from"react";var Lr=null;function La(){Lr&&Lr()}var Ud=t=>{if(t<=370)return"#00a564";if(t>=5e3)return"#ff0000";let m=[{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 d=0;d<m.length-1;d++){let S=m[d],y=m[d+1];if(t>=S.t&&t<=y.t){let p=(t-S.t)/(y.t-S.t);p=p*p*(3-2*p);let r=Math.round(S.r+(y.r-S.r)*p),C=Math.round(S.g+(y.g-S.g)*p),w=Math.round(S.b+(y.b-S.b)*p);return`#${((1<<24)+(r<<16)+(C<<8)+w).toString(16).slice(1)}`}}return"#ff0000"},_d=$t.memo(({mode:t,thinkingLevel:m,tokens:d="0.0k",tokensTotal:S="0.0k",cachedTokens:y=0,promptTokens:p=0,chatCacheTokenLatest:r=0,cacheCalculateMode:C="Session",chatId:w="NEW-SESSION",isMemoryEnabled:M=!0,apiTier:P="Free",aiProvider:F="Google",activeModel:k="",isProcessing:O=!1,lastChunkTime:K=0,theme:j="Dark",wps:H=0,showTPMEstimate:W=!1})=>{let X=gt(j),ie="",[ue,te]=Ir(0),[_,be]=Ir(0),[Pe,Ae]=Ir("MB"),[tt,Se]=Ir("green"),[xe,Me]=Ir(0),Bt=hs([]),We=hs(370),Oe=hs([]),ye=hs(K);Ar(()=>{ye.current=K},[K]),Ar(()=>{if(!O){Oe.current=[];return}if(H>0){let fe=Oe.current;fe.push(H),fe.length>3&&fe.shift()}},[O,H,K]),Ar(()=>{if(!O){Me(0);return}let fe=setInterval(()=>{let we=ye.current,oe=we>0?Date.now()-we:0;if(we>0&&oe>=1e3)Oe.current=[],Me(0);else if(we>0&&oe>500){Oe.current.length>0&&Oe.current.shift();let ge=Oe.current;if(ge.length>0){let Y=ge.reduce((Xe,Fe)=>Xe+Fe,0);Me(Math.round(Y/ge.length))}else Me(0)}else{let ge=Oe.current;if(ge.length>0){let Y=ge.reduce((Xe,Fe)=>Xe+Fe,0);Me(Math.round(Y/ge.length))}else H>0&&Me(Math.round(H))}},750);return()=>clearInterval(fe)},[O]),Ar(()=>{if(!O){Bt.current=[];return}if(K>0){let oe=Bt.current;(oe.length===0||oe[oe.length-1]!==K)&&(oe.push(K),oe.length>10&&oe.shift())}let fe=()=>{if(!K){Se("#00a564");return}let oe=Bt.current,ge=0;if(oe.length>1){let rt=0;for(let Qe=1;Qe<oe.length;Qe++)rt+=oe[Qe]-oe[Qe-1];ge=rt/(oe.length-1)}let Y=Date.now()-K,Fe=Y>=2500,yt=!Fe&&ge>0?Math.min(Y,ge*3):Y,it=Math.max(ge,yt),Tt=Fe?.4:.2;We.current=We.current*(1-Tt)+it*Tt,Se(Ud(We.current))};fe();let we=setInterval(fe,100);return()=>clearInterval(we)},[O,K]);let R=()=>{let fe=process.memoryUsage(),we=fe.heapTotal/(1024*1024)>=1024,oe=we?"GB":"MB",ge=(Y,Xe)=>{let Fe=Y/(1048576*(Xe?1024:1));return Xe?parseFloat(Fe.toFixed(2)):Math.round(Fe)};Ae(oe),be(ge(fe.heapTotal,we)),te(ge(fe.heapUsed,we))};return Ar(()=>{Lr=R,R();let fe=setInterval(()=>{R()},6e4);return()=>{clearInterval(fe),Lr===R&&(Lr=null)}},[]),$t.createElement(xn,{flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},$t.createElement(xn,null,$t.createElement(xn,{marginRight:1},$t.createElement(Ho,{color:X.textMuted},t.toLowerCase()==="flow"?"Studio":t.toLowerCase()==="icu"?"Computer Use":t.toLowerCase()==="flux"?"Workspace":"Omni")),$t.createElement(Ho,{color:X.textMuted,dimColor:!0},"\u2503 "),$t.createElement(xn,null,$t.createElement(Ho,{color:X.text,italic:!0},ea(process.cwd(),35)))),$t.createElement(xn,null,O&&!W?$t.createElement(xn,null,$t.createElement(Ho,{color:tt},"\u25CF ")):null,O&&W&&$t.createElement($t.Fragment,null,$t.createElement(Ho,{color:X.textMuted},"~",xe," tok/s"),$t.createElement(Ho,{color:X.textMuted,dimColor:!0}," \u2503")),d>0&&$t.createElement($t.Fragment,null,$t.createElement(xn,{marginX:1},$t.createElement(Ho,{color:X.text},Ft(S)," tok",(()=>{let fe=0;if(C==="Current")fe=typeof r=="number"?r:0;else{let we=typeof p=="number"?p:0,oe=typeof y=="number"?y:0;fe=we>0?oe/we*100:0}return fe<1?null:$t.createElement(Ho,{color:X.success||"green",dimColor:!0}," [",fe.toFixed(0),"% cached]")})())),$t.createElement(Ho,{color:X.textMuted,dimColor:!0},"\u2503")),$t.createElement(xn,{marginLeft:1},$t.createElement(Ho,{color:X.textMuted,bold:!0},ue," ",Pe))))}),Pa=_d;import ht,{useState as ps,useMemo as Hd,useEffect as Oa}from"react";import{Box as io,Text as lo,useInput as Wd}from"ink";import Xd from"ink-select-input";var Gd=({label:t,isSelected:m,theme:d="Dark"})=>{let S=gt(d),y=t==="Cancel"||t==="Back"||t.toLowerCase().includes("exit")||t.toLowerCase().includes("back");return ht.createElement(io,{marginTop:y?1:0,backgroundColor:m?S.highlightBg:void 0,paddingX:1,width:"100%"},ht.createElement(lo,{color:m?S.text:S.textMuted,bold:m},m?"\u276F ":" ",t))},Kd=8;function Ht({title:t,subtitle:m,items:d=[],onSelect:S,theme:y="Dark",searchable:p=!1,maxVisible:r=Kd}){let C=gt(y),[w,M]=ps(""),[P,F]=ps(0),[k,O]=ps("list"),K=Hd(()=>{if(!p||!w.trim())return d;let ue=w.toLowerCase().trim();return d.filter(te=>te.label&&te.label.toLowerCase().includes(ue))},[d,w,p]);Oa(()=>{F(0)},[w]);let[j,H]=ps(0);Oa(()=>{H(ue=>K.length<=r?0:P<ue?P:P>=ue+r?P-r+1:ue)},[P,K.length,r]),Wd((ue,te)=>{if(p){if(te.upArrow){O("list"),F(_=>K.length===0?0:_>0?_-1:K.length-1);return}if(te.downArrow){O("list"),F(_=>K.length===0?0:_<K.length-1?_+1:0);return}if(te.return){K.length>0&&K[P]&&S(K[P]);return}if(te.escape){if(w)M(""),O("list"),F(0);else{let _=d.find(be=>be.value==="Back"||be.label==="Back"||be.value==="Cancel"||be.label==="Cancel");_&&S(_)}return}if(te.backspace||te.delete){O("search"),M(_=>_.slice(0,-1));return}if(ue&&!te.ctrl&&!te.meta&&!te.tab){O("search"),M(_=>_+ue);return}}},{isActive:p});let W=K.length,X=j;W<=r?X=0:X=Math.max(0,Math.min(j,W-r));let ie=K.slice(X,X+r);return p?ht.createElement(io,{flexDirection:"column",borderStyle:"round",borderColor:C.borderMuted,padding:0,marginTop:0,flexShrink:0,width:"100%"},ht.createElement(io,{paddingX:1,paddingY:0,marginBottom:0,flexDirection:"row",justifyContent:"space-between"},t?ht.createElement(lo,{color:C.text,bold:!0},typeof t=="string"?t.toUpperCase():t):ht.createElement(io,null),W>0&&ht.createElement(lo,{color:C.textMuted},P+1,"/",W)),m&&ht.createElement(io,{paddingX:1,marginBottom:0},ht.createElement(lo,{color:C.textMuted,italic:!0}," ",m)),ht.createElement(io,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"row"},ht.createElement(lo,{color:k==="search"?C.primary||"cyan":C.textMuted,bold:k==="search"},"\u{1F50D} Search:"),ht.createElement(lo,{color:C.text,bold:!0}," ",w),k==="search"?ht.createElement(lo,{color:C.primary||"cyan"},"\u2588"):w?null:ht.createElement(lo,{color:C.textMuted,italic:!0}," (type to search...)")),ht.createElement(io,{flexDirection:"column",width:"100%"},K.length===0?ht.createElement(io,{paddingX:1,marginY:0},ht.createElement(lo,{color:C.warning||"yellow",italic:!0}," No matching items found")):ie.map((ue,te)=>{let _=X+te,be=_===P,Pe=ue.label==="Cancel"||ue.label==="Back"||ue.label.toLowerCase().includes("exit")||ue.label.toLowerCase().includes("back");return ht.createElement(io,{key:ue.value??ue.label??_,marginTop:Pe?1:0,backgroundColor:be?C.highlightBg:void 0,paddingX:1,width:"100%"},ht.createElement(lo,{color:be?C.text:C.textMuted,bold:be},be?"\u276F ":" ",ue.label))})),ht.createElement(io,{paddingX:1,marginTop:1},ht.createElement(lo,{color:C.textMuted,italic:!0},k==="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)"))):ht.createElement(io,{flexDirection:"column",borderStyle:"round",borderColor:C.borderMuted,padding:0,marginTop:0,flexShrink:0,width:"100%"},t&&ht.createElement(io,{paddingX:1,paddingY:0,marginBottom:m?0:1,flexDirection:"row",justifyContent:"space-between"},ht.createElement(lo,{color:C.text,bold:!0},typeof t=="string"?t.toUpperCase():t),d.length>r&&ht.createElement(lo,{color:C.textMuted,italic:!0},d.length," options")),m&&ht.createElement(io,{paddingX:1,marginBottom:1},ht.createElement(lo,{color:C.textMuted,italic:!0}," ",m)),ht.createElement(io,{flexDirection:"column",width:"100%"},ht.createElement(Xd,{items:d,onSelect:S,limit:r,itemComponent:ue=>ht.createElement(Gd,{...ue,theme:y}),indicatorComponent:()=>null})),ht.createElement(io,{paddingX:1,marginTop:1},ht.createElement(lo,{color:C.textMuted,italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}import I,{useState as qt,useEffect as Pr}from"react";import{Box as Ue,Text as ne,useInput as Vd}from"ink";import jd from"ink-text-input";import Yd from"v8";import Na from"os";var Wo=[...Object.keys(oa),"Mystery"],Xo=[{id:"appearance",label:"Appearance",desc:"Customize UI theme & rendering options"},{id:"memory",label:"Personalization",desc:"Manage system context & agent's memory"},{id:"secondaryModels",label:"Secondary Models",desc:"Sub-agents & auto-completion models"},{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"}],Fa=t=>{let m=t.autoApproveCommands||"",d=t.autoDisallowCommands||"",S=t.alwaysAskCommands||"",y=t.autoExec===!1&&t.allowExternalAccess===!1&&t.networkAccess===!1&&m===""&&d==="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&&t.overwriteProtection!==!1,p=t.autoExec===!0&&t.allowExternalAccess===!1&&t.networkAccess!==!1&&m==="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"&&d==="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&&t.overwriteProtection!==!1,r=t.autoExec===!0&&t.allowExternalAccess===!0&&t.networkAccess!==!1&&m==="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"&&d===""&&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&&t.overwriteProtection===!1;return y?"Strict":p?"Balanced":r?"Autonomous":t.sandboxPreset||"Custom"},Or=t=>!t||t.trim()===""?"None":t.length>40?t.substring(0,40)+"...":t;function bs({systemSettings:t,setSystemSettings:m,apiTier:d,setActiveView:S,setInputConfig:y,saveSettings:p,quotas:r,setMessages:C,aiProvider:w,autoCompletion:M,setAutoCompletion:P,profileData:F,setProfileData:k,initialSelectingTheme:O=!1,onCloseTheme:K=null,setProviderReturnView:j=null,setApiKey:H=null,initAI:W=null}){let X=t.theme==="Chaos"||t.theme==="Mystery"?"Mystery":t.theme||"Dark",ie=Wo.indexOf(X),[ue,te]=qt("categories"),[_,be]=qt(0),[Pe,Ae]=qt(0),[tt,Se]=qt("Sandbox"),[xe,Me]=qt(null),[Bt,We]=qt(""),[Oe,ye]=qt(O),[R,fe]=qt(ie>=0?ie:0),[we,oe]=qt(t.theme||"Dark"),[ge,Y]=qt(!1),[Xe,Fe]=qt("subAgent"),[yt,it]=qt(0),[Tt,rt]=qt(0),[Qe,ae]=qt(""),[Ee,mt]=qt("list"),[ft,He]=qt({});Pr(()=>{(async()=>{let T=["Google","DeepSeek","OpenRouter","NVIDIA","Mistral","Ollama","InferX","SenseNova","AIHubMix","Poolside","9router","ExpLabs","TokenHarbor","Infron","APInex","xKiro","c_openai"],A={};for(let Te of T)try{await mn(Te,{silent:!0})&&(A[Te]=!0)}catch{}He(A)})()},[]);let Dt=I.useMemo(()=>{let ce=["Google","DeepSeek","OpenRouter","NVIDIA","Mistral","Ollama","InferX","SenseNova","AIHubMix","Poolside","9router","ExpLabs","TokenHarbor","Infron","APInex","xKiro","c_openai"],A=!!(process.env.SUBAGENT_MODEL&&process.env.SUBAGENT_MODEL.trim())?`ENV (${process.env.SUBAGENT_MODEL.trim()})`:"ENV",Te=[{label:"Default (use the current model)",value:"Default",isHeader:!1},{label:A,value:"ENV",isHeader:!1}],Le=r?.providerTiers?.[w]||d||"Free",nt=un(w,Le,t?.customOpenAIBaseUrl)||[];nt.length>0&&(Te.push({label:`\u2500\u2500 ${w.toUpperCase()}${Le!=="Free"?` (${Le})`:""} \u2500\u2500`,isHeader:!0}),nt.forEach(ct=>{let ze=typeof ct=="string"?ct:ct.cmd||ct.name||ct.id||String(ct);ze&&!ze.trim().startsWith("---")&&!ze.startsWith(`
42
+ `);return l.createElement(D,{flexDirection:"column",width:"100%"},W.map((X,ie)=>l.createElement(D,{key:ie,flexDirection:"row",borderColor:r.codeBorder,paddingLeft:2,width:"100%"},l.createElement(D,{width:5,flexShrink:0},l.createElement(de,{color:"gray",dimColor:!0},ie===0?String(k).padStart(4," ")+" ":" ")),l.createElement(D,{flexGrow:1},kt(X,O,r.text)))))}if(w==="code-fence-close")return l.createElement(D,{flexDirection:"row",paddingLeft:2,marginBottom:1,width:"100%"},l.createElement(de,null," "));if(w==="write-header")return l.createElement(D,{flexDirection:"column",paddingX:1,width:m},l.createElement(or,{text:M,columns:m,theme:p}));if(w==="write-line"){let{gutterWidth:k,lineNum:O,isFirstLine:K,isLastLine:j,extension:H,wrappedLines:W}=t,X=(ie=!1)=>l.createElement(D,{flexDirection:"row",width:m,borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:r.codeBorder,paddingLeft:2,paddingRight:0,backgroundColor:r.codeBg,marginBottom:ie?1:0},l.createElement(D,{width:k+2,flexShrink:0},l.createElement(de,null," ".repeat(k+2))),l.createElement(D,{flexGrow:1},l.createElement(de,null," ")));return l.createElement(D,{flexDirection:"column"},K&&X(!1),l.createElement(D,{flexDirection:"row",width:m,borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:r.codeBorder,paddingLeft:2,paddingRight:0,backgroundColor:r.codeBg},l.createElement(D,{width:k+2,flexShrink:0},l.createElement(de,{color:"gray",dimColor:!0},String(O).padStart(k," ")," ")),l.createElement(D,{flexGrow:1,flexDirection:"column"},(W||[M]).map((ie,ue)=>l.createElement(D,{key:ue},kt((ie||"").replaceAll(" "," "),H,r.text))))),j&&X(!0))}return w==="write-footer"?l.createElement(D,{flexDirection:"column",paddingX:1,width:m,marginTop:1,marginBottom:1},l.createElement(or,{text:M,columns:m,theme:p})):w==="worked-duration"?l.createElement(D,{marginTop:1,marginBottom:2,paddingX:1,width:"100%"},l.createElement(de,{color:r.textMuted},"["),l.createElement(de,{color:r.textMuted},"Worked for ",l.createElement(de,{bold:!0,color:r.text},xs(F))),l.createElement(de,{color:r.textMuted},"]")):null}),bm=l.memo(({messages:t,showFullThinking:m,columns:d=80,aiProvider:S,version:y,theme:p="Dark"})=>l.createElement(D,{flexDirection:"column",width:"100%"},t.map((r,C)=>l.createElement(Aa,{key:r.id||C,msg:r,showFullThinking:m,columns:d,aiProvider:S,version:y,theme:p}))));import $t from"react";import{Box as xn,Text as Ho}from"ink";import{useState as Ir,useEffect as Ar,useRef as hs}from"react";var Lr=null;function La(){Lr&&Lr()}var Ud=t=>{if(t<=370)return"#00a564";if(t>=5e3)return"#ff0000";let m=[{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 d=0;d<m.length-1;d++){let S=m[d],y=m[d+1];if(t>=S.t&&t<=y.t){let p=(t-S.t)/(y.t-S.t);p=p*p*(3-2*p);let r=Math.round(S.r+(y.r-S.r)*p),C=Math.round(S.g+(y.g-S.g)*p),w=Math.round(S.b+(y.b-S.b)*p);return`#${((1<<24)+(r<<16)+(C<<8)+w).toString(16).slice(1)}`}}return"#ff0000"},_d=$t.memo(({mode:t,thinkingLevel:m,tokens:d="0.0k",tokensTotal:S="0.0k",cachedTokens:y=0,promptTokens:p=0,chatCacheTokenLatest:r=0,cacheCalculateMode:C="Session",chatId:w="NEW-SESSION",isMemoryEnabled:M=!0,apiTier:P="Free",aiProvider:F="Google",activeModel:k="",isProcessing:O=!1,lastChunkTime:K=0,theme:j="Dark",wps:H=0,showTPMEstimate:W=!1})=>{let X=gt(j),ie="",[ue,te]=Ir(0),[_,be]=Ir(0),[Pe,Ae]=Ir("MB"),[tt,Se]=Ir("green"),[xe,Me]=Ir(0),Bt=hs([]),We=hs(370),Oe=hs([]),ye=hs(K);Ar(()=>{ye.current=K},[K]),Ar(()=>{if(!O){Oe.current=[];return}if(H>0){let fe=Oe.current;fe.push(H),fe.length>3&&fe.shift()}},[O,H,K]),Ar(()=>{if(!O){Me(0);return}let fe=setInterval(()=>{let we=ye.current,oe=we>0?Date.now()-we:0;if(we>0&&oe>=1e3)Oe.current=[],Me(0);else if(we>0&&oe>500){Oe.current.length>0&&Oe.current.shift();let ge=Oe.current;if(ge.length>0){let Y=ge.reduce((Xe,Fe)=>Xe+Fe,0);Me(Math.round(Y/ge.length))}else Me(0)}else{let ge=Oe.current;if(ge.length>0){let Y=ge.reduce((Xe,Fe)=>Xe+Fe,0);Me(Math.round(Y/ge.length))}else H>0&&Me(Math.round(H))}},750);return()=>clearInterval(fe)},[O]),Ar(()=>{if(!O){Bt.current=[];return}if(K>0){let oe=Bt.current;(oe.length===0||oe[oe.length-1]!==K)&&(oe.push(K),oe.length>10&&oe.shift())}let fe=()=>{if(!K){Se("#00a564");return}let oe=Bt.current,ge=0;if(oe.length>1){let rt=0;for(let Qe=1;Qe<oe.length;Qe++)rt+=oe[Qe]-oe[Qe-1];ge=rt/(oe.length-1)}let Y=Date.now()-K,Fe=Y>=2500,yt=!Fe&&ge>0?Math.min(Y,ge*3):Y,it=Math.max(ge,yt),Tt=Fe?.4:.2;We.current=We.current*(1-Tt)+it*Tt,Se(Ud(We.current))};fe();let we=setInterval(fe,100);return()=>clearInterval(we)},[O,K]);let R=()=>{let fe=process.memoryUsage(),we=fe.heapTotal/(1024*1024)>=1024,oe=we?"GB":"MB",ge=(Y,Xe)=>{let Fe=Y/(1048576*(Xe?1024:1));return Xe?parseFloat(Fe.toFixed(2)):Math.round(Fe)};Ae(oe),be(ge(fe.heapTotal,we)),te(ge(fe.heapUsed,we))};return Ar(()=>{Lr=R,R();let fe=setInterval(()=>{R()},6e4);return()=>{clearInterval(fe),Lr===R&&(Lr=null)}},[]),$t.createElement(xn,{flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},$t.createElement(xn,null,t.toLowerCase()!=="flux"&&$t.createElement(xn,{marginRight:1},$t.createElement(Ho,{color:X.textMuted},t.toLowerCase()==="flow"?"Studio":t.toLowerCase()==="icu"?"Computer Use":t.toLowerCase()==="flux"?"Workspace":"Omni")),t.toLowerCase()!=="flux"&&$t.createElement(Ho,{color:X.textMuted,dimColor:!0},"\u2503 "),$t.createElement(xn,null,$t.createElement(Ho,{color:X.text,italic:!0},ea(process.cwd(),35)))),$t.createElement(xn,null,O&&!W?$t.createElement(xn,null,$t.createElement(Ho,{color:tt},"\u25CF ")):null,O&&W&&$t.createElement($t.Fragment,null,$t.createElement(Ho,{color:X.textMuted},"~",xe," tok/s"),$t.createElement(Ho,{color:X.textMuted,dimColor:!0}," \u2503")),d>0&&$t.createElement($t.Fragment,null,$t.createElement(xn,{marginX:1},$t.createElement(Ho,{color:X.text},Ft(S)," tok",(()=>{let fe=0;if(C==="Current")fe=typeof r=="number"?r:0;else{let we=typeof p=="number"?p:0,oe=typeof y=="number"?y:0;fe=we>0?oe/we*100:0}return fe<1?null:$t.createElement(Ho,{color:X.success||"green",dimColor:!0}," [",fe.toFixed(0),"% cached]")})())),$t.createElement(Ho,{color:X.textMuted,dimColor:!0},"\u2503")),$t.createElement(xn,{marginLeft:1},$t.createElement(Ho,{color:X.textMuted,bold:!0},ue," ",Pe))))}),Pa=_d;import ht,{useState as ps,useMemo as Hd,useEffect as Oa}from"react";import{Box as io,Text as lo,useInput as Wd}from"ink";import Xd from"ink-select-input";var Gd=({label:t,isSelected:m,theme:d="Dark"})=>{let S=gt(d),y=t==="Cancel"||t==="Back"||t.toLowerCase().includes("exit")||t.toLowerCase().includes("back");return ht.createElement(io,{marginTop:y?1:0,backgroundColor:m?S.highlightBg:void 0,paddingX:1,width:"100%"},ht.createElement(lo,{color:m?S.text:S.textMuted,bold:m},m?"\u276F ":" ",t))},Kd=8;function Ht({title:t,subtitle:m,items:d=[],onSelect:S,theme:y="Dark",searchable:p=!1,maxVisible:r=Kd}){let C=gt(y),[w,M]=ps(""),[P,F]=ps(0),[k,O]=ps("list"),K=Hd(()=>{if(!p||!w.trim())return d;let ue=w.toLowerCase().trim();return d.filter(te=>te.label&&te.label.toLowerCase().includes(ue))},[d,w,p]);Oa(()=>{F(0)},[w]);let[j,H]=ps(0);Oa(()=>{H(ue=>K.length<=r?0:P<ue?P:P>=ue+r?P-r+1:ue)},[P,K.length,r]),Wd((ue,te)=>{if(p){if(te.upArrow){O("list"),F(_=>K.length===0?0:_>0?_-1:K.length-1);return}if(te.downArrow){O("list"),F(_=>K.length===0?0:_<K.length-1?_+1:0);return}if(te.return){K.length>0&&K[P]&&S(K[P]);return}if(te.escape){if(w)M(""),O("list"),F(0);else{let _=d.find(be=>be.value==="Back"||be.label==="Back"||be.value==="Cancel"||be.label==="Cancel");_&&S(_)}return}if(te.backspace||te.delete){O("search"),M(_=>_.slice(0,-1));return}if(ue&&!te.ctrl&&!te.meta&&!te.tab){O("search"),M(_=>_+ue);return}}},{isActive:p});let W=K.length,X=j;W<=r?X=0:X=Math.max(0,Math.min(j,W-r));let ie=K.slice(X,X+r);return p?ht.createElement(io,{flexDirection:"column",borderStyle:"round",borderColor:C.borderMuted,padding:0,marginTop:0,flexShrink:0,width:"100%"},ht.createElement(io,{paddingX:1,paddingY:0,marginBottom:0,flexDirection:"row",justifyContent:"space-between"},t?ht.createElement(lo,{color:C.text,bold:!0},typeof t=="string"?t.toUpperCase():t):ht.createElement(io,null),W>0&&ht.createElement(lo,{color:C.textMuted},P+1,"/",W)),m&&ht.createElement(io,{paddingX:1,marginBottom:0},ht.createElement(lo,{color:C.textMuted,italic:!0}," ",m)),ht.createElement(io,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"row"},ht.createElement(lo,{color:k==="search"?C.primary||"cyan":C.textMuted,bold:k==="search"},"\u{1F50D} Search:"),ht.createElement(lo,{color:C.text,bold:!0}," ",w),k==="search"?ht.createElement(lo,{color:C.primary||"cyan"},"\u2588"):w?null:ht.createElement(lo,{color:C.textMuted,italic:!0}," (type to search...)")),ht.createElement(io,{flexDirection:"column",width:"100%"},K.length===0?ht.createElement(io,{paddingX:1,marginY:0},ht.createElement(lo,{color:C.warning||"yellow",italic:!0}," No matching items found")):ie.map((ue,te)=>{let _=X+te,be=_===P,Pe=ue.label==="Cancel"||ue.label==="Back"||ue.label.toLowerCase().includes("exit")||ue.label.toLowerCase().includes("back");return ht.createElement(io,{key:ue.value??ue.label??_,marginTop:Pe?1:0,backgroundColor:be?C.highlightBg:void 0,paddingX:1,width:"100%"},ht.createElement(lo,{color:be?C.text:C.textMuted,bold:be},be?"\u276F ":" ",ue.label))})),ht.createElement(io,{paddingX:1,marginTop:1},ht.createElement(lo,{color:C.textMuted,italic:!0},k==="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)"))):ht.createElement(io,{flexDirection:"column",borderStyle:"round",borderColor:C.borderMuted,padding:0,marginTop:0,flexShrink:0,width:"100%"},t&&ht.createElement(io,{paddingX:1,paddingY:0,marginBottom:m?0:1,flexDirection:"row",justifyContent:"space-between"},ht.createElement(lo,{color:C.text,bold:!0},typeof t=="string"?t.toUpperCase():t),d.length>r&&ht.createElement(lo,{color:C.textMuted,italic:!0},d.length," options")),m&&ht.createElement(io,{paddingX:1,marginBottom:1},ht.createElement(lo,{color:C.textMuted,italic:!0}," ",m)),ht.createElement(io,{flexDirection:"column",width:"100%"},ht.createElement(Xd,{items:d,onSelect:S,limit:r,itemComponent:ue=>ht.createElement(Gd,{...ue,theme:y}),indicatorComponent:()=>null})),ht.createElement(io,{paddingX:1,marginTop:1},ht.createElement(lo,{color:C.textMuted,italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}import I,{useState as qt,useEffect as Pr}from"react";import{Box as Ue,Text as ne,useInput as Vd}from"ink";import jd from"ink-text-input";import Yd from"v8";import Na from"os";var Wo=[...Object.keys(oa),"Mystery"],Xo=[{id:"appearance",label:"Appearance",desc:"Customize UI theme & rendering options"},{id:"memory",label:"Personalization",desc:"Manage system context & agent's memory"},{id:"secondaryModels",label:"Secondary Models",desc:"Sub-agents & auto-completion models"},{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"}],Fa=t=>{let m=t.autoApproveCommands||"",d=t.autoDisallowCommands||"",S=t.alwaysAskCommands||"",y=t.autoExec===!1&&t.allowExternalAccess===!1&&t.networkAccess===!1&&m===""&&d==="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&&t.overwriteProtection!==!1,p=t.autoExec===!0&&t.allowExternalAccess===!1&&t.networkAccess!==!1&&m==="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"&&d==="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&&t.overwriteProtection!==!1,r=t.autoExec===!0&&t.allowExternalAccess===!0&&t.networkAccess!==!1&&m==="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"&&d===""&&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&&t.overwriteProtection===!1;return y?"Strict":p?"Balanced":r?"Autonomous":t.sandboxPreset||"Custom"},Or=t=>!t||t.trim()===""?"None":t.length>40?t.substring(0,40)+"...":t;function bs({systemSettings:t,setSystemSettings:m,apiTier:d,setActiveView:S,setInputConfig:y,saveSettings:p,quotas:r,setMessages:C,aiProvider:w,autoCompletion:M,setAutoCompletion:P,profileData:F,setProfileData:k,initialSelectingTheme:O=!1,onCloseTheme:K=null,setProviderReturnView:j=null,setApiKey:H=null,initAI:W=null}){let X=t.theme==="Chaos"||t.theme==="Mystery"?"Mystery":t.theme||"Dark",ie=Wo.indexOf(X),[ue,te]=qt("categories"),[_,be]=qt(0),[Pe,Ae]=qt(0),[tt,Se]=qt("Sandbox"),[xe,Me]=qt(null),[Bt,We]=qt(""),[Oe,ye]=qt(O),[R,fe]=qt(ie>=0?ie:0),[we,oe]=qt(t.theme||"Dark"),[ge,Y]=qt(!1),[Xe,Fe]=qt("subAgent"),[yt,it]=qt(0),[Tt,rt]=qt(0),[Qe,ae]=qt(""),[Ee,mt]=qt("list"),[ft,He]=qt({});Pr(()=>{(async()=>{let T=["Google","DeepSeek","OpenRouter","NVIDIA","Mistral","Ollama","InferX","SenseNova","AIHubMix","Poolside","9router","ExpLabs","TokenHarbor","Infron","APInex","xKiro","c_openai"],A={};for(let Te of T)try{await mn(Te,{silent:!0})&&(A[Te]=!0)}catch{}He(A)})()},[]);let Dt=I.useMemo(()=>{let ce=["Google","DeepSeek","OpenRouter","NVIDIA","Mistral","Ollama","InferX","SenseNova","AIHubMix","Poolside","9router","ExpLabs","TokenHarbor","Infron","APInex","xKiro","c_openai"],A=!!(process.env.SUBAGENT_MODEL&&process.env.SUBAGENT_MODEL.trim())?`ENV (${process.env.SUBAGENT_MODEL.trim()})`:"ENV",Te=[{label:"Default (use the current model)",value:"Default",isHeader:!1},{label:A,value:"ENV",isHeader:!1}],Le=r?.providerTiers?.[w]||d||"Free",nt=un(w,Le,t?.customOpenAIBaseUrl)||[];nt.length>0&&(Te.push({label:`\u2500\u2500 ${w.toUpperCase()}${Le!=="Free"?` (${Le})`:""} \u2500\u2500`,isHeader:!0}),nt.forEach(ct=>{let ze=typeof ct=="string"?ct:ct.cmd||ct.name||ct.id||String(ct);ze&&!ze.trim().startsWith("---")&&!ze.startsWith(`
43
43
  ---`)&&Te.push({label:ze,value:ze,isHeader:!1,provider:w})}));for(let ct of ce)if(ct!==w&&ft[ct]){let ze=r?.providerTiers?.[ct]||"Free",mo=un(ct,ze)||[];mo.length>0&&(Te.push({label:`\u2500\u2500 ${ct.toUpperCase()}${ze!=="Free"?` (${ze})`:""} \u2500\u2500`,isHeader:!0}),mo.forEach(Je=>{let Ut=typeof Je=="string"?Je:Je.cmd||Je.name||Je.id||String(Je);Ut&&!Ut.trim().startsWith("---")&&!Ut.startsWith(`
44
- ---`)&&Te.push({label:Ut,value:Ut,isHeader:!1,provider:ct})}))}return Te},[w,d,r,ft]),Ve=I.useMemo(()=>{if(!Qe.trim())return Dt;let ce=Qe.trim().toLowerCase(),T=[],A=null;for(let Te of Dt)Te.isHeader?A=Te:(Te.label.toLowerCase().includes(ce)||Te.value&&Te.value.toLowerCase().includes(ce))&&(A&&!T.includes(A)&&T.push(A),T.push(Te));return T},[Dt,Qe]);Pr(()=>{if(ge){let ce=Ve.findIndex(T=>!T.isHeader);it(ce>=0?ce:0),rt(0)}},[Qe]),Pr(()=>{if(ge){if(Ve.length===0){it(0),rt(0);return}if(yt>=Ve.length||Ve[yt]?.isHeader){let ce=Ve.findIndex(T=>!T.isHeader);it(ce>=0?ce:0)}}},[Ve,ge]);let[wo,U]=qt(0),[rn,lr]=qt(0),[Ur,Tn]=qt("MB"),[_r,yn]=qt(!1);Pr(()=>{let ce=!1;return import("./exec_command-SQB5LU5X.js").then(T=>{ce||yn(!!T.isPtyAvailable)}).catch(()=>{}),()=>{ce=!0}},[]),Pr(()=>{let ce=Yd.getHeapStatistics().heap_size_limit,T=ce>=1024*1024*1024,A=T?"GB":"MB",Te=T?1024*1024*1024:1024*1024;lr(parseFloat((ce/Te).toFixed(2))),Tn(A);let Le=()=>{let mo=process.memoryUsage().rss/Te,Je=T?parseFloat(mo.toFixed(2)):Math.round(mo);U(Je)};Le();let nt=setInterval(()=>{Le()},3e4);return()=>clearInterval(nt)},[]);let ks=ce=>{switch(ce){case"providers":{let T=[{label:"Current Provider",value:"aiProvider",status:w==="c_openai"?"Custom (OpenAI)":w}];return w==="Ollama"&&T.push({label:"Endpoint",value:"ollamaEndpoint",status:t.ollamaEndpoint||"Cloud"}),(w==="c_openai"||w==="Custom (OpenAI)")&&(T.push({label:"Base URL",value:"customOpenAIBaseUrl",status:t.customOpenAIBaseUrl||"Not Configured"}),T.push({label:"API Key (if needed)",value:"customOpenAIKey",status:ft.c_openai?"Set":"None"})),T}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"},{label:"Verbose Thinking",value:"preserveThinking",status:t.preserveThinking!==!1?"ON":"OFF"}];case"memory":return[{label:"Base Personality",value:"profilePreset",status:F?.preset||"Default"},{label:"Nickname",value:"profileNickname",status:F?.nickname||"None"},{label:"Custom Instructions",value:"profileInstructions",status:Or(F?.instructions)}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:Fa(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:Or(t.alwaysAskCommands),section:"Sandbox"},{label:"Always Ask Files/Paths",value:"alwaysAskFiles",status:Or(t.alwaysAskFiles||".env, .env.*, *.env"),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Or(t.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Or(t.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:t.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Overwrite Protection",value:"overwriteProtection",status:t.overwriteProtection!==!1?"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"},{label:"Agent Clipboard Context",value:"clipboardContext",status:t.clipboardContext?"ON":"OFF",section:"Other"},{label:"Loop Limits",value:"loopLimits",status:t.loopLimits||"Default",section:"Other"}].filter(Te=>Te.section.toLowerCase()===tt.toLowerCase());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"secondaryModels":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:"Enable Auto-Completion",value:"autoCompletionEnabled",status:M?.enabled?"ON":"OFF"},{label:"Auto-Completion Model",value:"autoCompletionModel",status:M?.model&&M.model!=="Default"?M.model:"Default"},{label:"Commit Message Model",value:"commitMessageModel",status:t.commitMessageModel&&t.commitMessageModel!=="Default"?t.commitMessageModel:"Default"}];case"other":return[{label:"Directory Tree Design",value:"indentationTree",status:t.indentationTree!==!1?"Modern":"Legacy"},{label:"Compact Large Tool Results",value:"compressToolResults",status:t.compressToolResults?"ON":"OFF"},{label:"Auto Truncate Results",value:"autoTruncateResults",status:t.autoTruncateResults?"ON":"OFF"},{label:"Agent Finish Notification",value:"agentFinishSound",status:t.agentFinishSound?"ON":"OFF"},{label:"Image History for CU",value:"imageHistoryCU",status:t.imageHistoryCU||"Standard"},{label:"Context Length",value:"contextLength",status:t.contextLength||"256k"},{label:"Keep Reasoning Context",value:"keepReasoningContext",status:t.keepReasoningContext?"ON":"OFF"},{label:"Auto Exclude Metadata",value:"autoExcludeMetadata",status:t.autoExcludeMetadata?"ON":"OFF"},{label:"Disable Todo",value:"disableTodo",status:t.disableTodo?"ON":"OFF"},...process.platform==="win32"?[{label:"Prefer Bash",value:"preferBash",status:t.preferBash!==!1?"ON":"OFF"}]:[],{label:"Cache Calculate Mode",value:"cacheCalculateMode",status:t.cacheCalculateMode||"Session"}];default:return[]}},Ye=Xo[_].id,Qt=ks(Ye);Vd((ce,T)=>{if(ge){if(T.tab){mt(A=>A==="search"?"list":"search");return}if(Ee==="search"){T.escape?Y(!1):T.downArrow||T.return?mt("list"):T.backspace||T.delete?ae(A=>A.slice(0,-1)):ce&&!T.ctrl&&!T.meta&&ce.length===1&&ae(A=>A+ce);return}if(T.upArrow)it(A=>{if(Ve.length===0)return 0;let Te=(A-1+Ve.length)%Ve.length,Le=0;for(;Ve[Te]?.isHeader&&Le<Ve.length;)Te=(Te-1+Ve.length)%Ve.length,Le++;return Te});else if(T.downArrow)it(A=>{if(Ve.length===0)return 0;let Te=(A+1)%Ve.length,Le=0;for(;Ve[Te]?.isHeader&&Le<Ve.length;)Te=(Te+1)%Ve.length,Le++;return Te});else if(T.return){let A=Ve[yt];if(A&&!A.isHeader){let Te=A.value==="Default";Xe==="autoCompletion"?P(Le=>{let nt=Te?"":A.provider||"",ct={...Le,model:A.value,provider:nt,baseUrl:Te?"":Yl[nt]||""};return p({autoCompletion:ct,apiTier:d,quotas:r}),ct}):m(Xe==="commitMessage"?Le=>{let nt={...Le,commitMessageModel:Te?"Default":A.value,commitMessageProvider:Te?"":A.provider||""};return p({systemSettings:nt,apiTier:d,quotas:r}),nt}:Le=>{let nt={...Le,CustomSubAgent:!Te,SubAgentModel:A.value,SubAgentProvider:Te?"":A.provider||""};return p({systemSettings:nt,apiTier:d,quotas:r}),nt}),Y(!1)}}else T.escape?Y(!1):ce&&!T.ctrl&&!T.meta&&ce.length===1&&(ae(A=>A+ce),mt("search"));return}if(Oe){if(T.upArrow){let A=(R-1+Wo.length)%Wo.length;fe(A)}else if(T.downArrow){let A=(R+1)%Wo.length;fe(A)}else if(T.return){let A=Wo[R];m(Te=>{let Le={...Te,theme:A};return p({systemSettings:Le,apiTier:d,quotas:r}),Le}),K?K():ye(!1)}else T.escape&&(K?K():ye(!1));return}if(xe){T.escape&&Me(null);return}if(ue==="categories")T.upArrow?be(A=>(A-1+Xo.length)%Xo.length):T.downArrow?be(A=>(A+1)%Xo.length):T.return||T.rightArrow?Xo[_].id==="exit"?S("chat"):(te("items"),Ae(0)):T.escape&&S("chat");else if(ue==="items"){if(Ye==="security"&&(T.tab||ce===" ")){Se(A=>A==="Sandbox"?"Other":"Sandbox"),Ae(0);return}if(T.upArrow)Ae(A=>(A-1+Qt.length)%Qt.length);else if(T.downArrow)Ae(A=>(A+1)%Qt.length);else if(T.leftArrow)Ye==="security"&&tt==="Other"?(Se("Sandbox"),Ae(0)):te("categories");else if(T.rightArrow&&Ye==="security"&&tt==="Sandbox")Se("Other"),Ae(0);else if(T.escape)te("categories");else if(T.return){let A=Qt[Pe];Hr(A)}}});let Hr=ce=>{if(ce.value==="profilePreset"){let T=["Default","Sassy","Friendly","Playful","Efficient","Professional"],A=F?.preset||"Default",Le=(T.indexOf(A)+1)%T.length,nt=T[Le>=0?Le:0],ct={...F||{},preset:nt};k&&k(ct),p({profileData:ct,systemSettings:t,apiTier:d,quotas:r})}else if(ce.value==="profileNickname")Me("profileNickname"),We(F?.nickname||"");else if(ce.value==="profileInstructions")Me("profileInstructions"),We(F?.instructions||"");else if(ce.value==="memory")m(T=>({...T,memory:!T.memory}));else if(ce.value==="sandboxPreset"){let T=Fa(t),A=["Autonomous","Balanced","Strict"],Le=(A.indexOf(T)+1)%A.length,nt=A[Le];m(ct=>{let ze={...ct,sandboxPreset:nt};return nt==="Strict"?(ze.autoExec=!1,ze.allowExternalAccess=!1,ze.networkAccess=!1,ze.autoApproveCommands="",ze.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",ze.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",ze.autoApproveGit=!1,ze.overwriteProtection=!0):nt==="Balanced"?(ze.autoExec=!0,ze.allowExternalAccess=!1,ze.networkAccess=!0,ze.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",ze.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",ze.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",ze.autoApproveGit=!1,ze.overwriteProtection=!0):nt==="Autonomous"&&(ze.autoExec=!0,ze.allowExternalAccess=!0,ze.networkAccess=!0,ze.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",ze.autoDisallowCommands="",ze.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",ze.autoApproveGit=!0,ze.overwriteProtection=!1),ze})}else if(ce.value==="autoExec")t.autoExec?m(T=>({...T,autoExec:!1,sandboxPreset:"Custom"})):t.allowExternalAccess?S("doubleDanger"):S("autoExecDanger");else if(ce.value==="externalAccess")t.allowExternalAccess?m(T=>({...T,allowExternalAccess:!1,sandboxPreset:"Custom"})):t.autoExec?S("doubleDanger"):S("externalDanger");else if(ce.value==="networkAccess")m(T=>({...T,networkAccess:T.networkAccess===!1,sandboxPreset:"Custom"}));else if(ce.value==="alwaysAsk")Me("alwaysAskCommands"),We(t.alwaysAskCommands||"");else if(ce.value==="alwaysAskFiles")Me("alwaysAskFiles"),We(t.alwaysAskFiles||".env, .env.*, *.env");else if(ce.value==="autoApprove")Me("autoApproveCommands"),We(t.autoApproveCommands||"");else if(ce.value==="autoDisallow")Me("autoDisallowCommands"),We(t.autoDisallowCommands||"");else if(ce.value==="autoApproveGit")m(T=>({...T,autoApproveGit:!T.autoApproveGit,sandboxPreset:"Custom"}));else if(ce.value==="overwriteProtection")m(T=>({...T,overwriteProtection:T.overwriteProtection===!1,sandboxPreset:"Custom"}));else if(ce.value==="customOpenAIBaseUrl")Me("customOpenAIBaseUrl"),We(t.customOpenAIBaseUrl||"");else if(ce.value==="customOpenAIKey")Me("customOpenAIKey"),We("");else if(ce.value==="ollamaEndpoint")m(T=>{let A=T.ollamaEndpoint==="Local"?"Cloud":"Local",Te={...T,ollamaEndpoint:A};return p({systemSettings:Te,apiTier:d,quotas:r}),Te});else if(ce.value==="apiTier")S("apiTier");else if(ce.value==="aiProvider")j&&j("settings"),S("selectProvider");else if(ce.value==="advanceRollback")t.advanceRollback?m(T=>{let A={...T,advanceRollback:!1};return p({systemSettings:A,apiTier:d,quotas:r}),A}):S("advanceRollbackDanger");else if(ce.value==="autoDelete"){let T=["1d","7d","30d"],Te=(T.indexOf(t.autoDeleteHistory||"30d")+1)%T.length;m(Le=>({...Le,autoDeleteHistory:T[Te]}))}else if(ce.value==="autoUpdate")m(T=>({...T,autoUpdate:!T.autoUpdate}));else if(ce.value==="externalData")if(!t.useExternalData)y({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 T={...t,useExternalData:!1};m(T),p({systemSettings:T,apiTier:d,quotas:r}),C(A=>[...A,{id:Date.now(),role:"system",text:"[STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),S("chat")}else if(ce.value==="updateManager")S("updateManager");else if(ce.value==="parserDownload")S("parserDownload");else if(ce.value==="indentationTree")m(T=>{let A={...T,indentationTree:T.indentationTree===!1};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="compressToolResults")m(T=>{let A={...T,compressToolResults:!T.compressToolResults};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="autoTruncateResults")m(T=>{let A={...T,autoTruncateResults:!T.autoTruncateResults};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="agentFinishSound")m(T=>{let A={...T,agentFinishSound:!T.agentFinishSound};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="loopLimits"){let T=["Default","Extended","ENV"],Te=(T.indexOf(t.loopLimits||"Default")+1)%T.length;m(Le=>{let nt={...Le,loopLimits:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="imageHistoryCU"){let T=["Low","Standard","Extended","Max"],Te=(T.indexOf(t.imageHistoryCU||"Standard")+1)%T.length;m(Le=>{let nt={...Le,imageHistoryCU:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="contextLength"){let T=["16k","32k","64k","128k","256k","512k","1M"],Te=(T.indexOf(t.contextLength||"256k")+1)%T.length;m(Le=>{let nt={...Le,contextLength:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="keepReasoningContext")m(T=>{let A={...T,keepReasoningContext:!T.keepReasoningContext};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="autoExcludeMetadata")m(T=>{let A={...T,autoExcludeMetadata:!T.autoExcludeMetadata};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="disableTodo")m(T=>{let A={...T,disableTodo:!T.disableTodo};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="preferBash")m(T=>{let A=T.preferBash!==!1,Te={...T,preferBash:!A};return p({systemSettings:Te,apiTier:d,quotas:r}),Te});else if(ce.value==="cacheCalculateMode"){let T=["Session","Current"],Te=(T.indexOf(t.cacheCalculateMode||"Session")+1)%T.length;m(Le=>{let nt={...Le,cacheCalculateMode:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="subAgents")m(T=>{let A={...T,subAgents:T.subAgents===!1};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="subAgentModel"){let T=t.CustomSubAgent&&t.SubAgentModel?t.SubAgentModel:"Default",A=Ve.findIndex(Te=>Te.value===T);it(A>=0?A:0),Fe("subAgent"),Y(!0)}else if(ce.value==="autoCompletionEnabled")P(T=>{let A={...T,enabled:!T.enabled};return p({autoCompletion:A,apiTier:d,quotas:r}),A});else if(ce.value==="clipboardContext")m(T=>{let A={...T,clipboardContext:!T.clipboardContext};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="autoCompletionModel"){let T=M?.model||"Default",A=Ve.findIndex(Te=>Te.value===T);it(A>=0?A:0),Fe("autoCompletion"),Y(!0)}else if(ce.value==="commitMessageModel"){let T=t.commitMessageModel||"Default",A=Ve.findIndex(Te=>Te.value===T);it(A>=0?A:0),Fe("commitMessage"),Y(!0)}else if(ce.value==="preserveThinking")m(T=>{let A={...T,preserveThinking:T.preserveThinking===!1};return Ea(A.preserveThinking),p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="loadingPhrases")m(T=>{let A={...T,loadingPhrases:T.loadingPhrases===!1};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="progressiveRendering")m(T=>{let A={...T,progressiveRendering:!T.progressiveRendering};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="showTPMEstimate")m(T=>{let A={...T,showTPMEstimate:!T.showTPMEstimate};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="theme"){let T=t.theme==="Chaos"||t.theme==="Mystery"?"Mystery":t.theme||"Dark",A=Wo.indexOf(T);fe(A>=0?A:0),oe(t.theme||"Dark"),ye(!0)}},Be=gt(t.theme);if(ge){let ce=Xe==="autoCompletion"?M?.model||"Default":Xe==="commitMessage"?t.commitMessageModel||"Default":t.CustomSubAgent&&t.SubAgentModel?t.SubAgentModel:"Default",T=15,A=Tt;yt<A?A=yt:yt>=A+T&&(A=yt-T+1),A=Math.max(0,Math.min(A,Math.max(0,Ve.length-T))),A!==Tt&&rt(A);let Te=Ve.slice(A,A+T);return I.createElement(Ue,{flexDirection:"column",borderStyle:"round",borderColor:Be.border,padding:1,width:"100%",minHeight:32},I.createElement(Ue,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:Be.text,bold:!0,underline:!0},Xe==="autoCompletion"?"Select Auto-Completion Model:":Xe==="commitMessage"?"Select Commit Message Model:":"Select Sub-Agent Model:"),Ve.length>0&&I.createElement(ne,{color:"gray"},yt+1,"/",Ve.length)),I.createElement(Ue,{borderStyle:"single",borderColor:Ee==="search"?Be.primary||"cyan":"gray",paddingX:1,marginBottom:1},I.createElement(ne,{color:Ee==="search"?Be.primary||"cyan":"gray",bold:!0},"\u{1F50D} Search: "," "),I.createElement(ne,{color:Be.text},Qe),Ee==="search"&&I.createElement(ne,{color:Be.primary||"cyan"},"\u2588"),!Qe&&Ee!=="search"&&I.createElement(ne,{color:"gray",italic:!0},"(Press TAB or type to filter models...)")),I.createElement(Ue,{flexDirection:"column",flexGrow:1,height:T},Te.length>0?Te.map((Le,nt)=>{let ct=A+nt;if(Le.isHeader)return I.createElement(Ue,{key:`hdr-${ct}`,paddingX:1},I.createElement(ne,{color:"gray",bold:!0,underline:!0},Le.label));let ze=yt===ct&&Ee==="list",mo=ce===Le.value;return I.createElement(Ue,{key:`item-${Le.value}-${ct}`,paddingX:1,backgroundColor:ze?Be.highlightBg:void 0},I.createElement(ne,{color:ze?Be.text:Be.textDim,bold:ze},ze?"\u276F ":" ",Le.label,mo?I.createElement(ne,{color:Be.primary||"cyan",italic:!0}," (active)"):""))}):I.createElement(Ue,{paddingX:1},I.createElement(ne,{color:"gray",italic:!0},'No models matching "',Qe,'"'))),I.createElement(Ue,{paddingX:1,marginTop:1,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:"gray",italic:!0},"TAB to switch search/list \u2022 \u25B2\u25BC Navigate \u2022 ENTER to Select \u2022 ESC to Cancel"),I.createElement(ne,{color:Ee==="search"?Be.primary||"cyan":"gray",bold:!0},"[",Ee.toUpperCase()," MODE]")))}if(Oe){let ce=Wo[R],T=gt(ce);return I.createElement(Ue,{flexDirection:"column",borderStyle:"round",borderColor:T.border,padding:1,width:"100%",minHeight:32},I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:T.text,bold:!0},"Choose your color scheme:")),I.createElement(Ue,{flexDirection:"row",width:"100%",flexGrow:1},I.createElement(Ue,{flexDirection:"column",width:"30%",paddingRight:1},Wo.map((A,Te)=>{let Le=R===Te,nt=(t.theme||"Dark")===A,ct=A==="Forest Sprite"||A==="Spookfest";return I.createElement(Ue,{key:A,paddingX:0},I.createElement(ne,{color:Le?T.text:T.textDim,bold:Le},Le?"> ":" ",A,ct&&I.createElement(ne,{color:Le?T.success||"#52b788":"green",bold:!0}," \u2605"),nt?I.createElement(ne,{color:T.primary||"cyan",italic:!0}," (saved)"):""))})),I.createElement(Ue,{flexDirection:"column",flexGrow:1,borderStyle:"round",borderColor:T.borderMuted,paddingX:2,paddingY:1,backgroundColor:T.cardBg},I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:T.secondary||"cyan",bold:!0},"> ","you: "),I.createElement(ne,{color:T.text},"add a greeting function")),I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:T.success||"green"}," Here's the change:")),I.createElement(Ue,{flexDirection:"column",marginLeft:2,marginBottom:1},I.createElement(ne,null,I.createElement(ne,{color:T.textDim},"3 "),kt(' import "fmt"',".go",void 0)),I.createElement(ne,{color:T.textDim},"4"),I.createElement(Ue,{backgroundColor:T.diffRemovalBg},I.createElement(ne,null,I.createElement(ne,{color:T.diffRemovalNum||T.diffRemovalText},"5 "),I.createElement(ne,{color:T.diffRemovalPrefix||T.diffRemovalText},"- "),kt("func ",".go",void 0),kt("main()",".go",void 0,T.diffRemovalHighlightBg),kt(" {",".go",void 0))),I.createElement(Ue,{backgroundColor:T.diffAdditionBg},I.createElement(ne,null,I.createElement(ne,{color:T.diffAdditionNum||T.diffAdditionText},"5 "),I.createElement(ne,{color:T.diffAdditionPrefix||T.diffAdditionText},"+ "),kt("func ",".go",void 0),kt("greet(name string)",".go",void 0,T.diffAdditionHighlightBg),kt(" {",".go",void 0))),I.createElement(Ue,{backgroundColor:T.diffAdditionBg},I.createElement(ne,null,I.createElement(ne,{color:T.diffAdditionNum||T.diffAdditionText},"6 "),I.createElement(ne,{color:T.diffAdditionPrefix||T.diffAdditionText},"+ "),I.createElement(ne,null," "),kt('fmt.Printf("Hello, %s!\\n", name)',".go",void 0,T.diffAdditionHighlightBg))),I.createElement(ne,null,"7 }")),I.createElement(Ue,{flexDirection:"column",marginTop:1,marginBottom:1},I.createElement(ne,{color:T.textDim},"\u25BE Thought Process"),I.createElement(ne,{color:T.textMuted}," I need to add a greeting function. I'll use fmt.Printf.")),I.createElement(Ue,{flexDirection:"column"},I.createElement(ne,null,I.createElement(ne,{color:T.warning||"yellow"},"\u2699 tool: "),I.createElement(ne,{color:T.text},"write_file main.go")),I.createElement(ne,null,I.createElement(ne,{color:T.accent||"magenta"},"\u29BF task: "),I.createElement(ne,{color:T.text},"Implementing greeting")),I.createElement(ne,null,I.createElement(ne,{color:T.danger||"red"},"X error: "),I.createElement(ne,{color:T.text},"compilation failed")),I.createElement(ne,null,I.createElement(ne,{color:T.warning||"yellow"},"\u26A0 warning: "),I.createElement(ne,{color:T.text},"deprecation warning")),I.createElement(ne,null,I.createElement(ne,{color:T.info||"blue"},"\u2192 link: "),I.createElement(ne,{color:T.info||"blue",underline:!0},"file:///path/to/main.go")),I.createElement(ne,null,I.createElement(ne,{color:T.accent||"magenta"},"\u2605 accent: "),I.createElement(ne,{color:T.text},"highlighted text")),I.createElement(ne,{color:T.textDim},"\xB7 dim: press Enter to continue")))),I.createElement(Ue,{paddingX:1,marginTop:1,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:"gray",italic:!0},"\u25B2\u25BC Navigate \u2022 ENTER to Select \u2022 ESC to Cancel"),I.createElement(ne,{color:"gray"},"Previewing: ",Wo[R],Wo[R]==="Forest Sprite"?" \u2605":"")))}return I.createElement(Ue,{flexDirection:"column",borderStyle:"round",borderColor:Be.border,padding:0,width:"100%",minHeight:26},I.createElement(Ue,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:Be.borderMuted,width:"100%"},I.createElement(ne,{color:Be.text,bold:!0},"SYSTEM CONFIGURATION")),I.createElement(Ue,{flexDirection:"row",width:"100%",minHeight:20},I.createElement(Ue,{flexDirection:"column",width:"30%",maxWidth:40,borderStyle:"round",borderColor:ue==="categories"?Be.border:Be.borderMuted,padding:1,paddingY:0},I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:ue==="categories"?Be.text:Be.textDim,bold:!0,underline:!0},"CATEGORIES")),Xo.map((ce,T)=>{let A=_===T,Te=ce.id==="exit";return I.createElement(Ue,{key:ce.id,marginTop:Te?9:0,backgroundColor:A?ue==="categories"?Be.highlightBg:Be.cardBg:void 0,paddingX:1},I.createElement(ne,{color:A&&ue==="categories"?Be.text:Be.textDim,bold:A},A?"\u276F ":" ",ce.label))})),I.createElement(Ue,{flexDirection:"column",flexGrow:1,borderStyle:"round",borderColor:ue==="items"?Be.border:Be.borderMuted,paddingX:1,marginLeft:1,paddingY:0},I.createElement(Ue,{marginBottom:1,flexDirection:"row",justifyContent:"space-between",alignItems:"center"},I.createElement(ne,{color:ue==="items"?Be.text:Be.textDim,bold:!0,underline:!0},Xo[_].label.toUpperCase().includes("EXIT")?"Runtime Information":`${Xo[_].label} Settings`),Ye==="security"&&I.createElement(Ue,{flexDirection:"row"},I.createElement(Ue,{paddingX:1,backgroundColor:tt==="Sandbox"?ue==="items"?Be.highlightBg:Be.cardBg:void 0},I.createElement(ne,{bold:tt==="Sandbox",color:tt==="Sandbox"?Be.primary||"cyan":Be.textDim},"[ Sandbox ]")),I.createElement(Ue,{paddingX:1,backgroundColor:tt==="Other"?ue==="items"?Be.highlightBg:Be.cardBg:void 0},I.createElement(ne,{bold:tt==="Other",color:tt==="Other"?Be.primary||"cyan":Be.textDim},"[ Others ]")))),Qt.length>0?(()=>{let ce=null,T=[],A=Je=>(Je||"").split(",").map(Ut=>Ut.trim().toLowerCase()).filter(Boolean),Te=A(t.autoApproveCommands),Le=A(t.autoDisallowCommands),nt=A(t.alwaysAskCommands),ct=[...Te,...Le,...nt],ze=new Set(ct),mo=Ye==="security"&&ct.length!==ze.size;return Qt.forEach((Je,Ut)=>{let Cn=ue==="items"&&Pe===Ut,Mn=Je.label.length,Ds=Math.max(2,38-Mn),Et=".".repeat(Ds),le=ot=>Ye==="security"?(ot.value==="autoExec"||ot.value==="externalAccess")&&ot.status==="ON"?Be.statusOn:Be.statusOff:ot.status?.startsWith("\u2713")?Be.statusOn:ot.status?.startsWith("\u26A0")?Be.statusOff:ot.status==="ON"?Be.statusOn:ot.status==="OFF"?Be.statusOff:Be.text;Je.section&&Je.section!==ce&&Ye!=="security"&&(ce=Je.section,T.push(I.createElement(Ue,{key:`sec-hdr-${Je.section}`,marginTop:T.length>0?1:0,marginBottom:0,paddingX:1},I.createElement(ne,{color:"gray",bold:!0,underline:!0},Je.section.toUpperCase()))));let Nn=Cn&&xe&&(xe==="alwaysAskCommands"&&Je.value==="alwaysAsk"||xe==="alwaysAskFiles"&&Je.value==="alwaysAskFiles"||xe==="autoApproveCommands"&&Je.value==="autoApprove"||xe==="autoDisallowCommands"&&Je.value==="autoDisallow"||xe==="customOpenAIBaseUrl"&&Je.value==="customOpenAIBaseUrl"||xe==="customOpenAIKey"&&Je.value==="customOpenAIKey"||xe==="profileNickname"&&Je.value==="profileNickname"||xe==="profileInstructions"&&Je.value==="profileInstructions"),Wr=Je.value==="alwaysAsk"||Je.value==="alwaysAskFiles"||Je.value==="autoApprove"||Je.value==="autoDisallow"||Je.value==="profileInstructions",Xr=Je.value==="parserDownload";T.push(I.createElement(Ue,{key:Je.value,flexDirection:"column"},I.createElement(Ue,{backgroundColor:Cn&&!Nn?Be.highlightBg:void 0,paddingX:2},I.createElement(ne,{color:Cn?Be.text:Be.textDim,bold:Cn},Cn?"\u276F ":" ",Je.label),!Wr&&!Xr&&I.createElement(I.Fragment,null,I.createElement(ne,{color:"gray"},Et),I.createElement(ne,{color:le(Je),bold:!0},Je.value==="aiProvider"?Je.status:`[ ${Je.status} ]`))),Wr&&!Nn&&Je.status!=="None"&&I.createElement(Ue,{paddingX:4,marginBottom:1},I.createElement(ne,{color:"gray"},"\u21B3 ",Je.status)),Nn&&I.createElement(Ue,{flexDirection:"column",marginLeft:4,marginBottom:1},I.createElement(Ue,{paddingX:1,borderStyle:"single",borderColor:"gray",flexDirection:"row"},I.createElement(ne,{color:"gray",bold:!0},"> "," "),I.createElement(jd,{value:Bt,onChange:ot=>{let Pt=xe==="profileNickname"?20:xe==="profileInstructions"?250:1/0;We(ot.slice(0,Pt))},onSubmit:async ot=>{if(xe==="customOpenAIBaseUrl"){let Pt=ot.trim().replace(/\/+$/,""),De={...t,customOpenAIBaseUrl:Pt};m(De),p({systemSettings:De,apiTier:d,quotas:r})}else if(xe==="customOpenAIKey"){let Pt=ot.trim(),{replaceActiveProviderKey:De}=await import("./secrets-OHIQHB63.js"),ao=await De("c_openai",Pt);Pt&&(!ao||ao.ok!==!1)&&(He($o=>({...$o,c_openai:!0})),w==="c_openai"&&(H&&H(Pt),W&&W(Pt,{aiProvider:"c_openai"})))}else if(xe==="profileNickname"){let Pt=ot.trim().slice(0,20),De={...F||{},nickname:Pt};k&&k(De),p({profileData:De,systemSettings:t,apiTier:d,quotas:r})}else if(xe==="profileInstructions"){let Pt=ot.trim().slice(0,250),De={...F||{},instructions:Pt};k&&k(De),p({profileData:De,systemSettings:t,apiTier:d,quotas:r})}else{let Pt={...t,[xe]:ot.trim(),sandboxPreset:"Custom"};m(Pt),p({systemSettings:Pt,apiTier:d,quotas:r})}Me(null)}})),I.createElement(ne,{color:"gray",italic:!0}," ",xe==="customOpenAIBaseUrl"?"Enter Base URL (.../v1) \u2022 Press Enter to save, Esc to cancel":xe==="customOpenAIKey"?"Enter API Key \u2022 Press Enter to save, Esc to cancel":xe==="profileNickname"?`Enter Nickname (${Bt.length}/20) \u2022 Press Enter to save, Esc to cancel`:xe==="profileInstructions"?`Enter Custom Instructions (${Bt.length}/250) \u2022 Press Enter to save, Esc to cancel`:"Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),mo&&T.push(I.createElement(Ue,{key:"conflict-warning",marginTop:1,paddingX:1},I.createElement(ne,{color:Be.text,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),T})():I.createElement(Ue,{paddingX:1,flexDirection:"column",width:"100%"},Ye==="exit"?I.createElement(I.Fragment,null,I.createElement(Ue,{flexDirection:"column",marginBottom:1},I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"OS"," "),I.createElement(ne,{color:"gray"},"..................... "),I.createElement(ne,{color:Be.text},process.env.OS||process.platform||"N/A")),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Computer Name"," "),I.createElement(ne,{color:"gray"},".......... "),I.createElement(ne,{color:Be.text},process.env.COMPUTERNAME||process.env.HOSTNAME||"N/A")),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Processor Count"," "),I.createElement(ne,{color:"gray"},"........ "),I.createElement(ne,{color:Be.text},process.env.NUMBER_OF_PROCESSORS||"N/A")),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Node.js Version"," "),I.createElement(ne,{color:"gray"},"........ "),I.createElement(ne,{color:Be.text},"v",process.versions.node)),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"V8 Version"," "),I.createElement(ne,{color:"gray"},"...... ...... "),I.createElement(ne,{color:Be.text},"v",process.versions.v8)),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Data Directory"," "),I.createElement(ne,{color:"gray"},"......... "),Po===Co?"":I.createElement(ne,{color:Be.text},Po.replaceAll(Na.homedir(),"~").replaceAll("\\\\","/").replaceAll("\\","/"),", "),I.createElement(ne,{color:Be.text},Co.replaceAll(Na.homedir(),"~").replaceAll("\\\\","/").replaceAll("\\","/"))),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Viewport"," "),I.createElement(ne,{color:"gray"},"............... "),I.createElement(ne,{color:Be.text},process.stdout.rows||"?"," rows \xD7 ",process.stdout.columns||"?"," cols ",process.stdout.columns<90?"(too small width)":"")),I.createElement(Ue,{flexDirection:"row",marginBottom:0},I.createElement(ne,{color:Be.textDim},"Memory Load"," "),I.createElement(ne,{color:"gray"},"............ "),I.createElement(ne,{color:Be.text},wo,"/",rn," ",Ur))),I.createElement(Ue,{key:"pty-notice",paddingX:0,marginTop:0},I.createElement(ne,{color:_r?Be.statusOn:Be.warning},_r?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))):I.createElement(ne,{color:"gray",italic:!0},Xo[_].desc)))),I.createElement(Ue,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:"gray",italic:!0},ue==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":Ye==="security"?"\u25B2\u25BC Select Option \u2022 TAB/\u25C4\u25BA Switch Tab \u2022 Enter to Edit/Toggle \u2022 ESC to go back":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),ue==="categories"&&I.createElement(ne,{color:"gray"},Xo[_].desc)))}import Kt,{useState as vi}from"react";import{Box as So,Text as gn,useInput as qd}from"ink";import Qd from"ink-text-input";var zd=({question:t,options:m,onResolve:d,theme:S="Dark"})=>{let y=gt(S),[p,r]=vi(!1),[C,w]=vi(""),[M,P]=vi(0),F=!1,k=[],O=Array.isArray(m)&&m.length>0,K=t==="Agent has been running for a long time. Do you want to continue execution?";try{K&&O?k=[...m]:k=[...O?m:[],O?{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}:{id:"CUSTOM",label:"Your Answer",description:""}]}catch{F=!0}qd((H,W)=>{if(!p&&((W.leftArrow||W.upArrow)&&P(X=>Math.max(0,X-1)),(W.rightArrow||W.downArrow)&&P(X=>Math.min(k.length-1,X+1)),W.return)){let X=k[M];X?.id==="CUSTOM"?r(!0):d(F?"Selected Nothing":X.label)}});let j=At(2);return p?Kt.createElement(So,{flexDirection:"column",borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,backgroundColor:y.codeBg,width:"100%"},Kt.createElement(So,{paddingX:1},Kt.createElement(gn,{color:y.text,bold:!0},"SUGGEST SOMETHING")),Kt.createElement(So,{marginTop:1,paddingX:1},Kt.createElement(gn,{italic:!0,color:y.textMuted},"Replying to: ",t)),Kt.createElement(So,{marginTop:1,paddingX:1,flexDirection:"row"},Kt.createElement(Qd,{value:C,onChange:w,onSubmit:()=>d(C)})),Kt.createElement(So,{marginTop:1,paddingX:1,marginBottom:1},Kt.createElement(gn,{color:y.textMuted,italic:!0},"(Press Enter to send)"))):Kt.createElement(So,{flexDirection:"column",border:!0,borderStyle:"round",borderColor:y.codeBorder,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,marginY:1,marginRight:1,width:"100%"},Kt.createElement(So,{paddingX:1,marginBottom:1},Kt.createElement(gn,{color:"yellow",bold:!0},K?"TURN SAFETY SYSTEM: EXECUTION LIMIT":"AGENT REQUEST: ACTION REQUIRED")),Kt.createElement(So,{paddingX:1,marginBottom:1},Kt.createElement(gn,{color:y.text},t)),Kt.createElement(So,{flexDirection:"column",width:"100%"},k.map((H,W)=>{let X=W===M;return Kt.createElement(So,{key:H.id,flexDirection:"column",width:"100%",backgroundColor:X?y.highlightBg:void 0,paddingX:1,marginBottom:W===k.length-1?0:1},Kt.createElement(gn,{color:X?y.text:y.textMuted,bold:X},X?"\u276F ":" ",H.label),H.description&&Kt.createElement(So,{marginLeft:4},Kt.createElement(gn,{color:y.textMuted,italic:!0},H.description)))})),Kt.createElement(So,{paddingX:1,marginTop:1,marginBottom:1},Kt.createElement(gn,{color:y.textMuted,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},$a=zd;import Cu from"gradient-string";var Jd=t=>{let m=String(t||"").trim().split(/\s+/).filter(Boolean),d={sub:null,args:[],provider:null,providerBare:!1,index:null,url:null,temp:!1,all:!1,unmask:!1,nullMode:!1},S=[];for(let y=0;y<m.length;y++){let p=m[y];if(p==="--provider"){let r=m[y+1];r&&!r.startsWith("--")?(d.provider=r,y++):d.providerBare=!0}else if(p==="--index"){let r=m[y+1];r&&/^\d+$/.test(r)&&(d.index=parseInt(r,10)-1,y++)}else if(p==="--url"){let r=m[y+1];r&&!r.startsWith("--")&&(d.url=r,y++)}else p==="--temp"?d.temp=!0:p==="--null"?d.nullMode=!0:p==="--all"?d.all=!0:p==="--unmask"||p==="--reveal"?d.unmask=!0:p==="--mask"?d.unmask=!1:S.push(p)}return d.sub=S.length?S[0].toLowerCase():null,d.args=S.slice(1),d},Ua=["\u2726 API KEY MANAGEMENT","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key list [--provider <name>] [--unmask]","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key add <key> [--index <n>] [--provider <name>] [--url <endpoint>]","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key remove [<index>|<key>|--all] [--provider <name>]","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key use <index>|<key> | /key use <key> --temp","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key use --null (no key sent; c_openai / Ollama only)","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key clean [--provider <name>]","\u2800"],_a=async(t,m={})=>{let d=Jd(t),S=m.currentProvider||"Google",y=[],p=(w={})=>({lines:y,...w}),r=S;if(d.provider){let w=Pl(d.provider);if(!w)return{lines:[`\u2726 Unknown provider: ${d.provider}`]};r=w}let C=d.sub;if(!C)return{lines:Ua};if(C==="list"){if(d.providerBare){let M=Nl();y.push("\u2726 SAVED API KEYS");for(let P of M)y.push(`- ${P.provider} (${P.hasKeys?P.count:"No Saved Keys"})`);return y.push("\u2800"),p()}let w=await jl(r,{unmask:d.unmask});return y.push(`\u2726 ${Ol(r.replace("c_openai","Custom Endpoints"))} API KEYS`),y.push(...w),y.push("\u2800"),p()}if(C==="add"||C==="new"){let w=d.args.join(" ").trim();if(!w)return p({promptNewKey:!0});let M=await Xl(r,w,{index:d.index!==null?d.index:void 0,baseUrl:d.url!==null?d.url:void 0});return M.ok?(await Fl(r)===null&&await $l(r,M.index),y.push(`\u2726 Key added to ${r.replace("c_openai","Custom Endpoints")} slot ${M.index+1}.`),d.url!==null&&ii(r)&&y.push(`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Using URL: ${d.url}`),p()):M.full?{lines:[`\u2726 ${M.error}`,"\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Use /key add <key> --index <n> to overwrite a slot."]}:{lines:[`\u2726 Failed to add key: ${M.error}`]}}if(C==="remove"){let w;if(d.all)w=void 0;else if(d.args.length){let P=d.args.join(" ");w=/^\d+$/.test(P)?parseInt(P,10)-1:P}let M=await Gl(r,w,{all:d.all});return M.ok?M.all?(y.push(`\u2726 Cleared all keys for ${r.replace("c_openai","Custom Endpoints")}.`),p({promptNewKey:!0})):(y.push(`\u2726 Removed key from ${r.replace("c_openai","Custom Endpoints")} slot ${M.removedIndex+1}.`),M.needsNewKey?(y.push(`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No keys remain for ${r}. Please enter a new key.`),p({promptNewKey:!0})):p()):{lines:[`\u2726 ${M.error}`]}}if(C==="use"){let w=d.args.join(" ").trim();if(d.nullMode){if(!_l(r))return{lines:["\u2726 --null is only supported for Custom Endpoints and Ollama."]};await Hl(r,!0),ai(r);let F=r.replace("c_openai","Custom Endpoints");return y.push(`\u2726 ${F} now using NO API key (persisted).`),y.push("\u2800\u2800\u2514\u2500 Saved key slots were kept, they are just ignored."),r==="c_openai"&&y.push("\u2800\u2800\u2514\u2500 No Authorization header will be sent. Base URL is unchanged."),p({switchedKey:Ul})}if(!w)return{lines:["\u2726 Usage: /key use <index> | <key> [--temp] | /key use --null"]};if(d.temp)return Wl(r,w),y.push(`\u2726 Temporary key set for ${r.replace("c_openai","Custom Endpoints")} (session only).`),ii(r)&&y.push("\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Will use the current Custom base URL."),p({switchedKey:w});let M=/^\d+$/.test(w)?parseInt(w,10)-1:w,P=await Kl(r,M);return P.ok?(ai(r),y.push(`\u2726 ${r.replace("c_openai","Custom Endpoints")} now using slot ${P.index+1}.`),P.switchedBaseUrl&&y.push(`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Switched Base URL to: ${P.switchedBaseUrl}`),p({switchedBaseUrl:P.switchedBaseUrl,switchedKey:P.key})):{lines:[`\u2726 ${P.error}`]}}if(C==="clean"){let w=d.provider?r:null,M=await Vl(w);return y.push(w?`\u2726 Compacted ${w.replace("c_openai","Custom Endpoints")} key slots.`:`\u2726 Compacted all key stores (${M.touched} provider(s) touched).`),p()}return{lines:[`\u2726 Unknown subcommand: ${C}`,...Ua]}};import Xa from"node-notifier";import tn from"path";import Ha from"fs";import{execSync as Zd}from"child_process";import{fileURLToPath as Rd}from"url";var ws=tn.dirname(Rd(import.meta.url)),Nr=t=>{let m=[tn.resolve(ws,"../assets",t),tn.resolve(ws,"../../assets",t),tn.resolve(ws,"../../src/assets",t),tn.resolve(process.cwd(),"src/assets",t),tn.resolve(process.cwd(),"dist/assets",t)];for(let d of m)if(Ha.existsSync(d))return d;return m[0]},Wa=tn.join(process.env.APPDATA,"Microsoft","Windows","Start Menu","Programs","FluxFlow"),rf=tn.join(Wa,"FluxFlow.lnk"),sf=tn.resolve(ws,"../../node_modules/node-notifier/vendor/snoreToast/snoretoast-x64.exe"),Bi=()=>{if(process.platform==="win32")try{let t=Nr("logo.png"),m=Nr("logo.ico"),S=`
44
+ ---`)&&Te.push({label:Ut,value:Ut,isHeader:!1,provider:ct})}))}return Te},[w,d,r,ft]),Ve=I.useMemo(()=>{if(!Qe.trim())return Dt;let ce=Qe.trim().toLowerCase(),T=[],A=null;for(let Te of Dt)Te.isHeader?A=Te:(Te.label.toLowerCase().includes(ce)||Te.value&&Te.value.toLowerCase().includes(ce))&&(A&&!T.includes(A)&&T.push(A),T.push(Te));return T},[Dt,Qe]);Pr(()=>{if(ge){let ce=Ve.findIndex(T=>!T.isHeader);it(ce>=0?ce:0),rt(0)}},[Qe]),Pr(()=>{if(ge){if(Ve.length===0){it(0),rt(0);return}if(yt>=Ve.length||Ve[yt]?.isHeader){let ce=Ve.findIndex(T=>!T.isHeader);it(ce>=0?ce:0)}}},[Ve,ge]);let[wo,U]=qt(0),[rn,lr]=qt(0),[Ur,Tn]=qt("MB"),[_r,yn]=qt(!1);Pr(()=>{let ce=!1;return import("./exec_command-QBBSYF2H.js").then(T=>{ce||yn(!!T.isPtyAvailable)}).catch(()=>{}),()=>{ce=!0}},[]),Pr(()=>{let ce=Yd.getHeapStatistics().heap_size_limit,T=ce>=1024*1024*1024,A=T?"GB":"MB",Te=T?1024*1024*1024:1024*1024;lr(parseFloat((ce/Te).toFixed(2))),Tn(A);let Le=()=>{let mo=process.memoryUsage().rss/Te,Je=T?parseFloat(mo.toFixed(2)):Math.round(mo);U(Je)};Le();let nt=setInterval(()=>{Le()},3e4);return()=>clearInterval(nt)},[]);let ks=ce=>{switch(ce){case"providers":{let T=[{label:"Current Provider",value:"aiProvider",status:w==="c_openai"?"Custom (OpenAI)":w}];return w==="Ollama"&&T.push({label:"Endpoint",value:"ollamaEndpoint",status:t.ollamaEndpoint||"Cloud"}),(w==="c_openai"||w==="Custom (OpenAI)")&&(T.push({label:"Base URL",value:"customOpenAIBaseUrl",status:t.customOpenAIBaseUrl||"Not Configured"}),T.push({label:"API Key (if needed)",value:"customOpenAIKey",status:ft.c_openai?"Set":"None"})),T}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"},{label:"Verbose Thinking",value:"preserveThinking",status:t.preserveThinking!==!1?"ON":"OFF"}];case"memory":return[{label:"Base Personality",value:"profilePreset",status:F?.preset||"Default"},{label:"Nickname",value:"profileNickname",status:F?.nickname||"None"},{label:"Custom Instructions",value:"profileInstructions",status:Or(F?.instructions)}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:Fa(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:Or(t.alwaysAskCommands),section:"Sandbox"},{label:"Always Ask Files/Paths",value:"alwaysAskFiles",status:Or(t.alwaysAskFiles||".env, .env.*, *.env"),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Or(t.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Or(t.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:t.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Overwrite Protection",value:"overwriteProtection",status:t.overwriteProtection!==!1?"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"},{label:"Agent Clipboard Context",value:"clipboardContext",status:t.clipboardContext?"ON":"OFF",section:"Other"},{label:"Loop Limits",value:"loopLimits",status:t.loopLimits||"Default",section:"Other"}].filter(Te=>Te.section.toLowerCase()===tt.toLowerCase());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"secondaryModels":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:"Enable Auto-Completion",value:"autoCompletionEnabled",status:M?.enabled?"ON":"OFF"},{label:"Auto-Completion Model",value:"autoCompletionModel",status:M?.model&&M.model!=="Default"?M.model:"Default"},{label:"Commit Message Model",value:"commitMessageModel",status:t.commitMessageModel&&t.commitMessageModel!=="Default"?t.commitMessageModel:"Default"}];case"other":return[{label:"Directory Tree Design",value:"indentationTree",status:t.indentationTree!==!1?"Modern":"Legacy"},{label:"Compact Large Tool Results",value:"compressToolResults",status:t.compressToolResults?"ON":"OFF"},{label:"Auto Truncate Results",value:"autoTruncateResults",status:t.autoTruncateResults?"ON":"OFF"},{label:"Agent Finish Notification",value:"agentFinishSound",status:t.agentFinishSound?"ON":"OFF"},{label:"Image History for CU",value:"imageHistoryCU",status:t.imageHistoryCU||"Standard"},{label:"Context Length",value:"contextLength",status:t.contextLength||"256k"},{label:"Keep Reasoning Context",value:"keepReasoningContext",status:t.keepReasoningContext?"ON":"OFF"},{label:"Auto Exclude Metadata",value:"autoExcludeMetadata",status:t.autoExcludeMetadata?"ON":"OFF"},{label:"Disable Todo",value:"disableTodo",status:t.disableTodo?"ON":"OFF"},...process.platform==="win32"?[{label:"Prefer Bash",value:"preferBash",status:t.preferBash!==!1?"ON":"OFF"}]:[],{label:"Cache Calculate Mode",value:"cacheCalculateMode",status:t.cacheCalculateMode||"Session"}];default:return[]}},Ye=Xo[_].id,Qt=ks(Ye);Vd((ce,T)=>{if(ge){if(T.tab){mt(A=>A==="search"?"list":"search");return}if(Ee==="search"){T.escape?Y(!1):T.downArrow||T.return?mt("list"):T.backspace||T.delete?ae(A=>A.slice(0,-1)):ce&&!T.ctrl&&!T.meta&&ce.length===1&&ae(A=>A+ce);return}if(T.upArrow)it(A=>{if(Ve.length===0)return 0;let Te=(A-1+Ve.length)%Ve.length,Le=0;for(;Ve[Te]?.isHeader&&Le<Ve.length;)Te=(Te-1+Ve.length)%Ve.length,Le++;return Te});else if(T.downArrow)it(A=>{if(Ve.length===0)return 0;let Te=(A+1)%Ve.length,Le=0;for(;Ve[Te]?.isHeader&&Le<Ve.length;)Te=(Te+1)%Ve.length,Le++;return Te});else if(T.return){let A=Ve[yt];if(A&&!A.isHeader){let Te=A.value==="Default";Xe==="autoCompletion"?P(Le=>{let nt=Te?"":A.provider||"",ct={...Le,model:A.value,provider:nt,baseUrl:Te?"":Yl[nt]||""};return p({autoCompletion:ct,apiTier:d,quotas:r}),ct}):m(Xe==="commitMessage"?Le=>{let nt={...Le,commitMessageModel:Te?"Default":A.value,commitMessageProvider:Te?"":A.provider||""};return p({systemSettings:nt,apiTier:d,quotas:r}),nt}:Le=>{let nt={...Le,CustomSubAgent:!Te,SubAgentModel:A.value,SubAgentProvider:Te?"":A.provider||""};return p({systemSettings:nt,apiTier:d,quotas:r}),nt}),Y(!1)}}else T.escape?Y(!1):ce&&!T.ctrl&&!T.meta&&ce.length===1&&(ae(A=>A+ce),mt("search"));return}if(Oe){if(T.upArrow){let A=(R-1+Wo.length)%Wo.length;fe(A)}else if(T.downArrow){let A=(R+1)%Wo.length;fe(A)}else if(T.return){let A=Wo[R];m(Te=>{let Le={...Te,theme:A};return p({systemSettings:Le,apiTier:d,quotas:r}),Le}),K?K():ye(!1)}else T.escape&&(K?K():ye(!1));return}if(xe){T.escape&&Me(null);return}if(ue==="categories")T.upArrow?be(A=>(A-1+Xo.length)%Xo.length):T.downArrow?be(A=>(A+1)%Xo.length):T.return||T.rightArrow?Xo[_].id==="exit"?S("chat"):(te("items"),Ae(0)):T.escape&&S("chat");else if(ue==="items"){if(Ye==="security"&&(T.tab||ce===" ")){Se(A=>A==="Sandbox"?"Other":"Sandbox"),Ae(0);return}if(T.upArrow)Ae(A=>(A-1+Qt.length)%Qt.length);else if(T.downArrow)Ae(A=>(A+1)%Qt.length);else if(T.leftArrow)Ye==="security"&&tt==="Other"?(Se("Sandbox"),Ae(0)):te("categories");else if(T.rightArrow&&Ye==="security"&&tt==="Sandbox")Se("Other"),Ae(0);else if(T.escape)te("categories");else if(T.return){let A=Qt[Pe];Hr(A)}}});let Hr=ce=>{if(ce.value==="profilePreset"){let T=["Default","Sassy","Friendly","Playful","Efficient","Professional"],A=F?.preset||"Default",Le=(T.indexOf(A)+1)%T.length,nt=T[Le>=0?Le:0],ct={...F||{},preset:nt};k&&k(ct),p({profileData:ct,systemSettings:t,apiTier:d,quotas:r})}else if(ce.value==="profileNickname")Me("profileNickname"),We(F?.nickname||"");else if(ce.value==="profileInstructions")Me("profileInstructions"),We(F?.instructions||"");else if(ce.value==="memory")m(T=>({...T,memory:!T.memory}));else if(ce.value==="sandboxPreset"){let T=Fa(t),A=["Autonomous","Balanced","Strict"],Le=(A.indexOf(T)+1)%A.length,nt=A[Le];m(ct=>{let ze={...ct,sandboxPreset:nt};return nt==="Strict"?(ze.autoExec=!1,ze.allowExternalAccess=!1,ze.networkAccess=!1,ze.autoApproveCommands="",ze.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",ze.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",ze.autoApproveGit=!1,ze.overwriteProtection=!0):nt==="Balanced"?(ze.autoExec=!0,ze.allowExternalAccess=!1,ze.networkAccess=!0,ze.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",ze.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",ze.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",ze.autoApproveGit=!1,ze.overwriteProtection=!0):nt==="Autonomous"&&(ze.autoExec=!0,ze.allowExternalAccess=!0,ze.networkAccess=!0,ze.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",ze.autoDisallowCommands="",ze.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",ze.autoApproveGit=!0,ze.overwriteProtection=!1),ze})}else if(ce.value==="autoExec")t.autoExec?m(T=>({...T,autoExec:!1,sandboxPreset:"Custom"})):t.allowExternalAccess?S("doubleDanger"):S("autoExecDanger");else if(ce.value==="externalAccess")t.allowExternalAccess?m(T=>({...T,allowExternalAccess:!1,sandboxPreset:"Custom"})):t.autoExec?S("doubleDanger"):S("externalDanger");else if(ce.value==="networkAccess")m(T=>({...T,networkAccess:T.networkAccess===!1,sandboxPreset:"Custom"}));else if(ce.value==="alwaysAsk")Me("alwaysAskCommands"),We(t.alwaysAskCommands||"");else if(ce.value==="alwaysAskFiles")Me("alwaysAskFiles"),We(t.alwaysAskFiles||".env, .env.*, *.env");else if(ce.value==="autoApprove")Me("autoApproveCommands"),We(t.autoApproveCommands||"");else if(ce.value==="autoDisallow")Me("autoDisallowCommands"),We(t.autoDisallowCommands||"");else if(ce.value==="autoApproveGit")m(T=>({...T,autoApproveGit:!T.autoApproveGit,sandboxPreset:"Custom"}));else if(ce.value==="overwriteProtection")m(T=>({...T,overwriteProtection:T.overwriteProtection===!1,sandboxPreset:"Custom"}));else if(ce.value==="customOpenAIBaseUrl")Me("customOpenAIBaseUrl"),We(t.customOpenAIBaseUrl||"");else if(ce.value==="customOpenAIKey")Me("customOpenAIKey"),We("");else if(ce.value==="ollamaEndpoint")m(T=>{let A=T.ollamaEndpoint==="Local"?"Cloud":"Local",Te={...T,ollamaEndpoint:A};return p({systemSettings:Te,apiTier:d,quotas:r}),Te});else if(ce.value==="apiTier")S("apiTier");else if(ce.value==="aiProvider")j&&j("settings"),S("selectProvider");else if(ce.value==="advanceRollback")t.advanceRollback?m(T=>{let A={...T,advanceRollback:!1};return p({systemSettings:A,apiTier:d,quotas:r}),A}):S("advanceRollbackDanger");else if(ce.value==="autoDelete"){let T=["1d","7d","30d"],Te=(T.indexOf(t.autoDeleteHistory||"30d")+1)%T.length;m(Le=>({...Le,autoDeleteHistory:T[Te]}))}else if(ce.value==="autoUpdate")m(T=>({...T,autoUpdate:!T.autoUpdate}));else if(ce.value==="externalData")if(!t.useExternalData)y({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 T={...t,useExternalData:!1};m(T),p({systemSettings:T,apiTier:d,quotas:r}),C(A=>[...A,{id:Date.now(),role:"system",text:"[STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),S("chat")}else if(ce.value==="updateManager")S("updateManager");else if(ce.value==="parserDownload")S("parserDownload");else if(ce.value==="indentationTree")m(T=>{let A={...T,indentationTree:T.indentationTree===!1};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="compressToolResults")m(T=>{let A={...T,compressToolResults:!T.compressToolResults};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="autoTruncateResults")m(T=>{let A={...T,autoTruncateResults:!T.autoTruncateResults};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="agentFinishSound")m(T=>{let A={...T,agentFinishSound:!T.agentFinishSound};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="loopLimits"){let T=["Default","Extended","ENV"],Te=(T.indexOf(t.loopLimits||"Default")+1)%T.length;m(Le=>{let nt={...Le,loopLimits:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="imageHistoryCU"){let T=["Low","Standard","Extended","Max"],Te=(T.indexOf(t.imageHistoryCU||"Standard")+1)%T.length;m(Le=>{let nt={...Le,imageHistoryCU:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="contextLength"){let T=["16k","32k","64k","128k","256k","512k","1M"],Te=(T.indexOf(t.contextLength||"256k")+1)%T.length;m(Le=>{let nt={...Le,contextLength:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="keepReasoningContext")m(T=>{let A={...T,keepReasoningContext:!T.keepReasoningContext};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="autoExcludeMetadata")m(T=>{let A={...T,autoExcludeMetadata:!T.autoExcludeMetadata};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="disableTodo")m(T=>{let A={...T,disableTodo:!T.disableTodo};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="preferBash")m(T=>{let A=T.preferBash!==!1,Te={...T,preferBash:!A};return p({systemSettings:Te,apiTier:d,quotas:r}),Te});else if(ce.value==="cacheCalculateMode"){let T=["Session","Current"],Te=(T.indexOf(t.cacheCalculateMode||"Session")+1)%T.length;m(Le=>{let nt={...Le,cacheCalculateMode:T[Te]};return p({systemSettings:nt,apiTier:d,quotas:r}),nt})}else if(ce.value==="subAgents")m(T=>{let A={...T,subAgents:T.subAgents===!1};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="subAgentModel"){let T=t.CustomSubAgent&&t.SubAgentModel?t.SubAgentModel:"Default",A=Ve.findIndex(Te=>Te.value===T);it(A>=0?A:0),Fe("subAgent"),Y(!0)}else if(ce.value==="autoCompletionEnabled")P(T=>{let A={...T,enabled:!T.enabled};return p({autoCompletion:A,apiTier:d,quotas:r}),A});else if(ce.value==="clipboardContext")m(T=>{let A={...T,clipboardContext:!T.clipboardContext};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="autoCompletionModel"){let T=M?.model||"Default",A=Ve.findIndex(Te=>Te.value===T);it(A>=0?A:0),Fe("autoCompletion"),Y(!0)}else if(ce.value==="commitMessageModel"){let T=t.commitMessageModel||"Default",A=Ve.findIndex(Te=>Te.value===T);it(A>=0?A:0),Fe("commitMessage"),Y(!0)}else if(ce.value==="preserveThinking")m(T=>{let A={...T,preserveThinking:T.preserveThinking===!1};return Ea(A.preserveThinking),p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="loadingPhrases")m(T=>{let A={...T,loadingPhrases:T.loadingPhrases===!1};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="progressiveRendering")m(T=>{let A={...T,progressiveRendering:!T.progressiveRendering};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="showTPMEstimate")m(T=>{let A={...T,showTPMEstimate:!T.showTPMEstimate};return p({systemSettings:A,apiTier:d,quotas:r}),A});else if(ce.value==="theme"){let T=t.theme==="Chaos"||t.theme==="Mystery"?"Mystery":t.theme||"Dark",A=Wo.indexOf(T);fe(A>=0?A:0),oe(t.theme||"Dark"),ye(!0)}},Be=gt(t.theme);if(ge){let ce=Xe==="autoCompletion"?M?.model||"Default":Xe==="commitMessage"?t.commitMessageModel||"Default":t.CustomSubAgent&&t.SubAgentModel?t.SubAgentModel:"Default",T=15,A=Tt;yt<A?A=yt:yt>=A+T&&(A=yt-T+1),A=Math.max(0,Math.min(A,Math.max(0,Ve.length-T))),A!==Tt&&rt(A);let Te=Ve.slice(A,A+T);return I.createElement(Ue,{flexDirection:"column",borderStyle:"round",borderColor:Be.border,padding:1,width:"100%",minHeight:32},I.createElement(Ue,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:Be.text,bold:!0,underline:!0},Xe==="autoCompletion"?"Select Auto-Completion Model:":Xe==="commitMessage"?"Select Commit Message Model:":"Select Sub-Agent Model:"),Ve.length>0&&I.createElement(ne,{color:"gray"},yt+1,"/",Ve.length)),I.createElement(Ue,{borderStyle:"single",borderColor:Ee==="search"?Be.primary||"cyan":"gray",paddingX:1,marginBottom:1},I.createElement(ne,{color:Ee==="search"?Be.primary||"cyan":"gray",bold:!0},"\u{1F50D} Search: "," "),I.createElement(ne,{color:Be.text},Qe),Ee==="search"&&I.createElement(ne,{color:Be.primary||"cyan"},"\u2588"),!Qe&&Ee!=="search"&&I.createElement(ne,{color:"gray",italic:!0},"(Press TAB or type to filter models...)")),I.createElement(Ue,{flexDirection:"column",flexGrow:1,height:T},Te.length>0?Te.map((Le,nt)=>{let ct=A+nt;if(Le.isHeader)return I.createElement(Ue,{key:`hdr-${ct}`,paddingX:1},I.createElement(ne,{color:"gray",bold:!0,underline:!0},Le.label));let ze=yt===ct&&Ee==="list",mo=ce===Le.value;return I.createElement(Ue,{key:`item-${Le.value}-${ct}`,paddingX:1,backgroundColor:ze?Be.highlightBg:void 0},I.createElement(ne,{color:ze?Be.text:Be.textDim,bold:ze},ze?"\u276F ":" ",Le.label,mo?I.createElement(ne,{color:Be.primary||"cyan",italic:!0}," (active)"):""))}):I.createElement(Ue,{paddingX:1},I.createElement(ne,{color:"gray",italic:!0},'No models matching "',Qe,'"'))),I.createElement(Ue,{paddingX:1,marginTop:1,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:"gray",italic:!0},"TAB to switch search/list \u2022 \u25B2\u25BC Navigate \u2022 ENTER to Select \u2022 ESC to Cancel"),I.createElement(ne,{color:Ee==="search"?Be.primary||"cyan":"gray",bold:!0},"[",Ee.toUpperCase()," MODE]")))}if(Oe){let ce=Wo[R],T=gt(ce);return I.createElement(Ue,{flexDirection:"column",borderStyle:"round",borderColor:T.border,padding:1,width:"100%",minHeight:32},I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:T.text,bold:!0},"Choose your color scheme:")),I.createElement(Ue,{flexDirection:"row",width:"100%",flexGrow:1},I.createElement(Ue,{flexDirection:"column",width:"30%",paddingRight:1},Wo.map((A,Te)=>{let Le=R===Te,nt=(t.theme||"Dark")===A,ct=A==="Forest Sprite"||A==="Spookfest";return I.createElement(Ue,{key:A,paddingX:0},I.createElement(ne,{color:Le?T.text:T.textDim,bold:Le},Le?"> ":" ",A,ct&&I.createElement(ne,{color:Le?T.success||"#52b788":"green",bold:!0}," \u2605"),nt?I.createElement(ne,{color:T.primary||"cyan",italic:!0}," (saved)"):""))})),I.createElement(Ue,{flexDirection:"column",flexGrow:1,borderStyle:"round",borderColor:T.borderMuted,paddingX:2,paddingY:1,backgroundColor:T.cardBg},I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:T.secondary||"cyan",bold:!0},"> ","you: "),I.createElement(ne,{color:T.text},"add a greeting function")),I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:T.success||"green"}," Here's the change:")),I.createElement(Ue,{flexDirection:"column",marginLeft:2,marginBottom:1},I.createElement(ne,null,I.createElement(ne,{color:T.textDim},"3 "),kt(' import "fmt"',".go",void 0)),I.createElement(ne,{color:T.textDim},"4"),I.createElement(Ue,{backgroundColor:T.diffRemovalBg},I.createElement(ne,null,I.createElement(ne,{color:T.diffRemovalNum||T.diffRemovalText},"5 "),I.createElement(ne,{color:T.diffRemovalPrefix||T.diffRemovalText},"- "),kt("func ",".go",void 0),kt("main()",".go",void 0,T.diffRemovalHighlightBg),kt(" {",".go",void 0))),I.createElement(Ue,{backgroundColor:T.diffAdditionBg},I.createElement(ne,null,I.createElement(ne,{color:T.diffAdditionNum||T.diffAdditionText},"5 "),I.createElement(ne,{color:T.diffAdditionPrefix||T.diffAdditionText},"+ "),kt("func ",".go",void 0),kt("greet(name string)",".go",void 0,T.diffAdditionHighlightBg),kt(" {",".go",void 0))),I.createElement(Ue,{backgroundColor:T.diffAdditionBg},I.createElement(ne,null,I.createElement(ne,{color:T.diffAdditionNum||T.diffAdditionText},"6 "),I.createElement(ne,{color:T.diffAdditionPrefix||T.diffAdditionText},"+ "),I.createElement(ne,null," "),kt('fmt.Printf("Hello, %s!\\n", name)',".go",void 0,T.diffAdditionHighlightBg))),I.createElement(ne,null,"7 }")),I.createElement(Ue,{flexDirection:"column",marginTop:1,marginBottom:1},I.createElement(ne,{color:T.textDim},"\u25BE Thought Process"),I.createElement(ne,{color:T.textMuted}," I need to add a greeting function. I'll use fmt.Printf.")),I.createElement(Ue,{flexDirection:"column"},I.createElement(ne,null,I.createElement(ne,{color:T.warning||"yellow"},"\u2699 tool: "),I.createElement(ne,{color:T.text},"write_file main.go")),I.createElement(ne,null,I.createElement(ne,{color:T.accent||"magenta"},"\u29BF task: "),I.createElement(ne,{color:T.text},"Implementing greeting")),I.createElement(ne,null,I.createElement(ne,{color:T.danger||"red"},"X error: "),I.createElement(ne,{color:T.text},"compilation failed")),I.createElement(ne,null,I.createElement(ne,{color:T.warning||"yellow"},"\u26A0 warning: "),I.createElement(ne,{color:T.text},"deprecation warning")),I.createElement(ne,null,I.createElement(ne,{color:T.info||"blue"},"\u2192 link: "),I.createElement(ne,{color:T.info||"blue",underline:!0},"file:///path/to/main.go")),I.createElement(ne,null,I.createElement(ne,{color:T.accent||"magenta"},"\u2605 accent: "),I.createElement(ne,{color:T.text},"highlighted text")),I.createElement(ne,{color:T.textDim},"\xB7 dim: press Enter to continue")))),I.createElement(Ue,{paddingX:1,marginTop:1,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:"gray",italic:!0},"\u25B2\u25BC Navigate \u2022 ENTER to Select \u2022 ESC to Cancel"),I.createElement(ne,{color:"gray"},"Previewing: ",Wo[R],Wo[R]==="Forest Sprite"?" \u2605":"")))}return I.createElement(Ue,{flexDirection:"column",borderStyle:"round",borderColor:Be.border,padding:0,width:"100%",minHeight:26},I.createElement(Ue,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:Be.borderMuted,width:"100%"},I.createElement(ne,{color:Be.text,bold:!0},"SYSTEM CONFIGURATION")),I.createElement(Ue,{flexDirection:"row",width:"100%",minHeight:20},I.createElement(Ue,{flexDirection:"column",width:"30%",maxWidth:40,borderStyle:"round",borderColor:ue==="categories"?Be.border:Be.borderMuted,padding:1,paddingY:0},I.createElement(Ue,{marginBottom:1},I.createElement(ne,{color:ue==="categories"?Be.text:Be.textDim,bold:!0,underline:!0},"CATEGORIES")),Xo.map((ce,T)=>{let A=_===T,Te=ce.id==="exit";return I.createElement(Ue,{key:ce.id,marginTop:Te?9:0,backgroundColor:A?ue==="categories"?Be.highlightBg:Be.cardBg:void 0,paddingX:1},I.createElement(ne,{color:A&&ue==="categories"?Be.text:Be.textDim,bold:A},A?"\u276F ":" ",ce.label))})),I.createElement(Ue,{flexDirection:"column",flexGrow:1,borderStyle:"round",borderColor:ue==="items"?Be.border:Be.borderMuted,paddingX:1,marginLeft:1,paddingY:0},I.createElement(Ue,{marginBottom:1,flexDirection:"row",justifyContent:"space-between",alignItems:"center"},I.createElement(ne,{color:ue==="items"?Be.text:Be.textDim,bold:!0,underline:!0},Xo[_].label.toUpperCase().includes("EXIT")?"Runtime Information":`${Xo[_].label} Settings`),Ye==="security"&&I.createElement(Ue,{flexDirection:"row"},I.createElement(Ue,{paddingX:1,backgroundColor:tt==="Sandbox"?ue==="items"?Be.highlightBg:Be.cardBg:void 0},I.createElement(ne,{bold:tt==="Sandbox",color:tt==="Sandbox"?Be.primary||"cyan":Be.textDim},"[ Sandbox ]")),I.createElement(Ue,{paddingX:1,backgroundColor:tt==="Other"?ue==="items"?Be.highlightBg:Be.cardBg:void 0},I.createElement(ne,{bold:tt==="Other",color:tt==="Other"?Be.primary||"cyan":Be.textDim},"[ Others ]")))),Qt.length>0?(()=>{let ce=null,T=[],A=Je=>(Je||"").split(",").map(Ut=>Ut.trim().toLowerCase()).filter(Boolean),Te=A(t.autoApproveCommands),Le=A(t.autoDisallowCommands),nt=A(t.alwaysAskCommands),ct=[...Te,...Le,...nt],ze=new Set(ct),mo=Ye==="security"&&ct.length!==ze.size;return Qt.forEach((Je,Ut)=>{let Cn=ue==="items"&&Pe===Ut,Mn=Je.label.length,Ds=Math.max(2,38-Mn),Et=".".repeat(Ds),le=ot=>Ye==="security"?(ot.value==="autoExec"||ot.value==="externalAccess")&&ot.status==="ON"?Be.statusOn:Be.statusOff:ot.status?.startsWith("\u2713")?Be.statusOn:ot.status?.startsWith("\u26A0")?Be.statusOff:ot.status==="ON"?Be.statusOn:ot.status==="OFF"?Be.statusOff:Be.text;Je.section&&Je.section!==ce&&Ye!=="security"&&(ce=Je.section,T.push(I.createElement(Ue,{key:`sec-hdr-${Je.section}`,marginTop:T.length>0?1:0,marginBottom:0,paddingX:1},I.createElement(ne,{color:"gray",bold:!0,underline:!0},Je.section.toUpperCase()))));let Nn=Cn&&xe&&(xe==="alwaysAskCommands"&&Je.value==="alwaysAsk"||xe==="alwaysAskFiles"&&Je.value==="alwaysAskFiles"||xe==="autoApproveCommands"&&Je.value==="autoApprove"||xe==="autoDisallowCommands"&&Je.value==="autoDisallow"||xe==="customOpenAIBaseUrl"&&Je.value==="customOpenAIBaseUrl"||xe==="customOpenAIKey"&&Je.value==="customOpenAIKey"||xe==="profileNickname"&&Je.value==="profileNickname"||xe==="profileInstructions"&&Je.value==="profileInstructions"),Wr=Je.value==="alwaysAsk"||Je.value==="alwaysAskFiles"||Je.value==="autoApprove"||Je.value==="autoDisallow"||Je.value==="profileInstructions",Xr=Je.value==="parserDownload";T.push(I.createElement(Ue,{key:Je.value,flexDirection:"column"},I.createElement(Ue,{backgroundColor:Cn&&!Nn?Be.highlightBg:void 0,paddingX:2},I.createElement(ne,{color:Cn?Be.text:Be.textDim,bold:Cn},Cn?"\u276F ":" ",Je.label),!Wr&&!Xr&&I.createElement(I.Fragment,null,I.createElement(ne,{color:"gray"},Et),I.createElement(ne,{color:le(Je),bold:!0},Je.value==="aiProvider"?Je.status:`[ ${Je.status} ]`))),Wr&&!Nn&&Je.status!=="None"&&I.createElement(Ue,{paddingX:4,marginBottom:1},I.createElement(ne,{color:"gray"},"\u21B3 ",Je.status)),Nn&&I.createElement(Ue,{flexDirection:"column",marginLeft:4,marginBottom:1},I.createElement(Ue,{paddingX:1,borderStyle:"single",borderColor:"gray",flexDirection:"row"},I.createElement(ne,{color:"gray",bold:!0},"> "," "),I.createElement(jd,{value:Bt,onChange:ot=>{let Pt=xe==="profileNickname"?20:xe==="profileInstructions"?250:1/0;We(ot.slice(0,Pt))},onSubmit:async ot=>{if(xe==="customOpenAIBaseUrl"){let Pt=ot.trim().replace(/\/+$/,""),De={...t,customOpenAIBaseUrl:Pt};m(De),p({systemSettings:De,apiTier:d,quotas:r})}else if(xe==="customOpenAIKey"){let Pt=ot.trim(),{replaceActiveProviderKey:De}=await import("./secrets-OHIQHB63.js"),ao=await De("c_openai",Pt);Pt&&(!ao||ao.ok!==!1)&&(He($o=>({...$o,c_openai:!0})),w==="c_openai"&&(H&&H(Pt),W&&W(Pt,{aiProvider:"c_openai"})))}else if(xe==="profileNickname"){let Pt=ot.trim().slice(0,20),De={...F||{},nickname:Pt};k&&k(De),p({profileData:De,systemSettings:t,apiTier:d,quotas:r})}else if(xe==="profileInstructions"){let Pt=ot.trim().slice(0,250),De={...F||{},instructions:Pt};k&&k(De),p({profileData:De,systemSettings:t,apiTier:d,quotas:r})}else{let Pt={...t,[xe]:ot.trim(),sandboxPreset:"Custom"};m(Pt),p({systemSettings:Pt,apiTier:d,quotas:r})}Me(null)}})),I.createElement(ne,{color:"gray",italic:!0}," ",xe==="customOpenAIBaseUrl"?"Enter Base URL (.../v1) \u2022 Press Enter to save, Esc to cancel":xe==="customOpenAIKey"?"Enter API Key \u2022 Press Enter to save, Esc to cancel":xe==="profileNickname"?`Enter Nickname (${Bt.length}/20) \u2022 Press Enter to save, Esc to cancel`:xe==="profileInstructions"?`Enter Custom Instructions (${Bt.length}/250) \u2022 Press Enter to save, Esc to cancel`:"Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),mo&&T.push(I.createElement(Ue,{key:"conflict-warning",marginTop:1,paddingX:1},I.createElement(ne,{color:Be.text,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),T})():I.createElement(Ue,{paddingX:1,flexDirection:"column",width:"100%"},Ye==="exit"?I.createElement(I.Fragment,null,I.createElement(Ue,{flexDirection:"column",marginBottom:1},I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"OS"," "),I.createElement(ne,{color:"gray"},"..................... "),I.createElement(ne,{color:Be.text},process.env.OS||process.platform||"N/A")),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Computer Name"," "),I.createElement(ne,{color:"gray"},".......... "),I.createElement(ne,{color:Be.text},process.env.COMPUTERNAME||process.env.HOSTNAME||"N/A")),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Processor Count"," "),I.createElement(ne,{color:"gray"},"........ "),I.createElement(ne,{color:Be.text},process.env.NUMBER_OF_PROCESSORS||"N/A")),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Node.js Version"," "),I.createElement(ne,{color:"gray"},"........ "),I.createElement(ne,{color:Be.text},"v",process.versions.node)),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"V8 Version"," "),I.createElement(ne,{color:"gray"},"...... ...... "),I.createElement(ne,{color:Be.text},"v",process.versions.v8)),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Data Directory"," "),I.createElement(ne,{color:"gray"},"......... "),Po===Co?"":I.createElement(ne,{color:Be.text},Po.replaceAll(Na.homedir(),"~").replaceAll("\\\\","/").replaceAll("\\","/"),", "),I.createElement(ne,{color:Be.text},Co.replaceAll(Na.homedir(),"~").replaceAll("\\\\","/").replaceAll("\\","/"))),I.createElement(Ue,{flexDirection:"row"},I.createElement(ne,{color:Be.textDim},"Viewport"," "),I.createElement(ne,{color:"gray"},"............... "),I.createElement(ne,{color:Be.text},process.stdout.rows||"?"," rows \xD7 ",process.stdout.columns||"?"," cols ",process.stdout.columns<90?"(too small width)":"")),I.createElement(Ue,{flexDirection:"row",marginBottom:0},I.createElement(ne,{color:Be.textDim},"Memory Load"," "),I.createElement(ne,{color:"gray"},"............ "),I.createElement(ne,{color:Be.text},wo,"/",rn," ",Ur))),I.createElement(Ue,{key:"pty-notice",paddingX:0,marginTop:0},I.createElement(ne,{color:_r?Be.statusOn:Be.warning},_r?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))):I.createElement(ne,{color:"gray",italic:!0},Xo[_].desc)))),I.createElement(Ue,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},I.createElement(ne,{color:"gray",italic:!0},ue==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":Ye==="security"?"\u25B2\u25BC Select Option \u2022 TAB/\u25C4\u25BA Switch Tab \u2022 Enter to Edit/Toggle \u2022 ESC to go back":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),ue==="categories"&&I.createElement(ne,{color:"gray"},Xo[_].desc)))}import Kt,{useState as vi}from"react";import{Box as So,Text as gn,useInput as qd}from"ink";import Qd from"ink-text-input";var zd=({question:t,options:m,onResolve:d,theme:S="Dark"})=>{let y=gt(S),[p,r]=vi(!1),[C,w]=vi(""),[M,P]=vi(0),F=!1,k=[],O=Array.isArray(m)&&m.length>0,K=t==="Agent has been running for a long time. Do you want to continue execution?";try{K&&O?k=[...m]:k=[...O?m:[],O?{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}:{id:"CUSTOM",label:"Your Answer",description:""}]}catch{F=!0}qd((H,W)=>{if(!p&&((W.leftArrow||W.upArrow)&&P(X=>Math.max(0,X-1)),(W.rightArrow||W.downArrow)&&P(X=>Math.min(k.length-1,X+1)),W.return)){let X=k[M];X?.id==="CUSTOM"?r(!0):d(F?"Selected Nothing":X.label)}});let j=At(2);return p?Kt.createElement(So,{flexDirection:"column",borderStyle:"single",borderLeft:!1,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,backgroundColor:y.codeBg,width:"100%"},Kt.createElement(So,{paddingX:1},Kt.createElement(gn,{color:y.text,bold:!0},"SUGGEST SOMETHING")),Kt.createElement(So,{marginTop:1,paddingX:1},Kt.createElement(gn,{italic:!0,color:y.textMuted},"Replying to: ",t)),Kt.createElement(So,{marginTop:1,paddingX:1,flexDirection:"row"},Kt.createElement(Qd,{value:C,onChange:w,onSubmit:()=>d(C)})),Kt.createElement(So,{marginTop:1,paddingX:1,marginBottom:1},Kt.createElement(gn,{color:y.textMuted,italic:!0},"(Press Enter to send)"))):Kt.createElement(So,{flexDirection:"column",border:!0,borderStyle:"round",borderColor:y.codeBorder,paddingLeft:2,paddingRight:0,paddingTop:1,paddingBottom:1,marginY:1,marginRight:1,width:"100%"},Kt.createElement(So,{paddingX:1,marginBottom:1},Kt.createElement(gn,{color:"yellow",bold:!0},K?"TURN SAFETY SYSTEM: EXECUTION LIMIT":"AGENT REQUEST: ACTION REQUIRED")),Kt.createElement(So,{paddingX:1,marginBottom:1},Kt.createElement(gn,{color:y.text},t)),Kt.createElement(So,{flexDirection:"column",width:"100%"},k.map((H,W)=>{let X=W===M;return Kt.createElement(So,{key:H.id,flexDirection:"column",width:"100%",backgroundColor:X?y.highlightBg:void 0,paddingX:1,marginBottom:W===k.length-1?0:1},Kt.createElement(gn,{color:X?y.text:y.textMuted,bold:X},X?"\u276F ":" ",H.label),H.description&&Kt.createElement(So,{marginLeft:4},Kt.createElement(gn,{color:y.textMuted,italic:!0},H.description)))})),Kt.createElement(So,{paddingX:1,marginTop:1,marginBottom:1},Kt.createElement(gn,{color:y.textMuted,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},$a=zd;import Cu from"gradient-string";var Jd=t=>{let m=String(t||"").trim().split(/\s+/).filter(Boolean),d={sub:null,args:[],provider:null,providerBare:!1,index:null,url:null,temp:!1,all:!1,unmask:!1,nullMode:!1},S=[];for(let y=0;y<m.length;y++){let p=m[y];if(p==="--provider"){let r=m[y+1];r&&!r.startsWith("--")?(d.provider=r,y++):d.providerBare=!0}else if(p==="--index"){let r=m[y+1];r&&/^\d+$/.test(r)&&(d.index=parseInt(r,10)-1,y++)}else if(p==="--url"){let r=m[y+1];r&&!r.startsWith("--")&&(d.url=r,y++)}else p==="--temp"?d.temp=!0:p==="--null"?d.nullMode=!0:p==="--all"?d.all=!0:p==="--unmask"||p==="--reveal"?d.unmask=!0:p==="--mask"?d.unmask=!1:S.push(p)}return d.sub=S.length?S[0].toLowerCase():null,d.args=S.slice(1),d},Ua=["\u2726 API KEY MANAGEMENT","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key list [--provider <name>] [--unmask]","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key add <key> [--index <n>] [--provider <name>] [--url <endpoint>]","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key remove [<index>|<key>|--all] [--provider <name>]","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key use <index>|<key> | /key use <key> --temp","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key use --null (no key sent; c_openai / Ollama only)","\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m /key clean [--provider <name>]","\u2800"],_a=async(t,m={})=>{let d=Jd(t),S=m.currentProvider||"Google",y=[],p=(w={})=>({lines:y,...w}),r=S;if(d.provider){let w=Pl(d.provider);if(!w)return{lines:[`\u2726 Unknown provider: ${d.provider}`]};r=w}let C=d.sub;if(!C)return{lines:Ua};if(C==="list"){if(d.providerBare){let M=Nl();y.push("\u2726 SAVED API KEYS");for(let P of M)y.push(`- ${P.provider} (${P.hasKeys?P.count:"No Saved Keys"})`);return y.push("\u2800"),p()}let w=await jl(r,{unmask:d.unmask});return y.push(`\u2726 ${Ol(r.replace("c_openai","Custom Endpoints"))} API KEYS`),y.push(...w),y.push("\u2800"),p()}if(C==="add"||C==="new"){let w=d.args.join(" ").trim();if(!w)return p({promptNewKey:!0});let M=await Xl(r,w,{index:d.index!==null?d.index:void 0,baseUrl:d.url!==null?d.url:void 0});return M.ok?(await Fl(r)===null&&await $l(r,M.index),y.push(`\u2726 Key added to ${r.replace("c_openai","Custom Endpoints")} slot ${M.index+1}.`),d.url!==null&&ii(r)&&y.push(`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Using URL: ${d.url}`),p()):M.full?{lines:[`\u2726 ${M.error}`,"\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Use /key add <key> --index <n> to overwrite a slot."]}:{lines:[`\u2726 Failed to add key: ${M.error}`]}}if(C==="remove"){let w;if(d.all)w=void 0;else if(d.args.length){let P=d.args.join(" ");w=/^\d+$/.test(P)?parseInt(P,10)-1:P}let M=await Gl(r,w,{all:d.all});return M.ok?M.all?(y.push(`\u2726 Cleared all keys for ${r.replace("c_openai","Custom Endpoints")}.`),p({promptNewKey:!0})):(y.push(`\u2726 Removed key from ${r.replace("c_openai","Custom Endpoints")} slot ${M.removedIndex+1}.`),M.needsNewKey?(y.push(`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m No keys remain for ${r}. Please enter a new key.`),p({promptNewKey:!0})):p()):{lines:[`\u2726 ${M.error}`]}}if(C==="use"){let w=d.args.join(" ").trim();if(d.nullMode){if(!_l(r))return{lines:["\u2726 --null is only supported for Custom Endpoints and Ollama."]};await Hl(r,!0),ai(r);let F=r.replace("c_openai","Custom Endpoints");return y.push(`\u2726 ${F} now using NO API key (persisted).`),y.push("\u2800\u2800\u2514\u2500 Saved key slots were kept, they are just ignored."),r==="c_openai"&&y.push("\u2800\u2800\u2514\u2500 No Authorization header will be sent. Base URL is unchanged."),p({switchedKey:Ul})}if(!w)return{lines:["\u2726 Usage: /key use <index> | <key> [--temp] | /key use --null"]};if(d.temp)return Wl(r,w),y.push(`\u2726 Temporary key set for ${r.replace("c_openai","Custom Endpoints")} (session only).`),ii(r)&&y.push("\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Will use the current Custom base URL."),p({switchedKey:w});let M=/^\d+$/.test(w)?parseInt(w,10)-1:w,P=await Kl(r,M);return P.ok?(ai(r),y.push(`\u2726 ${r.replace("c_openai","Custom Endpoints")} now using slot ${P.index+1}.`),P.switchedBaseUrl&&y.push(`\u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Switched Base URL to: ${P.switchedBaseUrl}`),p({switchedBaseUrl:P.switchedBaseUrl,switchedKey:P.key})):{lines:[`\u2726 ${P.error}`]}}if(C==="clean"){let w=d.provider?r:null,M=await Vl(w);return y.push(w?`\u2726 Compacted ${w.replace("c_openai","Custom Endpoints")} key slots.`:`\u2726 Compacted all key stores (${M.touched} provider(s) touched).`),p()}return{lines:[`\u2726 Unknown subcommand: ${C}`,...Ua]}};import Xa from"node-notifier";import tn from"path";import Ha from"fs";import{execSync as Zd}from"child_process";import{fileURLToPath as Rd}from"url";var ws=tn.dirname(Rd(import.meta.url)),Nr=t=>{let m=[tn.resolve(ws,"../assets",t),tn.resolve(ws,"../../assets",t),tn.resolve(ws,"../../src/assets",t),tn.resolve(process.cwd(),"src/assets",t),tn.resolve(process.cwd(),"dist/assets",t)];for(let d of m)if(Ha.existsSync(d))return d;return m[0]},Wa=tn.join(process.env.APPDATA,"Microsoft","Windows","Start Menu","Programs","FluxFlow"),rf=tn.join(Wa,"FluxFlow.lnk"),sf=tn.resolve(ws,"../../node_modules/node-notifier/vendor/snoreToast/snoretoast-x64.exe"),Bi=()=>{if(process.platform==="win32")try{let t=Nr("logo.png"),m=Nr("logo.ico"),S=`
45
45
  $key = 'HKCU:\\Software\\Classes\\AppUserModelId\\FluxFlow'
46
46
  New-Item -Path $key -Force | Out-Null
47
47
  Set-ItemProperty -Path $key -Name 'DisplayName' -Value 'FluxFlow'
@@ -255,7 +255,7 @@ ${g}
255
255
  \u2800\u2800 \x1B[2m\u2514\u2500\x1B[22m ${g}
256
256
  \u2800`}]))};Ss?x(Ss):import("./meow-SQBRZB7H.js").then(({MEOW_LINES:c})=>{Ss=c,x(Ss)}),w("");break}case"/halloween":case"/trick-or-treat":{let x=c=>{let g=c[Math.floor(Math.random()*c.length)];L(b=>($(b.length+1),[...b,{id:Date.now(),role:"system",text:`\u{1F383} TRICK OR TREAT
257
257
  \u2800\u2800 \x1B[2m\u2514\u2500\x1B[22m ${g}
258
- \u2800`}]))};vs?x(vs):import("./halloween-EZTJXDUW.js").then(({SPOOKY_LINES:c})=>{vs=c,x(vs)}),w("");break}case"/truncate":{w("");let x=0;L(c=>{let b=[...c.map(B=>{let v=B.fullText||B.text||"";return!v.startsWith("[ACTION RESULT]: ")&&!v.startsWith("[TOOL RESULT]: ")||v.startsWith("[ACTION RESULT]: Goal")||v.startsWith("[ACTION RESULT]: USER CHOOSE")||v.startsWith("[ACTION RESULT]: Background subagent started. Task ID:")||v.includes("[ACTION RESULT]: ...Old result truncated to save tokens")?B:(x++,{...B,fullText:"[ACTION RESULT]: ...Old result truncated to save tokens"})}),{id:Date.now(),role:"system",text:`\u2726 Tool Truncation...
258
+ \u2800`}]))};vs?x(vs):import("./halloween-EZTJXDUW.js").then(({SPOOKY_LINES:c})=>{vs=c,x(vs)}),w("");break}case"/truncate":{w("");let x=0;L(c=>{let b=[...c.map(B=>{let v=B.fullText||B.text||"";return!v.startsWith("[ACTION RESULT]: ")&&!v.startsWith("[TOOL RESULT]: ")||v.startsWith("[ACTION RESULT]: Goal")||v.startsWith("[ACTION RESULT]: USER CHOOSE")||v.startsWith("[ACTION RESULT]: Background subagent started. Task ID:")||v.startsWith("[ACTION RESULT]: Subagent task")||v.includes("[ACTION RESULT]: ...Old result truncated to save tokens")?B:(x++,{...B,fullText:"[ACTION RESULT]: ...Old result truncated to save tokens"})}),{id:Date.now(),role:"system",text:`\u2726 Tool Truncation...
259
259
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Truncated ${x} tool result(s).
260
260
  \u2800`,isMeta:!0}];return Pn(Ct,null,b),$(b.length),b});break}case"/kill":{(async()=>{let c=n[1]?parseInt(n[1],10):null,{getProcessTree:g,killProcess:b}=await import("./process-6Y7LS2MS.js");if(!c||isNaN(c))L(B=>($(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u2726 Usage: \x1B[36m/kill <pid>\x1B[0m
261
261
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Select an active process PID from the autocomplete list.
@@ -277,21 +277,21 @@ ${g}
277
277
 
278
278
  ${n}`};L(c=>{let g=[...c,h];return $(g.length),Pn(Ct,null,g),g}),(async()=>{let c=!1,g=()=>{c||(c=!0,L(G=>{let ee=G[G.length-1];if(ee&&ee.text&&ee.text.includes("Request Cancelled"))return G;let V=[...G.map(q=>q.isStreaming?{...q,isStreaming:!1}:q),{id:"cancel-"+Date.now(),role:"agent",text:`
279
279
 
280
- \x1B[33m\u24D8 Request Cancelled\x1B[0m`,isMeta:!1}];return $(V.length),V}))},b=!1;Js(!0),Os(Date.now()),W(!1);let B=Date.now(),v=!0;try{let G=[...jt,h].filter(N=>N.role!=="think"&&!N.isVisualFeedback&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.includes("[TERMINAL_RECORD]"))&&!String(N.id).startsWith("welcome")),ee=[],z=G.map((N,pe)=>{let Ce=N.fullText||N.text||"";if(N.role==="user"&&pe<G.length-1)if(Ce.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let ve=Ce.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(ve!==-1){let Ge=Ce.substring(0,ve).lastIndexOf("[SYSTEM METADATA]");Ge!==-1?Ce=Ce.substring(Ge).trim():Ce=Ce.substring(ve).trim()}}else{let ve=Ce.lastIndexOf("[USER]"),et=Ce.lastIndexOf("[USER PROMPT]");ve!==-1?Ce=Ce.substring(ve+6).trim():et!==-1&&(Ce=Ce.substring(et).trim())}return{...N,text:Ce}}),V=0;for(;V<z.length;){let N=z[V];if(N.role==="user")ee.push(N),V++;else{let pe=[];for(;V<z.length&&z[V].role!=="user";)pe.push(z[V]),V++;let Ce=[],ve=[],et=null,Ge=!1,St=()=>{Ce.length>0&&(ee.push({role:"agent",text:Ce.join(`
280
+ \x1B[33m\u24D8 Request Cancelled\x1B[0m`,isMeta:!1}];return $(V.length),V}))},b=!1;Js(!0),Os(Date.now()),W(!1);let B=Date.now(),v=!0;try{let G=[...jt,h].filter(N=>N.role!=="think"&&!N.isVisualFeedback&&!N.isMeta&&!N.isTerminalRecord&&!(N.text&&N.text.includes("[TERMINAL_RECORD]"))&&!String(N.id).startsWith("welcome")),ee=[],z=G.map((N,pe)=>{let Ce=N.fullText||N.text||"";if(N.role==="user"&&pe<G.length-1)if(Ce.includes("**CONTEXT SUMMARY OF PREVIOUS TURNS")){let ve=Ce.indexOf("**CONTEXT SUMMARY OF PREVIOUS TURNS");if(ve!==-1){let Ke=Ce.substring(0,ve).lastIndexOf("[SYSTEM METADATA]");Ke!==-1?Ce=Ce.substring(Ke).trim():Ce=Ce.substring(ve).trim()}}else{let ve=Ce.lastIndexOf("[USER]"),et=Ce.lastIndexOf("[USER PROMPT]");ve!==-1?Ce=Ce.substring(ve+6).trim():et!==-1&&(Ce=Ce.substring(et).trim())}return{...N,text:Ce}}),V=0;for(;V<z.length;){let N=z[V];if(N.role==="user")ee.push(N),V++;else{let pe=[];for(;V<z.length&&z[V].role!=="user";)pe.push(z[V]),V++;let Ce=[],ve=[],et=null,Ke=!1,St=()=>{Ce.length>0&&(ee.push({role:"agent",text:Ce.join(`
281
281
  `).trim()}),Ce=[]),ve.length>0&&(ee.push({role:"system",text:ve.join(`
282
282
 
283
- `),...et?{binaryPart:et}:{}}),ve=[],et=null),Ge=!1};for(let bt=0;bt<pe.length;bt++){let Q=pe[bt],me=Q.role==="system"&&(Q.text?.startsWith("[ACTION RESULT]")||Q.text?.startsWith("[TOOL RESULT]")||Q.text?.startsWith("SUCCESS:")||Q.text?.startsWith("ERROR:")||Q.fullText?.startsWith("[ACTION RESULT]")||Q.fullText?.startsWith("[TOOL RESULT]")||Q.fullText?.startsWith("SUCCESS:")||Q.fullText?.startsWith("ERROR:")),Ie=Q.fullText||Q.text||"",Ke=Ie.trim();if(!(!Ke&&!Q.binaryPart)){if(me){let Ne=!Ke.startsWith("[ACTION RESULT]")&&!Ke.startsWith("[TOOL RESULT]")?`[ACTION RESULT]: ${Ke}`:Ke;ve.push(Ne),Q.binaryPart&&(et=Q.binaryPart)}else if(Q.role==="agent"){!Ge&&ve.length>0&&St();let Ne=Ke,Mt=ba(Ne),to=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,Xt=[],Ot;for(;(Ot=to.exec(Mt))!==null;)Xt.push(Ot.index);if(Xt.length>0){let Lo=Ta(Ne),dt=[];for(let vt=0;vt<Xt.length;vt++){let xt=Xt[vt],ho=vt+1<Xt.length?Xt[vt+1]:Ne.length;Lo.find(pt=>pt.fullMatch&&Ne.startsWith(pt.fullMatch,xt))||dt.push({start:xt,end:ho})}if(dt.length>0){let vt="",xt=0;for(let ho of dt)vt+=Ne.substring(xt,ho.start),xt=ho.end;vt+=Ne.substring(xt),Ne=vt.trim()}}if(!Ne)continue;let eo=Ie.endsWith(`
284
- `),Ao=Ne.toLowerCase().includes("tool:")||Ne.toLowerCase().includes("action:"),_o=!1;for(let Lo=bt+1;Lo<pe.length;Lo++){let dt=pe[Lo];if(dt.role==="agent"){let vt=(dt.fullText||dt.text||"").trim();if(vt){_o=vt.startsWith("[");break}}}Ce.push(Ne),Ao&&eo&&_o?Ge=!0:Ge=!1}}}St()}}let q=ya(Ye,ee,{profile:Un,thinkingLevel:Ve,mode:X,systemSettings:re,janitorModel:A,sessionStats:Sn,chatId:Ct,isPlayground:!!He.playground,aiProvider:U,apiKey:Je,apiTier:ot,wildcardTooling:Hr,wildercardTooling:ce,cols:_.columns-6,rows:30,onTokenChunk:(N,pe)=>{let Ce=Date.now();if(Os(Ce),typeof pe=="number"){Xi.current=pe;let ve=Ns.current;ve.startTime||(ve.startTime=Ce,ve.totalWords=0,ve.chunks=[]),ve.totalWords+=pe,ve.chunks||(ve.chunks=[]),ve.chunks.push({time:Ce,words:pe});let Ge=Ce-400;if(ve.chunks=ve.chunks.filter(St=>St.time>=Ge),ve.chunks.length>0){let St=ve.chunks.reduce((me,Ie)=>me+Ie.words,0),bt=ve.chunks[0].time,Q=Math.max(.4,(Ce-bt)/1e3);ve.wps=Math.round(St/Q*10)/10}}},onVisualFeedback:N=>{L(pe=>[...pe.map(ve=>ve.isStreaming?{...ve,isStreaming:!1}:ve),{id:"visual-"+Date.now()+"-"+Math.random().toString(36).substring(2,9),role:"system",text:N,isVisualFeedback:!0}])},onSubagentUpdate:()=>{Bc(ga.map(N=>({...N})))},onExecStart:N=>{Qe(),ae(),Zi(N),zn("")},onExecChunk:N=>{zn(pe=>pe+N)},onExecEnd:()=>{let N=Gs.current,pe=Ks.current||"";Gs.current=null,Ks.current="",L(Ce=>{if(!N)return Ce;let ve=na(pe),et=`[TERMINAL_RECORD]
283
+ `),...et?{binaryPart:et}:{}}),ve=[],et=null),Ke=!1};for(let bt=0;bt<pe.length;bt++){let Q=pe[bt],me=Q.role==="system"&&(Q.text?.startsWith("[ACTION RESULT]")||Q.text?.startsWith("[TOOL RESULT]")||Q.text?.startsWith("SUCCESS:")||Q.text?.startsWith("ERROR:")||Q.fullText?.startsWith("[ACTION RESULT]")||Q.fullText?.startsWith("[TOOL RESULT]")||Q.fullText?.startsWith("SUCCESS:")||Q.fullText?.startsWith("ERROR:")),Ie=Q.fullText||Q.text||"",Ge=Ie.trim();if(!(!Ge&&!Q.binaryPart)){if(me){let Ne=!Ge.startsWith("[ACTION RESULT]")&&!Ge.startsWith("[TOOL RESULT]")?`[ACTION RESULT]: ${Ge}`:Ge;ve.push(Ne),Q.binaryPart&&(et=Q.binaryPart)}else if(Q.role==="agent"){!Ke&&ve.length>0&&St();let Ne=Ge,Mt=ba(Ne),to=/\[\s*(?:tool:(?:functions\.)?|action:(?:functions\.)?|action:)([a-zA-Z0-9_]+)\s*\(/gi,Xt=[],Ot;for(;(Ot=to.exec(Mt))!==null;)Xt.push(Ot.index);if(Xt.length>0){let Lo=Ta(Ne),dt=[];for(let vt=0;vt<Xt.length;vt++){let xt=Xt[vt],ho=vt+1<Xt.length?Xt[vt+1]:Ne.length;Lo.find(pt=>pt.fullMatch&&Ne.startsWith(pt.fullMatch,xt))||dt.push({start:xt,end:ho})}if(dt.length>0){let vt="",xt=0;for(let ho of dt)vt+=Ne.substring(xt,ho.start),xt=ho.end;vt+=Ne.substring(xt),Ne=vt.trim()}}if(!Ne)continue;let eo=Ie.endsWith(`
284
+ `),Ao=Ne.toLowerCase().includes("tool:")||Ne.toLowerCase().includes("action:"),_o=!1;for(let Lo=bt+1;Lo<pe.length;Lo++){let dt=pe[Lo];if(dt.role==="agent"){let vt=(dt.fullText||dt.text||"").trim();if(vt){_o=vt.startsWith("[");break}}}Ce.push(Ne),Ao&&eo&&_o?Ke=!0:Ke=!1}}}St()}}let q=ya(Ye,ee,{profile:Un,thinkingLevel:Ve,mode:X,systemSettings:re,janitorModel:A,sessionStats:Sn,chatId:Ct,isPlayground:!!He.playground,aiProvider:U,apiKey:Je,apiTier:ot,wildcardTooling:Hr,wildercardTooling:ce,cols:_.columns-6,rows:30,onTokenChunk:(N,pe)=>{let Ce=Date.now();if(Os(Ce),typeof pe=="number"){Xi.current=pe;let ve=Ns.current;ve.startTime||(ve.startTime=Ce,ve.totalWords=0,ve.chunks=[]),ve.totalWords+=pe,ve.chunks||(ve.chunks=[]),ve.chunks.push({time:Ce,words:pe});let Ke=Ce-400;if(ve.chunks=ve.chunks.filter(St=>St.time>=Ke),ve.chunks.length>0){let St=ve.chunks.reduce((me,Ie)=>me+Ie.words,0),bt=ve.chunks[0].time,Q=Math.max(.4,(Ce-bt)/1e3);ve.wps=Math.round(St/Q*10)/10}}},onVisualFeedback:N=>{L(pe=>[...pe.map(ve=>ve.isStreaming?{...ve,isStreaming:!1}:ve),{id:"visual-"+Date.now()+"-"+Math.random().toString(36).substring(2,9),role:"system",text:N,isVisualFeedback:!0}])},onSubagentUpdate:()=>{Bc(ga.map(N=>({...N})))},onExecStart:N=>{Qe(),ae(),Zi(N),zn("")},onExecChunk:N=>{zn(pe=>pe+N)},onExecEnd:()=>{let N=Gs.current,pe=Ks.current||"";Gs.current=null,Ks.current="",L(Ce=>{if(!N)return Ce;let ve=na(pe),et=`[TERMINAL_RECORD]
285
285
  COMMAND: ${N}
286
286
  PTY: ${er}
287
287
  OUTPUT: ${ve.replace(/\n{3,}/g,`
288
288
 
289
- `)}`,St=[...Ce.map(bt=>bt.isStreaming?{...bt,isStreaming:!1}:bt),{id:"term-"+Date.now(),role:"system",text:et,isTerminalRecord:!0}];return $(St.length),St}),Zi(null),Ri(!1),zn("")},onToolResult:(N,pe)=>{if(N==="success"){if(bc(Ce=>Ce+1),pe==="generate_image"){Mc(et=>et+1);let ve={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[qo.quality]||.002;Sc(et=>et+ve)}}else N==="denied"?Tc(Ce=>Ce+1):wc(Ce=>Ce+1)},onIDEApproval:Uo,onToolApproval:async(N,pe,Ce={})=>{let ve=fn(pe||"{}"),et=ve.path||ve.targetPath||ve.file||"",Ge=re?.alwaysAskFiles||".env, .env.*, *.env",St=(N==="view_file"||N==="write_file"||N==="update_file")&&Sl(et,Ge),bt=et?wt.resolve(et).toLowerCase():"",Q=et?wt.extname(et).toLowerCase():"",Ie=N==="write_file"&&re.overwriteProtection!==!1&&et&&at.existsSync(wt.resolve(process.cwd(),et))&&(re.autoExec||Vs||Q&&Ys.current.has(Q)),Ke=!St&&!Ie&&(re.autoExec||Vs||N==="write_file"&&Q&&Ys.current.has(Q)||N==="update_file"&&bt&&nl.current.has(bt));if(N==="exec_command"){let{command:Ne}=ve,Mt=(Ne||"").trim(),to=/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i,Ot=(dt=>{let vt=[],xt="",ho=null;for(let yo=0;yo<dt.length;yo++){let pt=dt[yo];ho?(pt===ho&&(ho=null),xt+=pt):pt==='"'||pt==="'"?(ho=pt,xt+=pt):pt==="&"&&dt[yo+1]==="&"||pt==="|"&&dt[yo+1]==="|"?(xt.trim()&&(vt.push(xt.trim()),xt=""),yo++):pt===";"||pt==="|"||pt==="&"?xt.trim()&&(vt.push(xt.trim()),xt=""):xt+=pt}return xt.trim()&&vt.push(xt.trim()),vt.length>0?vt:[dt]})(Mt),eo=(dt,vt)=>{if(!vt)return!1;let xt=dt.toLowerCase(),ho=/[*?]/.test(vt),yo=vt.split(",").map(pt=>pt.trim().toLowerCase()).filter(Boolean);return ho?yo.some(pt=>{if(!/[*?]/.test(pt))return xt===pt?!0:xt.startsWith(pt)?/\s|[;&|/]/.test(xt.charAt(pt.length)):!1;try{if(oc(xt,pt,{dot:!0,nocase:!0}))return!0;let Zn=xt.match(/"[^"]*"|'[^']*'|\S+/g)||[];return[Zn.join(" "),Zn.slice(0,3).join(" "),Zn.slice(1).join(" ")].some(es=>es&&oc(es,pt,{dot:!0,nocase:!0}))}catch{return!1}return!1}):yo.some(pt=>xt===pt?!0:xt.startsWith(pt)?/\s|[;&|/]/.test(xt.charAt(pt.length)):!1)},Ao=Ot.some(dt=>eo(dt,re?.autoDisallowCommands)),_o=Ot.some(dt=>eo(dt,re?.alwaysAskCommands)),Lo=Ot.length>0&&Ot.every(dt=>eo(dt,re?.autoApproveCommands)||re?.autoApproveGit&&/^git\s+commit\b/i.test(dt));return Ao?"deny":_o?Ce.checkOnly?null:new Promise(dt=>{Fr(),an({tool:N,args:pe,resolve:dt}),le("terminalApproval")}):Lo||re?.autoApproveGit&&/^git\s+commit\b/i.test(Mt)||re.autoExec||Vs||rl.current.has(Mt)||Mt&&to.test(Mt)?"allow":Ce.checkOnly?null:new Promise(dt=>{Fr(),an({tool:N,args:pe,resolve:dt}),le("terminalApproval")})}return Ke?"allow":Ce.checkOnly?null:new Promise(Ne=>{Fr(),an({tool:N,args:pe,resolve:Ne,isOverwrite:!!(Ce.isOverwritePrompt||Ie)}),le("approval")})},onAskUser:async(N,pe)=>(Qe(),ae(),Fr(),new Promise(Ce=>{let ve=!1;qs({question:N,options:pe,resolve:et=>{ve||(ve=!0,L(Ge=>{if(Ge.some(Q=>Q.isAskRecord&&Q.text?.includes(`Selection: ${et}`)))return Ge;let bt=[...Ge,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
289
+ `)}`,St=[...Ce.map(bt=>bt.isStreaming?{...bt,isStreaming:!1}:bt),{id:"term-"+Date.now(),role:"system",text:et,isTerminalRecord:!0}];return $(St.length),St}),Zi(null),Ri(!1),zn("")},onToolResult:(N,pe)=>{if(N==="success"){if(bc(Ce=>Ce+1),pe==="generate_image"){Mc(et=>et+1);let ve={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[qo.quality]||.002;Sc(et=>et+ve)}}else N==="denied"?Tc(Ce=>Ce+1):wc(Ce=>Ce+1)},onIDEApproval:Uo,onToolApproval:async(N,pe,Ce={})=>{let ve=fn(pe||"{}"),et=ve.path||ve.targetPath||ve.file||"",Ke=re?.alwaysAskFiles||".env, .env.*, *.env",St=(N==="view_file"||N==="write_file"||N==="update_file")&&Sl(et,Ke),bt=et?wt.resolve(et).toLowerCase():"",Q=et?wt.extname(et).toLowerCase():"",Ie=N==="write_file"&&re.overwriteProtection!==!1&&et&&at.existsSync(wt.resolve(process.cwd(),et))&&(re.autoExec||Vs||Q&&Ys.current.has(Q)),Ge=!St&&!Ie&&(re.autoExec||Vs||N==="write_file"&&Q&&Ys.current.has(Q)||N==="update_file"&&bt&&nl.current.has(bt));if(N==="exec_command"){let{command:Ne}=ve,Mt=(Ne||"").trim(),to=/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i,Ot=(dt=>{let vt=[],xt="",ho=null;for(let yo=0;yo<dt.length;yo++){let pt=dt[yo];ho?(pt===ho&&(ho=null),xt+=pt):pt==='"'||pt==="'"?(ho=pt,xt+=pt):pt==="&"&&dt[yo+1]==="&"||pt==="|"&&dt[yo+1]==="|"?(xt.trim()&&(vt.push(xt.trim()),xt=""),yo++):pt===";"||pt==="|"||pt==="&"?xt.trim()&&(vt.push(xt.trim()),xt=""):xt+=pt}return xt.trim()&&vt.push(xt.trim()),vt.length>0?vt:[dt]})(Mt),eo=(dt,vt)=>{if(!vt)return!1;let xt=dt.toLowerCase(),ho=/[*?]/.test(vt),yo=vt.split(",").map(pt=>pt.trim().toLowerCase()).filter(Boolean);return ho?yo.some(pt=>{if(!/[*?]/.test(pt))return xt===pt?!0:xt.startsWith(pt)?/\s|[;&|/]/.test(xt.charAt(pt.length)):!1;try{if(oc(xt,pt,{dot:!0,nocase:!0}))return!0;let Zn=xt.match(/"[^"]*"|'[^']*'|\S+/g)||[];return[Zn.join(" "),Zn.slice(0,3).join(" "),Zn.slice(1).join(" ")].some(es=>es&&oc(es,pt,{dot:!0,nocase:!0}))}catch{return!1}return!1}):yo.some(pt=>xt===pt?!0:xt.startsWith(pt)?/\s|[;&|/]/.test(xt.charAt(pt.length)):!1)},Ao=Ot.some(dt=>eo(dt,re?.autoDisallowCommands)),_o=Ot.some(dt=>eo(dt,re?.alwaysAskCommands)),Lo=Ot.length>0&&Ot.every(dt=>eo(dt,re?.autoApproveCommands)||re?.autoApproveGit&&/^git\s+commit\b/i.test(dt));return Ao?"deny":_o?Ce.checkOnly?null:new Promise(dt=>{Fr(),an({tool:N,args:pe,resolve:dt}),le("terminalApproval")}):Lo||re?.autoApproveGit&&/^git\s+commit\b/i.test(Mt)||re.autoExec||Vs||rl.current.has(Mt)||Mt&&to.test(Mt)?"allow":Ce.checkOnly?null:new Promise(dt=>{Fr(),an({tool:N,args:pe,resolve:dt}),le("terminalApproval")})}return Ge?"allow":Ce.checkOnly?null:new Promise(Ne=>{Fr(),an({tool:N,args:pe,resolve:Ne,isOverwrite:!!(Ce.isOverwritePrompt||Ie)}),le("approval")})},onAskUser:async(N,pe)=>(Qe(),ae(),Fr(),new Promise(Ce=>{let ve=!1;qs({question:N,options:pe,resolve:et=>{ve||(ve=!0,L(Ke=>{if(Ke.some(Q=>Q.isAskRecord&&Q.text?.includes(`Selection: ${et}`)))return Ke;let bt=[...Ke,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
290
290
  Question: ${N}
291
- Selection: ${et}`,isAskRecord:!0}];return $(bt.length),bt}),Ce(et))}}),le("ask")})),onUsage:N=>{let pe=N.totalTokenCount||0,Ce=N.cachedContentTokenCount||0,ve=N.candidatesTokenCount||0,et=Math.max(0,pe-ve);if(ln({tokens:pe}),ji(Ge=>Ge+pe),et>0&&Yi(Ge=>Ge+et),Ce>0&&qi(Ge=>Ge+Ce),ve>0&&Qi(Ge=>Ge+ve),et>0||Ce>0){no.current.push({input:et,cached:Ce}),no.current.length>3&&no.current.shift();let Ge=no.current.reduce((Q,me)=>Q+me.input,0),St=no.current.reduce((Q,me)=>Q+me.cached,0),bt=Ge>0?St/Ge*100:0;vn(bt)}Ki(Ge=>Ge+1)}},async()=>zo.current?zo.current:null,Bo),J=!1,$e=null,_e=null,ke=!1,Ze=!1,Wt=!1,lt=!1,se=0,he=null,qe=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let N of q){if(await new Promise(Q=>setTimeout(Q,3)),N.type==="text"&&Os(Date.now()),v&&N.type==="text"&&(B=Date.now(),v=!1,re.progressiveRendering&&Ee()),N.type==="status"){if(N.content&&(N.content.includes("Steering Hint Injected")||N.content.includes("Question Forwarded"))){let Q=zo.current;Q&&(L(me=>{$(me.length+1);let Ie=Q.startsWith("/btw"),Ke=Ie?Q.replace(/^\/btw\s*/,""):Q,Ne=Ie?"[QUESTION]":"[STEERING HINT]";return[...me,{id:"hint-"+Date.now(),role:"user",text:`${Ne}
292
- ${Ke}`,color:"cyan",isSteeringHint:!0,hintType:Ie?"QUESTION":"STEERING HINT",hintContent:Ke}]}),Rs(null),zo.current=null)}N.content?.includes("[start]")||Qs(N.content),N.content?.includes("[start]")?(clearInterval(pr),hr(0),pr=setInterval(()=>{hr(Q=>Q+1)},1e3)):N.content?.includes("[end]")&&(hr(0),clearInterval(pr)),Ln()&&ls(N.content),N.content==="Request Cancelled"&&(Qe(),ae(),g());continue}if(N.type==="status_history"){Qs(N.content),Ln()&&ls(N.content),L(Q=>[...Q,{id:"condense-"+Date.now(),role:"system",text:`\u2726 ${N.content}
293
- \u2800`,isMeta:!0}]);continue}if(N.type==="summary_injected"){L(Q=>Q.map(me=>me.id===N.content.id?{...me,fullText:N.content.text}:me));continue}if(N.type==="spinner"){Ic(N.content);continue}if(N.type==="model_update"){Nc(N.content);continue}if(N.type==="turn_reset"){if(Qe(),ae(),$e=null,_e=null,J=!1,ke=!1,Ze=!1,lt=!1,Wt=!1,L(Q=>{let me=Q.map(Ie=>{if(Ie.isStreaming){let Ke=Ie.text?Yt(Ie.text):Ie.text,Ne=Ie.fullText?Yt(Ie.fullText):Ie.fullText;return{...Ie,isStreaming:!1,text:Ke,fullText:Ne}}return Ie});return $(me.length),me}),Jo(),global.gc){for(let Q=0;Q<2;Q++)global.gc(),await new Promise(me=>setImmediate(me));m.current=Date.now()}continue}if(N.type==="interactive_turn_finished"){Js(!1),hr(0),clearInterval(pr),Ln()&&ls(null),b=!0,re?.agentFinishSound&&(async()=>{try{let me=(await Zo())[Ct],Ie=Br(me,String(Ct));ki(Ie)}catch{ki(String(Ct))}})(),Jo(),re?.autoTruncateResults&&L(Q=>{let me=Q.map(Ie=>{let Ke=Ie.fullText||Ie.text||"";if(!Ke.startsWith("[ACTION RESULT]: ")&&!Ke.startsWith("[TOOL RESULT]: ")||Ke.startsWith("[ACTION RESULT]: Goal")||Ke.includes("[ACTION RESULT]: ...Old result truncated")||Ke.includes("[ACTION RESULT]: Diff result ")||Ke.startsWith("[ACTION RESULT]: USER CHOOSE")||Ke.startsWith("[ACTION RESULT]: Skill:")||Ke.startsWith("[ACTION RESULT]: DOCs:")||Ke.startsWith("[ACTION RESULT]: Markdown parsed")||Ke.startsWith("[ACTION RESULT]: Search results for [")||Ke.startsWith("[ACTION RESULT]: AI Mode temporarily failed")||Ke.startsWith("[ACTION RESULT]: Background subagent started. Task ID:")||/^\[ACTION RESULT\]: File \[.*?\] saved/s.test(Ke))return Ie;if(re?.overwriteProtection!==!1){let Ne=Ke.match(/^\[ACTION RESULT\]:\s*File\s*\[(.*?)\]\s*updated(?:\s+with\s+some\s+blocks\s+failed)?\.\s*(?:\[(\d+\/\d+)\]\s*blocks\s*applied\.)?([\s\S]*)$/);if(Ne)try{let Mt=Ne[1],to=Ne[2]||"",Xt=Ne[3]||"",Ot=wt.basename(Mt),eo=Xt.replace("[DIFF_START]","");eo=eo.replace(/\[DIFF_END\](?=[^\[]*$)/,""),eo=eo.split(/\r?\n/).filter(oi=>{let Rn=oi.trim();return Rn.startsWith("-")||Rn.startsWith("+")||Rn.startsWith("@@")}).join(`
294
- `).trim();let Ao=0,_o=0,Lo=Xt.matchAll(/@@\s*([^@]+?)\s*@@/g);for(let oi of Lo){let Rn=oi[1],Cl=Rn.match(/\+(\d+)/),Ml=Rn.match(/-(\d+)/);Cl&&(Ao+=parseInt(Cl[1],10)),Ml&&(_o+=parseInt(Ml[1],10))}let dt=[];Ao>0&&dt.push(`+${Ao}`),_o>0&&dt.push(`-${_o}`);let vt=dt.length>0?` Total ${dt.join(" ")} changes.`:"",xt=wt.join(Co,"DiffBackups");at.ensureDirSync(xt);let ho=String(Date.now()).slice(-5),yo=hu.randomBytes(2).toString("hex"),pt=`${Ot}-diff-${ho}-${yo}.txt`,Zn=wt.join(xt,pt);at.writeFileSync(Zn,eo,"utf8");let yl=`${Co.replaceAll("\\","/").replace(Es.homedir().replaceAll("\\","/"),"~")}/DiffBackups/${pt}`,es=to?` ${to} blocks.`:"";return{...Ie,fullText:`[ACTION RESULT]: Diff result ${Ot} saved in '${yl}'.${es}${vt}`}}catch{}}return{...Ie,fullText:"[ACTION RESULT]: ...Old result truncated to save tokens"}});return Pn(Ct,null,me),$(me.length),me}),process.stdout.isTTY&&(async()=>{try{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}})();continue}if(N.type==="visual_feedback"){Qe(),ae(),L(Q=>{let me=[...Q,{id:"feedback-"+Date.now()+"-"+Math.random().toString(36).substring(2,9),role:"system",text:Yt(N.content),isVisualFeedback:!0}];return $(me.length),me});continue}if(N.type==="exec_start"){Qe(),ae();continue}if(N.type==="liveTokens"){ln({tokens:N.content});continue}if(N.type==="usage"){let Q=N.content.totalTokenCount||0,me=N.content.cachedContentTokenCount||0,Ie=N.content.candidatesTokenCount||0,Ke=Math.max(0,Q-Ie);if(ln({tokens:Q}),ji(Ne=>Ne+Q),Ke>0&&Yi(Ne=>Ne+Ke),me>0&&qi(Ne=>Ne+me),Ie>0&&Qi(Ne=>Ne+Ie),Ke>0||me>0){no.current.push({input:Ke,cached:me}),no.current.length>3&&no.current.shift();let Ne=no.current.reduce((Xt,Ot)=>Xt+Ot.input,0),Mt=no.current.reduce((Xt,Ot)=>Xt+Ot.cached,0),to=Ne>0?Mt/Ne*100:0;vn(to)}Ki(Ne=>Ne+1);continue}if(N.type==="tool_time"){Cc(Q=>Q+N.content);continue}if(N.type==="tool_result"){ae(),$e=null,_e=null,J=!1,ke=!1,Ze=!1,lt=!1,Wt=!1,se=0,he=null,L(Q=>{let me=[...Q,{id:"tool-"+Date.now()+"-"+Math.random().toString(36).substring(2,7),role:"system",text:Yt(N.content),fullText:Yt(N.aiContent),binaryPart:N.binaryPart,toolName:N.toolName}];return $(me.length),me}),Y.current&&(_e=Y.current.id,Ze=!0);continue}let pe=N.content;if(N.type==="text"&&pe.includes("Request Cancelled")){if(global.gc){for(let Q=0;Q<3;Q++)global.gc(),await new Promise(me=>setImmediate(me));m.current=Date.now()}continue}let Ce=pe.toLowerCase();if(pe.includes("```")&&(ke=!ke),(Ce.includes("tool:")||Ce.includes("action:"))&&(Ze=!0,se=0,he=null,(pe.includes("[tool:")||pe.includes("[action:"))&&(se=0)),Ze){for(let Q=0;Q<pe.length;Q++){let me=pe[Q];!he&&(me==="'"||me==='"'||me==="`")?he=me:he&&me===he&&pe[Q-1]!=="\\"&&(he=null),he||(me==="("||me==="["?se++:(me===")"||me==="]")&&se--)}se<=0&&!he&&(Ze=!1)}let ve=/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])/i,et=(Q,me,Ie=1)=>{let Ke=me>0?Q[me-1]:"",Ne=me+Ie<Q.length?Q[me+Ie]:"";return Ke==="`"&&Ne==="`"},Ge=Q=>{let me=/(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\])/gi,Ie;for(;(Ie=me.exec(Q))!==null;)if(!et(Q,Ie.index,Ie[0].length))return{index:Ie.index,length:Ie[0].length};return{index:-1,length:0}},St=Y.current?.role==="agent"&&Y.current.text||"",bt=!Wt&&St.trim().length===0;if(!J&&bt&&(ve.test(pe)||ve.test(St+pe))){let Q=ve.test(pe)?pe:St+pe,me=Q.match(ve),Ie=me.index,Ke=me[0].length,Ne=Q.substring(Ie+Ke);Qe(),Y.current=null,J=!0,Wt=!0,$e="think-"+Date.now(),Y.current={id:$e,role:"think",text:"",isStreaming:!0,startTime:Date.now()};let Mt=Ge(Ne);if(Mt.index!==-1){let Xt=Ne.substring(0,Mt.index).replace(/^\r?\n+/,"").replace(/\r?\n+$/,""),Ot=Ne.substring(Mt.index+Mt.length);Y.current.text=Yt(Xt);let eo=Y.current.startTime||Date.now();Y.current.duration=Date.now()-eo,ae(),J=!1,_e="agent-"+Date.now(),Y.current={id:_e,role:"agent",text:"",isStreaming:!0},Ot&&ft(Ot)}else{let to=Ne.replace(/^\r?\n+/,"");to&&ft(to)}continue}if(!J&&!Wt&&pe.trim().length>0&&(Wt=!0),J&&Y.current?.role==="think"){Qe();let me=(Y.current.text||"")+pe,Ie=Ge(me);if(Ie.index!==-1){let Ke=me.substring(0,Ie.index),Ne=me.substring(Ie.index+Ie.length);Y.current.text=Yt(Ke);let Mt=Y.current.startTime||Date.now();Y.current.duration=Date.now()-Mt,ae(),J=!1,_e="agent-"+Date.now(),Y.current={id:_e,role:"agent",text:"",isStreaming:!0},Ne&&ft(Ne)}else ft(pe);continue}else if(!J){let Q=pe.toLowerCase();!lt&&(Q.includes("tool:")||Q.includes("action:"))&&(lt=!0),!Y.current||Y.current.role!=="agent"?(_e="agent-"+Date.now(),Y.current={id:_e,role:"agent",text:Yt(pe),isStreaming:!0},it()):ft(pe)}}let je=Date.now();yc(N=>N+(je-B))}catch(G){L(ee=>($(ee.length+1),[...ee,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${G.message}`}]))}finally{let G=Date.now()-B;if(Y.current&&(Y.current.workedDuration=G),rt.current&&(await mt(),clearInterval(rt.current),rt.current=null),Js(!1),Qs(null),hr(0),clearInterval(pr),ae(),Zs.current&&g(),Jo(),global.gc)try{for(let ee=0;ee<3;ee++)global.gc(),await new Promise(z=>setImmediate(z));m.current=Date.now()}catch{}if(b||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),zo.current){ei(zo.current),Rs(null);let ee=zo.current;zo.current=null,L(z=>{let V=[...z],q=V.reverse().find(J=>J.text?.includes("[STEERING HINT: QUEUED]")||J.text?.includes("[QUESTION: QUEUED]"));return q&&(q.text.includes("[STEERING HINT: QUEUED]")?q.text=q.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]"):q.text.includes("[QUESTION: QUEUED]")&&(q.text=q.text.replace("[QUESTION: QUEUED]","[QUESTION: FINISHED_TURN]"))),V.reverse()}),le("resolution")}L(ee=>{let z=Date.now()-B,V=!1,q=[...ee].reverse().map(_e=>{let ke=_e.isStreaming?{..._e,isStreaming:!1}:_e;return ke.text&&(ke.text=(" "+ke.text).slice(1)),!V&&ke.role==="agent"&&(V=!0,ke={...ke,workedDuration:z}),ke}).reverse();if(!q.some(_e=>_e.role==="agent"&&_e.text?.trim().length>0)){let _e=[...q].reverse().find(ke=>ke.role==="think"&&ke.text?.trim().length>0);_e&&q.push({id:"agent-fallback-"+Date.now(),role:"agent",text:_e.text,isStreaming:!1,workedDuration:z})}let $e=q.filter(_e=>!String(_e.id).startsWith("welcome")&&(!_e.isMeta||_e.text&&_e.text.includes("Request Cancelled")));return Pn(Ct,null,$e),$(q.length),q})}})()}w(""),W(!1)}},st=rr(()=>{if(C.startsWith("/skill edit ")&&!tt){let n=C.split(" "),h=n[n.length-1];if(h&&h.startsWith("--")){let x=h.slice(2).toLowerCase(),c=[...wi||[],...bi||[]],g=new Set,b=[];for(let v of c){let G=(v?.filePath||"").replace(/\\/g,"/").toLowerCase(),ee=G.includes("/skills/fluxflow/skill.md")||G.includes("/skills/about-fluxflow/skill.md")||v?.name?.toLowerCase()==="fluxflow";v&&v.name&&!ee&&!g.has(v.name.toLowerCase())&&(g.add(v.name.toLowerCase()),b.push(v))}return b.filter(v=>v.name.toLowerCase().includes(x)).map(v=>({cmd:`--${v.name}`,desc:v.description||"Skill"}))}}if(C.startsWith("/")&&!tt){let n=C.split(" "),h=n[n.length-1].toLowerCase();if(n.length===1){let c=h.startsWith("/")?h.slice(1):h;return bl.filter(g=>(g.cmd.startsWith("/")?g.cmd.slice(1):g.cmd).toLowerCase().includes(c))}let x=bl;for(let c=0;c<n.length-1;c++){let g=n[c].toLowerCase(),b=x.find(B=>B.cmd.toLowerCase()===g);if(b&&b.subs)x=b.subs;else return[]}return x.filter(c=>c.cmd.toLowerCase().includes(h))}let f=C.split(" "),a=f[f.length-1],E=a&&a.startsWith("\\@");if((a&&a.startsWith("@")||E)&&!tt){let n=a.indexOf("#"),h=n!==-1,x=E?2:1,c=h?a.substring(x,n).toLowerCase():a.slice(x).toLowerCase(),g=h?a.substring(n):"";return Iu(process.cwd()).filter(v=>v.name.toLowerCase().includes(c)).map(v=>{let G=v.relativePath.replace(/\\/g,"/"),ee=G.startsWith(".")?G:"./"+G;return{cmd:(E?"\\@":"@")+"["+ee+g+"]",desc:v.relativePath}})}return[]},[C,tt]);ut(()=>{let f=0;for(;f<st.length;){let a=st[f],E=a?.cmd||a||"";if(typeof E=="string"&&E.trimStart().startsWith("---"))f++;else break}Ae(f<st.length?f:0)},[st]);let[Zr,Rr]=Z(0),Tl=Re(0);ut(()=>{let f=Tl.current>0,a=st.length>0;if(Tl.current=st.length,!a){Rr(0);return}if(!f){Rr(1);return}Rr(st.length)},[st]),ut(()=>{if(Zr>0&&Zr<st.length){let f=setTimeout(()=>{Rr(a=>Math.min(a+1,st.length))},1);return()=>clearTimeout(f)}},[Zr,st.length]),ut(()=>{if(Et!=="providerBudgetSelect")return;let f=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside","ExpLabs","TokenHarbor","Infron","APInex","xKiro"],a=De.providerBudgets||{},E=f.reduce((o,n)=>(o[n]=!!(a[n]&&(a[n].agentLimit||a[n].tokenLimit||a[n].monthlyTokenLimit||a[n].dailyCostLimit||a[n].monthlyCostLimit)),o),{});Hi(E),Gr(0)},[Et]),ut(()=>{if(Et!=="providerBudgetFlow")return;let f={},a=De.providerBudgets||{};for(let E of Fn){let o=a[E]||{};f[E]={agentLimit:nn(o.agentLimit),tokenLimit:nn(o.tokenLimit),monthlyTokenLimit:nn(o.monthlyTokenLimit),dailyCostLimit:nn(o.dailyCostLimit),monthlyCostLimit:nn(o.monthlyCostLimit)}}cr(f),Eo(0)},[Et,Fn]);let qu=({label:f,isSelected:a})=>{let E=f==="Cancel"||f==="Back"||f.toLowerCase().includes("exit")||f.toLowerCase().includes("back");return e.createElement(u,{marginTop:E?1:0,backgroundColor:a?"#2a2a2a":void 0,paddingX:1,width:"100%"},e.createElement(i,{color:a?"white":"gray",bold:a},a?"\u276F ":" ",f))},To=(f,a,E,o=10,n=2,h=9)=>{let x=vo(E),c=!x&&E>0?Math.min(100,a/E*100):0,g=Math.round(c),b=Math.round(g/100*o),B="\u2588".repeat(b)+"\u2591".repeat(Math.max(0,o-b)),v=s.success||"green";g>=40&&g<=80?v=s.warning||"yellow":g>80&&(v=s.danger||"red");let G=f.toLowerCase().includes("cost")||f.toLowerCase().includes("spend"),ee=!G&&(f.toLowerCase().includes("token")||f.toLowerCase().includes("daily")||f.toLowerCase().includes("monthly")),z=x?"\u221E":G?`$${Number(E).toFixed(2)}`:ee?Ft(E):E,V=Number(a)||0,q=G?`$${V.toFixed(V<.01&&V>0?4:2)}`:ee?Ft(a):a,J;return x||c===0?J="0%":c>0&&c<1?J="<1%":J=`${g}%`,e.createElement(u,{flexDirection:"row",paddingLeft:n,key:f},e.createElement(u,{width:h},e.createElement(i,{color:s.textMuted},f,": ")),e.createElement(i,{color:v},B),e.createElement(i,{color:s.textMuted}," ",J," (",q,"/",z,")"))},_c=()=>{switch(Et){case"settings":return e.createElement(bs,{systemSettings:re,setSystemSettings:_t,apiTier:ot,setActiveView:le,setInputConfig:fo,saveSettings:zt,quotas:De,setMessages:L,aiProvider:U,autoCompletion:dr,setAutoCompletion:Ps,profileData:Un,setProfileData:Ls,setProviderReturnView:Is,setApiKey:Ut,initAI:Mo});case"theme":return e.createElement(bs,{systemSettings:re,setSystemSettings:_t,apiTier:ot,setActiveView:le,setInputConfig:fo,saveSettings:zt,quotas:De,setMessages:L,aiProvider:U,autoCompletion:dr,setAutoCompletion:Ps,profileData:Un,setProfileData:Ls,initialSelectingTheme:!0,onCloseTheme:()=>le("chat"),setProviderReturnView:Is,setApiKey:Ut,initAI:Mo});case"selectProvider":return e.createElement(Ht,{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:"Experiential Labs",value:"ExpLabs"},{label:"Token Harbor",value:"TokenHarbor"},{label:"Infron",value:"Infron"},{label:"APInex",value:"APInex"},{label:"xKiro",value:"xKiro"},{label:"Ollama",value:"Ollama"},...process.env.ENABLE_9ROUTER==="true"||process.env.ENABLE_9ROUTER===!0?[{label:"9router [Local Proxy]",value:"9router"}]:[],{label:"AIHubMix [Experimental]",value:"AIHubMix"},{label:"Mistral [Experimental]",value:"Mistral"},{label:"OpenRouter [Experimental]",value:"OpenRouter"},{label:"Custom [OpenAI Chat Completion]",value:"c_openai"},{label:"Back",value:sn}],theme:re.theme,onSelect:async o=>{if(o.value===sn||o.value==="settings"||o.value==="Back"){le(sn);return}let n=o.value,h=await mn(n),x="";if(n==="9router"){let c=await Ni();c.ok||(x=`
291
+ Selection: ${et}`,isAskRecord:!0}];return $(bt.length),bt}),Ce(et))}}),le("ask")})),onUsage:N=>{let pe=N.totalTokenCount||0,Ce=N.cachedContentTokenCount||0,ve=N.candidatesTokenCount||0,et=Math.max(0,pe-ve);if(ln({tokens:pe}),ji(Ke=>Ke+pe),et>0&&Yi(Ke=>Ke+et),Ce>0&&qi(Ke=>Ke+Ce),ve>0&&Qi(Ke=>Ke+ve),et>0||Ce>0){no.current.push({input:et,cached:Ce}),no.current.length>3&&no.current.shift();let Ke=no.current.reduce((Q,me)=>Q+me.input,0),St=no.current.reduce((Q,me)=>Q+me.cached,0),bt=Ke>0?St/Ke*100:0;vn(bt)}Ki(Ke=>Ke+1)}},async()=>zo.current?zo.current:null,Bo),J=!1,$e=null,_e=null,ke=!1,Ze=!1,Wt=!1,lt=!1,se=0,he=null,qe=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let N of q){if(await new Promise(Q=>setTimeout(Q,3)),N.type==="text"&&Os(Date.now()),v&&N.type==="text"&&(B=Date.now(),v=!1,re.progressiveRendering&&Ee()),N.type==="status"){if(N.content&&(N.content.includes("Steering Hint Injected")||N.content.includes("Question Forwarded"))){let Q=zo.current;Q&&(L(me=>{$(me.length+1);let Ie=Q.startsWith("/btw"),Ge=Ie?Q.replace(/^\/btw\s*/,""):Q,Ne=Ie?"[QUESTION]":"[STEERING HINT]";return[...me,{id:"hint-"+Date.now(),role:"user",text:`${Ne}
292
+ ${Ge}`,color:"cyan",isSteeringHint:!0,hintType:Ie?"QUESTION":"STEERING HINT",hintContent:Ge}]}),Rs(null),zo.current=null)}N.content?.includes("[start]")||Qs(N.content),N.content?.includes("[start]")?(clearInterval(pr),hr(0),pr=setInterval(()=>{hr(Q=>Q+1)},1e3)):N.content?.includes("[end]")&&(hr(0),clearInterval(pr)),Ln()&&ls(N.content),N.content==="Request Cancelled"&&(Qe(),ae(),g());continue}if(N.type==="status_history"){Qs(N.content),Ln()&&ls(N.content),L(Q=>[...Q,{id:"condense-"+Date.now(),role:"system",text:`\u2726 ${N.content}
293
+ \u2800`,isMeta:!0}]);continue}if(N.type==="summary_injected"){L(Q=>Q.map(me=>me.id===N.content.id?{...me,fullText:N.content.text}:me));continue}if(N.type==="spinner"){Ic(N.content);continue}if(N.type==="model_update"){Nc(N.content);continue}if(N.type==="turn_reset"){if(Qe(),ae(),$e=null,_e=null,J=!1,ke=!1,Ze=!1,lt=!1,Wt=!1,L(Q=>{let me=Q.map(Ie=>{if(Ie.isStreaming){let Ge=Ie.text?Yt(Ie.text):Ie.text,Ne=Ie.fullText?Yt(Ie.fullText):Ie.fullText;return{...Ie,isStreaming:!1,text:Ge,fullText:Ne}}return Ie});return $(me.length),me}),Jo(),global.gc){for(let Q=0;Q<2;Q++)global.gc(),await new Promise(me=>setImmediate(me));m.current=Date.now()}continue}if(N.type==="interactive_turn_finished"){Js(!1),hr(0),clearInterval(pr),Ln()&&ls(null),b=!0,re?.agentFinishSound&&(async()=>{try{let me=(await Zo())[Ct],Ie=Br(me,String(Ct));ki(Ie)}catch{ki(String(Ct))}})(),Jo(),re?.autoTruncateResults&&L(Q=>{let me=Q.map(Ie=>{let Ge=Ie.fullText||Ie.text||"";if(!Ge.startsWith("[ACTION RESULT]: ")&&!Ge.startsWith("[TOOL RESULT]: ")||Ge.startsWith("[ACTION RESULT]: Goal")||Ge.includes("[ACTION RESULT]: ...Old result truncated")||Ge.includes("[ACTION RESULT]: Diff result ")||Ge.startsWith("[ACTION RESULT]: USER CHOOSE")||Ge.startsWith("[ACTION RESULT]: Skill:")||Ge.startsWith("[ACTION RESULT]: DOCs:")||Ge.startsWith("[ACTION RESULT]: Markdown parsed")||Ge.startsWith("[ACTION RESULT]: Search results for [")||Ge.startsWith("[ACTION RESULT]: AI Mode temporarily failed")||Ge.startsWith("[ACTION RESULT]: Background subagent started. Task ID:")||Ge.startsWith("[ACTION RESULT]: Subagent task")||/^\[ACTION RESULT\]: File \[.*?\] saved/s.test(Ge))return Ie;if(re?.overwriteProtection!==!1){let Ne=Ge.match(/^\[ACTION RESULT\]:\s*File\s*\[(.*?)\]\s*updated(?:\s+with\s+some\s+blocks\s+failed)?\.\s*(?:\[(\d+\/\d+)\]\s*blocks\s*applied\.)?([\s\S]*)$/);if(Ne)try{let Mt=Ne[1],to=Ne[2]||"",Xt=Ne[3]||"",Ot=wt.basename(Mt),eo=Xt.replace("[DIFF_START]","");eo=eo.replace(/\[DIFF_END\](?=[^\[]*$)/,""),eo=eo.split(/\r?\n/).filter(oi=>{let Rn=oi.trim();return Rn.startsWith("-")||Rn.startsWith("+")||Rn.startsWith("@@")}).join(`
294
+ `).trim();let Ao=0,_o=0,Lo=Xt.matchAll(/@@\s*([^@]+?)\s*@@/g);for(let oi of Lo){let Rn=oi[1],Cl=Rn.match(/\+(\d+)/),Ml=Rn.match(/-(\d+)/);Cl&&(Ao+=parseInt(Cl[1],10)),Ml&&(_o+=parseInt(Ml[1],10))}let dt=[];Ao>0&&dt.push(`+${Ao}`),_o>0&&dt.push(`-${_o}`);let vt=dt.length>0?` Total ${dt.join(" ")} changes.`:"",xt=wt.join(Co,"DiffBackups");at.ensureDirSync(xt);let ho=String(Date.now()).slice(-5),yo=hu.randomBytes(2).toString("hex"),pt=`${Ot}-diff-${ho}-${yo}.txt`,Zn=wt.join(xt,pt);at.writeFileSync(Zn,eo,"utf8");let yl=`${Co.replaceAll("\\","/").replace(Es.homedir().replaceAll("\\","/"),"~")}/DiffBackups/${pt}`,es=to?` ${to} blocks.`:"";return{...Ie,fullText:`[ACTION RESULT]: Diff result ${Ot} saved in '${yl}'.${es}${vt}`}}catch{}}return{...Ie,fullText:"[ACTION RESULT]: ...Old result truncated to save tokens"}});return Pn(Ct,null,me),$(me.length),me}),process.stdout.isTTY&&(async()=>{try{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}catch{process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")}})();continue}if(N.type==="visual_feedback"){Qe(),ae(),L(Q=>{let me=[...Q,{id:"feedback-"+Date.now()+"-"+Math.random().toString(36).substring(2,9),role:"system",text:Yt(N.content),isVisualFeedback:!0}];return $(me.length),me});continue}if(N.type==="exec_start"){Qe(),ae();continue}if(N.type==="liveTokens"){ln({tokens:N.content});continue}if(N.type==="usage"){let Q=N.content.totalTokenCount||0,me=N.content.cachedContentTokenCount||0,Ie=N.content.candidatesTokenCount||0,Ge=Math.max(0,Q-Ie);if(ln({tokens:Q}),ji(Ne=>Ne+Q),Ge>0&&Yi(Ne=>Ne+Ge),me>0&&qi(Ne=>Ne+me),Ie>0&&Qi(Ne=>Ne+Ie),Ge>0||me>0){no.current.push({input:Ge,cached:me}),no.current.length>3&&no.current.shift();let Ne=no.current.reduce((Xt,Ot)=>Xt+Ot.input,0),Mt=no.current.reduce((Xt,Ot)=>Xt+Ot.cached,0),to=Ne>0?Mt/Ne*100:0;vn(to)}Ki(Ne=>Ne+1);continue}if(N.type==="tool_time"){Cc(Q=>Q+N.content);continue}if(N.type==="tool_result"){ae(),$e=null,_e=null,J=!1,ke=!1,Ze=!1,lt=!1,Wt=!1,se=0,he=null,L(Q=>{let me=[...Q,{id:"tool-"+Date.now()+"-"+Math.random().toString(36).substring(2,7),role:"system",text:Yt(N.content),fullText:Yt(N.aiContent),binaryPart:N.binaryPart,toolName:N.toolName}];return $(me.length),me}),Y.current&&(_e=Y.current.id,Ze=!0);continue}let pe=N.content;if(N.type==="text"&&pe.includes("Request Cancelled")){if(global.gc){for(let Q=0;Q<3;Q++)global.gc(),await new Promise(me=>setImmediate(me));m.current=Date.now()}continue}let Ce=pe.toLowerCase();if(pe.includes("```")&&(ke=!ke),(Ce.includes("tool:")||Ce.includes("action:"))&&(Ze=!0,se=0,he=null,(pe.includes("[tool:")||pe.includes("[action:"))&&(se=0)),Ze){for(let Q=0;Q<pe.length;Q++){let me=pe[Q];!he&&(me==="'"||me==='"'||me==="`")?he=me:he&&me===he&&pe[Q-1]!=="\\"&&(he=null),he||(me==="("||me==="["?se++:(me===")"||me==="]")&&se--)}se<=0&&!he&&(Ze=!1)}let ve=/^\s*(?:<think_fluxflow[^>]*>|<\|channel>thought|\[think_fluxflow\])/i,et=(Q,me,Ie=1)=>{let Ge=me>0?Q[me-1]:"",Ne=me+Ie<Q.length?Q[me+Ie]:"";return Ge==="`"&&Ne==="`"},Ke=Q=>{let me=/(?:<\/think_fluxflow>|<channel\|>|\[\/think_fluxflow\])/gi,Ie;for(;(Ie=me.exec(Q))!==null;)if(!et(Q,Ie.index,Ie[0].length))return{index:Ie.index,length:Ie[0].length};return{index:-1,length:0}},St=Y.current?.role==="agent"&&Y.current.text||"",bt=!Wt&&St.trim().length===0;if(!J&&bt&&(ve.test(pe)||ve.test(St+pe))){let Q=ve.test(pe)?pe:St+pe,me=Q.match(ve),Ie=me.index,Ge=me[0].length,Ne=Q.substring(Ie+Ge);Qe(),Y.current=null,J=!0,Wt=!0,$e="think-"+Date.now(),Y.current={id:$e,role:"think",text:"",isStreaming:!0,startTime:Date.now()};let Mt=Ke(Ne);if(Mt.index!==-1){let Xt=Ne.substring(0,Mt.index).replace(/^\r?\n+/,"").replace(/\r?\n+$/,""),Ot=Ne.substring(Mt.index+Mt.length);Y.current.text=Yt(Xt);let eo=Y.current.startTime||Date.now();Y.current.duration=Date.now()-eo,ae(),J=!1,_e="agent-"+Date.now(),Y.current={id:_e,role:"agent",text:"",isStreaming:!0},Ot&&ft(Ot)}else{let to=Ne.replace(/^\r?\n+/,"");to&&ft(to)}continue}if(!J&&!Wt&&pe.trim().length>0&&(Wt=!0),J&&Y.current?.role==="think"){Qe();let me=(Y.current.text||"")+pe,Ie=Ke(me);if(Ie.index!==-1){let Ge=me.substring(0,Ie.index),Ne=me.substring(Ie.index+Ie.length);Y.current.text=Yt(Ge);let Mt=Y.current.startTime||Date.now();Y.current.duration=Date.now()-Mt,ae(),J=!1,_e="agent-"+Date.now(),Y.current={id:_e,role:"agent",text:"",isStreaming:!0},Ne&&ft(Ne)}else ft(pe);continue}else if(!J){let Q=pe.toLowerCase();!lt&&(Q.includes("tool:")||Q.includes("action:"))&&(lt=!0),!Y.current||Y.current.role!=="agent"?(_e="agent-"+Date.now(),Y.current={id:_e,role:"agent",text:Yt(pe),isStreaming:!0},it()):ft(pe)}}let je=Date.now();yc(N=>N+(je-B))}catch(G){L(ee=>($(ee.length+1),[...ee,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${G.message}`}]))}finally{let G=Date.now()-B;if(Y.current&&(Y.current.workedDuration=G),rt.current&&(await mt(),clearInterval(rt.current),rt.current=null),Js(!1),Qs(null),hr(0),clearInterval(pr),ae(),Zs.current&&g(),Jo(),global.gc)try{for(let ee=0;ee<3;ee++)global.gc(),await new Promise(z=>setImmediate(z));m.current=Date.now()}catch{}if(b||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),zo.current){ei(zo.current),Rs(null);let ee=zo.current;zo.current=null,L(z=>{let V=[...z],q=V.reverse().find(J=>J.text?.includes("[STEERING HINT: QUEUED]")||J.text?.includes("[QUESTION: QUEUED]"));return q&&(q.text.includes("[STEERING HINT: QUEUED]")?q.text=q.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]"):q.text.includes("[QUESTION: QUEUED]")&&(q.text=q.text.replace("[QUESTION: QUEUED]","[QUESTION: FINISHED_TURN]"))),V.reverse()}),le("resolution")}L(ee=>{let z=Date.now()-B,V=!1,q=[...ee].reverse().map(_e=>{let ke=_e.isStreaming?{..._e,isStreaming:!1}:_e;return ke.text&&(ke.text=(" "+ke.text).slice(1)),!V&&ke.role==="agent"&&(V=!0,ke={...ke,workedDuration:z}),ke}).reverse();if(!q.some(_e=>_e.role==="agent"&&_e.text?.trim().length>0)){let _e=[...q].reverse().find(ke=>ke.role==="think"&&ke.text?.trim().length>0);_e&&q.push({id:"agent-fallback-"+Date.now(),role:"agent",text:_e.text,isStreaming:!1,workedDuration:z})}let $e=q.filter(_e=>!String(_e.id).startsWith("welcome")&&(!_e.isMeta||_e.text&&_e.text.includes("Request Cancelled")));return Pn(Ct,null,$e),$(q.length),q})}})()}w(""),W(!1)}},st=rr(()=>{if(C.startsWith("/skill edit ")&&!tt){let n=C.split(" "),h=n[n.length-1];if(h&&h.startsWith("--")){let x=h.slice(2).toLowerCase(),c=[...wi||[],...bi||[]],g=new Set,b=[];for(let v of c){let G=(v?.filePath||"").replace(/\\/g,"/").toLowerCase(),ee=G.includes("/skills/fluxflow/skill.md")||G.includes("/skills/about-fluxflow/skill.md")||v?.name?.toLowerCase()==="fluxflow";v&&v.name&&!ee&&!g.has(v.name.toLowerCase())&&(g.add(v.name.toLowerCase()),b.push(v))}return b.filter(v=>v.name.toLowerCase().includes(x)).map(v=>({cmd:`--${v.name}`,desc:v.description||"Skill"}))}}if(C.startsWith("/")&&!tt){let n=C.split(" "),h=n[n.length-1].toLowerCase();if(n.length===1){let c=h.startsWith("/")?h.slice(1):h;return bl.filter(g=>(g.cmd.startsWith("/")?g.cmd.slice(1):g.cmd).toLowerCase().includes(c))}let x=bl;for(let c=0;c<n.length-1;c++){let g=n[c].toLowerCase(),b=x.find(B=>B.cmd.toLowerCase()===g);if(b&&b.subs)x=b.subs;else return[]}return x.filter(c=>c.cmd.toLowerCase().includes(h))}let f=C.split(" "),a=f[f.length-1],E=a&&a.startsWith("\\@");if((a&&a.startsWith("@")||E)&&!tt){let n=a.indexOf("#"),h=n!==-1,x=E?2:1,c=h?a.substring(x,n).toLowerCase():a.slice(x).toLowerCase(),g=h?a.substring(n):"";return Iu(process.cwd()).filter(v=>v.name.toLowerCase().includes(c)).map(v=>{let G=v.relativePath.replace(/\\/g,"/"),ee=G.startsWith(".")?G:"./"+G;return{cmd:(E?"\\@":"@")+"["+ee+g+"]",desc:v.relativePath}})}return[]},[C,tt]);ut(()=>{let f=0;for(;f<st.length;){let a=st[f],E=a?.cmd||a||"";if(typeof E=="string"&&E.trimStart().startsWith("---"))f++;else break}Ae(f<st.length?f:0)},[st]);let[Zr,Rr]=Z(0),Tl=Re(0);ut(()=>{let f=Tl.current>0,a=st.length>0;if(Tl.current=st.length,!a){Rr(0);return}if(!f){Rr(1);return}Rr(st.length)},[st]),ut(()=>{if(Zr>0&&Zr<st.length){let f=setTimeout(()=>{Rr(a=>Math.min(a+1,st.length))},1);return()=>clearTimeout(f)}},[Zr,st.length]),ut(()=>{if(Et!=="providerBudgetSelect")return;let f=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside","ExpLabs","TokenHarbor","Infron","APInex","xKiro"],a=De.providerBudgets||{},E=f.reduce((o,n)=>(o[n]=!!(a[n]&&(a[n].agentLimit||a[n].tokenLimit||a[n].monthlyTokenLimit||a[n].dailyCostLimit||a[n].monthlyCostLimit)),o),{});Hi(E),Gr(0)},[Et]),ut(()=>{if(Et!=="providerBudgetFlow")return;let f={},a=De.providerBudgets||{};for(let E of Fn){let o=a[E]||{};f[E]={agentLimit:nn(o.agentLimit),tokenLimit:nn(o.tokenLimit),monthlyTokenLimit:nn(o.monthlyTokenLimit),dailyCostLimit:nn(o.dailyCostLimit),monthlyCostLimit:nn(o.monthlyCostLimit)}}cr(f),Eo(0)},[Et,Fn]);let qu=({label:f,isSelected:a})=>{let E=f==="Cancel"||f==="Back"||f.toLowerCase().includes("exit")||f.toLowerCase().includes("back");return e.createElement(u,{marginTop:E?1:0,backgroundColor:a?"#2a2a2a":void 0,paddingX:1,width:"100%"},e.createElement(i,{color:a?"white":"gray",bold:a},a?"\u276F ":" ",f))},To=(f,a,E,o=10,n=2,h=9)=>{let x=vo(E),c=!x&&E>0?Math.min(100,a/E*100):0,g=Math.round(c),b=Math.round(g/100*o),B="\u2588".repeat(b)+"\u2591".repeat(Math.max(0,o-b)),v=s.success||"green";g>=40&&g<=80?v=s.warning||"yellow":g>80&&(v=s.danger||"red");let G=f.toLowerCase().includes("cost")||f.toLowerCase().includes("spend"),ee=!G&&(f.toLowerCase().includes("token")||f.toLowerCase().includes("daily")||f.toLowerCase().includes("monthly")),z=x?"\u221E":G?`$${Number(E).toFixed(2)}`:ee?Ft(E):E,V=Number(a)||0,q=G?`$${V.toFixed(V<.01&&V>0?4:2)}`:ee?Ft(a):a,J;return x||c===0?J="0%":c>0&&c<1?J="<1%":J=`${g}%`,e.createElement(u,{flexDirection:"row",paddingLeft:n,key:f},e.createElement(u,{width:h},e.createElement(i,{color:s.textMuted},f,": ")),e.createElement(i,{color:v},B),e.createElement(i,{color:s.textMuted}," ",J," (",q,"/",z,")"))},_c=()=>{switch(Et){case"settings":return e.createElement(bs,{systemSettings:re,setSystemSettings:_t,apiTier:ot,setActiveView:le,setInputConfig:fo,saveSettings:zt,quotas:De,setMessages:L,aiProvider:U,autoCompletion:dr,setAutoCompletion:Ps,profileData:Un,setProfileData:Ls,setProviderReturnView:Is,setApiKey:Ut,initAI:Mo});case"theme":return e.createElement(bs,{systemSettings:re,setSystemSettings:_t,apiTier:ot,setActiveView:le,setInputConfig:fo,saveSettings:zt,quotas:De,setMessages:L,aiProvider:U,autoCompletion:dr,setAutoCompletion:Ps,profileData:Un,setProfileData:Ls,initialSelectingTheme:!0,onCloseTheme:()=>le("chat"),setProviderReturnView:Is,setApiKey:Ut,initAI:Mo});case"selectProvider":return e.createElement(Ht,{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:"Experiential Labs",value:"ExpLabs"},{label:"Token Harbor",value:"TokenHarbor"},{label:"Infron",value:"Infron"},{label:"APInex",value:"APInex"},{label:"xKiro",value:"xKiro"},{label:"Ollama",value:"Ollama"},...process.env.ENABLE_9ROUTER==="true"||process.env.ENABLE_9ROUTER===!0?[{label:"9router [Local Proxy]",value:"9router"}]:[],{label:"AIHubMix [Experimental]",value:"AIHubMix"},{label:"Mistral [Experimental]",value:"Mistral"},{label:"OpenRouter [Experimental]",value:"OpenRouter"},{label:"Custom [OpenAI Chat Completion]",value:"c_openai"},{label:"Back",value:sn}],theme:re.theme,onSelect:async o=>{if(o.value===sn||o.value==="settings"||o.value==="Back"){le(sn);return}let n=o.value,h=await mn(n),x="";if(n==="9router"){let c=await Ni();c.ok||(x=`
295
295
 
296
296
  \x1B[33m\u2726 WARNING: 9router does not appear to be running on ${c.url}.\x1B[39m
297
297
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m To start 9router: \x1B[36mnpx 9router\x1B[39m or \x1B[36mnpm i -g 9router && 9router\x1B[39m`)}if(n==="c_openai"){if(!re.customOpenAIBaseUrl){fo({label:"Enter Custom OpenAI Base URL (.../v1):",key:"customOpenAIBaseUrl",value:"",returnView:sn}),le("input");return}let c=h||"";try{li()}catch{}rn(n),Ut(c),Mo(c,{aiProvider:n,onIDEApproval:Uo});let g=(De.providerTiers||{})[n]||"Free",b=po(n,g)||"";Qt(b),Pt(g),_t(B=>({...B,memory:!1})),zt({aiProvider:n,activeModel:b,apiTier:g,quotas:De,systemSettings:{...re,memory:!1}}),L(B=>[...B,{role:"system",text:`\u2726 Switched to Custom (OpenAI)!${b?`
@@ -302,7 +302,7 @@ ${Ke}`,color:"cyan",isSteeringHint:!0,hintType:Ie?"QUESTION":"STEERING HINT",hin
302
302
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Model: ${g}.`:""}${rs(n,g)}${(n==="Ollama"||n==="InferX"||n==="SenseNova"||n==="AIHubMix"||n==="Poolside"||n==="9router"||n==="ExpLabs"||n==="TokenHarbor"||n==="Infron"||n==="APInex"||n==="xKiro"||n==="c_openai")&&re.memory?`
303
303
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available with ${b}.`:""}${n==="NVIDIA"&&process.env.NVIDIA_BASE_URL&&re.memory?`
304
304
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available with Custom Endpoints.`:""}${x}
305
- \u2800`,isMeta:!0}]),le(sn)}else fo({label:`Enter ${n==="c_openai"?"Custom (OpenAI)":n} API Key:`,key:"providerKey",provider:n,value:"",returnView:sn}),le("input")},onClose:()=>le(sn)});case"apiTier":return e.createElement(Ht,{title:`Show Paid models from ${U.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] ${ot==="Paid"?"\u25CF":""}`,value:"Paid"},{label:"Back",value:"settings"}],theme:re.theme,onSelect:o=>{if(o.value==="settings"||o.value==="Back"){le("settings");return}let n=o.value;Pt(n);let h={...De.providerTiers||{},[U]:n},x={...De,providerTiers:h};ao(x),zt({apiTier:n,quotas:x}),le("settings")}});case"resetMode":return e.createElement(Ht,{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:re.theme,onSelect:o=>{if(o.value==="apiTier"||o.value==="Back"){le("apiTier");return}let n=o.value,h={...De,resetMode:n};ao(h),n==="Custom"?(fo({label:"Enter monthly reset day (1-30):",key:"quotas",subKey:"resetDay",value:String(De.resetDay||1),returnView:"settings"}),le("input")):(zt({apiTier:ot,quotas:h}),le("settings"))},onClose:()=>le("apiTier")});case"budgetTypeSelect":return e.createElement(Ht,{title:"SELECT BUDGET TYPE",items:[{label:`Global Budget (single limit for all providers) ${ot==="Paid"&&!De.providerBudgets?.__useProvider?"\u25CF":""}`,value:"global"},{label:`Provider Budgets (set limits per provider individually) ${De.providerBudgets?.__useProvider?"\u25CF":""}`,value:"provider"},{label:"Back",value:Yo}],theme:re.theme,onSelect:o=>{if(o.value===Yo||o.value==="Back"){le(Yo);return}if(o.value==="global"){let n={...De,agentLimit:99999999,tokenLimit:99999999999999,monthlyTokenLimit:99999999999999,providerBudgets:{__useProvider:!1}};ao(n);let h=Yo==="settings"?"resetMode":"budgetResetMode";fo({label:"Enter Agent daily budget (tokens used):",key:"quotas",subKey:"tokenLimit",value:nn(n.tokenLimit),returnView:Yo,next:x=>({label:"Enter Agent monthly budget (tokens used):",key:"quotas",subKey:"monthlyTokenLimit",value:nn(x.monthlyTokenLimit),returnView:Yo,next:c=>({label:"Enter Daily Cost Limit ($ or 0 for unlimited):",key:"quotas",subKey:"dailyCostLimit",value:nn(c.dailyCostLimit),returnView:Yo,next:g=>({label:"Enter Monthly Cost Limit ($ or 0 for unlimited):",key:"quotas",subKey:"monthlyCostLimit",value:nn(g.monthlyCostLimit),returnView:h})})})}),le("input")}else if(o.value==="provider"){let n={...De,agentLimit:99999999,tokenLimit:99999999999999,monthlyTokenLimit:99999999999999,providerBudgets:{...De.providerBudgets||{},__useProvider:!0}};ao(n),le("providerBudgetSelect")}},onClose:()=>le(Yo)});case"providerBudgetSelect":{let o=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside","ExpLabs","TokenHarbor","Infron","APInex","xKiro"],n=o.some(h=>As[h]);return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:0,width:"100%"},e.createElement(u,{paddingX:1,marginBottom:1},e.createElement(i,{color:s.text,bold:!0},"SELECT PROVIDERS TO SET LIMITS FOR")),o.map((h,x)=>{let c=x===_i,g=!!As[h];return e.createElement(u,{key:h,backgroundColor:c?s.highlightBg||"#2a2a2a":void 0,paddingX:1,width:"100%",flexDirection:"row"},e.createElement(i,{color:c?s.text:s.textMuted,bold:c},c?"\u276F ":" "),e.createElement(i,{color:g?s.success||"green":s.textMuted},g?"\u2611":"\u2610"),e.createElement(i,{color:c?s.text:s.textMuted,bold:c}," ",h),g&&(De.providerBudgets?.[h]?.agentLimit||De.providerBudgets?.[h]?.tokenLimit||De.providerBudgets?.[h]?.monthlyTokenLimit||De.providerBudgets?.[h]?.dailyCostLimit||De.providerBudgets?.[h]?.monthlyCostLimit)?e.createElement(i,{color:s.primary||"cyan"}," (budget set)"):null)}),e.createElement(u,{paddingX:1,marginTop:1,flexDirection:"column"},e.createElement(i,{color:s.textMuted,italic:!0},"\u2191\u2193 Navigate \u2022 Space to toggle \u2022 Enter to confirm \u2022 ESC to go back"),!n&&e.createElement(i,{color:s.warning||"yellow",italic:!0}," Select at least one provider to continue")))}case"providerBudgetFlow":{let o=Fn.length,n=o*4;return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:0,width:"100%"},e.createElement(u,{paddingX:1,marginBottom:0,justifyContent:"space-between",flexDirection:"row"},e.createElement(i,{color:s.text,bold:!0},"PROVIDER BUDGET CONFIGURATION"),e.createElement(i,{color:s.textMuted,italic:!0},"(0 or blank = unlimited)")),e.createElement(u,{paddingX:1,marginTop:1,flexDirection:"row"},e.createElement(u,{width:13},e.createElement(i,{color:s.textMuted,bold:!0},"PROVIDER")),e.createElement(u,{width:20,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"DAILY TOKENS")),e.createElement(u,{width:22,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"MONTHLY TOKENS")),e.createElement(u,{width:18,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"DAILY COST ($)")),e.createElement(u,{width:20,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"MONTHLY COST ($)"))),e.createElement(u,{paddingX:1},e.createElement(i,{color:s.borderMuted},"\u2500".repeat(93))),Fn.map((h,x)=>{let c=x*4,g=x*4+1,b=x*4+2,B=x*4+3,v=$n===c,G=$n===g,ee=$n===b,z=$n===B,V=v||G||ee||z,q=ar[h]?.tokenLimit??"",J=ar[h]?.monthlyTokenLimit??"",$e=ar[h]?.dailyCostLimit??"",_e=ar[h]?.monthlyCostLimit??"";return e.createElement(u,{key:h,flexDirection:"row",paddingX:1,marginY:0,backgroundColor:V?s.highlightBg||"#2a2a2a":void 0},e.createElement(u,{width:13,flexDirection:"row"},e.createElement(i,{color:V?s.primary||"cyan":s.text,bold:V},V?"\u276F ":" ",h)),e.createElement(u,{width:20,paddingLeft:1,flexDirection:"row"},v?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ "),e.createElement(sr,{value:q,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},tokenLimit:ke}}))},onSubmit:()=>Eo(g)}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:q?s.text:s.textMuted},"[ ",q||"0 (\u221E)"," ]")),e.createElement(u,{width:22,paddingLeft:1,flexDirection:"row"},G?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ "),e.createElement(sr,{value:J,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},monthlyTokenLimit:ke}}))},onSubmit:()=>Eo(b)}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:J?s.text:s.textMuted},"[ ",J||"0 (\u221E)"," ]")),e.createElement(u,{width:18,paddingLeft:1,flexDirection:"row"},ee?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ $"),e.createElement(sr,{value:$e,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},dailyCostLimit:ke}}))},onSubmit:()=>Eo(B)}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:$e?s.warning||"yellow":s.textMuted},"[ ",$e?`$${$e}`:"0 (\u221E)"," ]")),e.createElement(u,{width:20,paddingLeft:1,flexDirection:"row"},z?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ $"),e.createElement(sr,{value:_e,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},monthlyCostLimit:ke}}))},onSubmit:()=>{x+1<o?Eo((x+1)*4):Eo(n)}}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:_e?s.warning||"yellow":s.textMuted},"[ ",_e?`$${_e}`:"0 (\u221E)"," ]")))}),e.createElement(u,{paddingX:1,marginTop:1},$n===n?e.createElement(u,{backgroundColor:s.highlightBg||"#2a2a2a",paddingX:1},e.createElement(i,{color:s.success||"green",bold:!0},"\u276F [ Save & Apply Budgets ]")):e.createElement(i,{color:s.textMuted}," [ Save & Apply Budgets ]")),e.createElement(u,{paddingX:1,marginTop:1,flexDirection:"column"},e.createElement(i,{color:s.textMuted,italic:!0},"\u2191\u2193/\u2190\u2192 Navigate \u2022 Enter next / save \u2022 ESC to go back")))}case"budgetResetMode":return e.createElement(Ht,{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:re.theme,onSelect:o=>{if(o.value==="chat"||o.value==="Back"){le("chat");return}let n=o.value,h={...De,resetMode:n};ao(h),n==="Custom"?(fo({label:"Enter monthly reset day (1-30):",key:"quotas",subKey:"resetDay",value:String(De.resetDay||1),returnView:"chat"}),le("input")):(zt({apiTier:ot,quotas:h}),le("chat"))},onClose:()=>le("chat")});case"budgetView":{let o=jn?.agent||0,n=De.agentLimit||99999999,h=jn?.tokens||0,x=De.tokenLimit||99999999999999,c=De.resetMode==="Custom"?qr?.tokens||0:ur?.tokens||0,g=De.monthlyTokenLimit||99999999999999,b=jn?.cost||0,B=De.dailyCostLimit||99999999999999,v=De.resetMode==="Custom"?qr?.cost||0:ur?.cost||0,G=De.monthlyCostLimit||99999999999999,ee=ot!=="Paid",z=!!De.providerBudgets?.__useProvider,V=De.providerBudgets||{},q=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside","ExpLabs","TokenHarbor","Infron","APInex","xKiro"].filter(ke=>V[ke]&&(V[ke].agentLimit||V[ke].tokenLimit||V[ke].monthlyTokenLimit||V[ke].dailyCostLimit||V[ke].monthlyCostLimit)),J=!z&&(vo(x)||vo(g))&&(vo(B)||vo(G)),$e="",_e="";if(De.resetMode==="Custom"){let ke=new Date,Ze=De.resetDay||1,Wt=ke.getFullYear(),lt=ke.getMonth();ke.getDate()>=Ze&&(lt+=1,lt>11&&(lt=0,Wt+=1));let se=new Date(Wt,lt,Ze,0,0,0);$e=`${se.toLocaleString("default",{month:"short"}).toUpperCase()}-${Ze}`;let qe=Math.max(0,se.getTime()-ke.getTime()),je=Math.floor(qe/(1e3*60*60)),N=Math.floor(je/24),pe=je%24;_e=`(${N} days: ${pe} hrs left)`}return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:1,paddingBottom:0,paddingTop:0,width:"100%"},e.createElement(u,{marginBottom:1,justifyContent:"space-between",width:"100%"},e.createElement(i,{color:s.text,bold:!0,underline:!0},"USAGE LIMITS"),e.createElement(i,{color:s.textMuted},"[ ESC to Close ]")),J?e.createElement(u,{padding:1,justifyContent:"center",alignItems:"center",width:"100%"},e.createElement(i,{color:s.text,bold:!0},"LIMITS NOT SET")):z&&q.length>0?e.createElement(u,{flexDirection:"column",gap:0,width:"100%"},(()=>{let ke=r?.columns||_?.columns||80;if(ke<115){let lt=Math.max(5,Math.min(30,ke-50));return q.map(se=>{let he=V[se],qe=0,je=jn?.models?.[se]||{};for(let Ge in je)qe+=je[Ge]?.tokens||0;let N=0,Ce=(De.resetMode==="Custom"?qr:ur)?.models?.[se]||{};for(let Ge in Ce)N+=Ce[Ge]?.tokens||0;let ve=0;for(let Ge in je)ve+=je[Ge]?.cost||0;let et=0;for(let Ge in Ce)et+=Ce[Ge]?.cost||0;return e.createElement(u,{key:se,flexDirection:"column",borderStyle:"single",borderColor:s.borderMuted,paddingX:1,width:"100%"},e.createElement(u,{marginBottom:0},e.createElement(i,{color:s.primary,bold:!0},"\u25C6 ",se)),To("Daily",qe,he.tokenLimit||99999999999999,lt,2,9),To("Monthly",N,he.monthlyTokenLimit||99999999999999,lt,2,9),(!vo(he.dailyCostLimit)||!vo(he.monthlyCostLimit))&&e.createElement(e.Fragment,null,To("Daily Cost",ve,he.dailyCostLimit||99999999999999,lt,2,11),To("Monthly Cost",et,he.monthlyCostLimit||99999999999999,lt,2,11)))})}let Wt=[];for(let lt=0;lt<q.length;lt+=2)Wt.push(q.slice(lt,lt+2));return Wt.map((lt,se)=>e.createElement(u,{key:se,flexDirection:"row",width:"100%"},lt.map(he=>{let qe=V[he],je=0,N=jn?.models?.[he]||{};for(let me in N)je+=N[me]?.tokens||0;let pe=0,ve=(De.resetMode==="Custom"?qr:ur)?.models?.[he]||{};for(let me in ve)pe+=ve[me]?.tokens||0;let et=0;for(let me in N)et+=N[me]?.cost||0;let Ge=0;for(let me in ve)Ge+=ve[me]?.cost||0;let St=lt.length===1,bt=St?ke:Math.floor(ke/2),Q=Math.max(5,Math.min(25,bt-36));return e.createElement(u,{key:he,flexDirection:"column",borderStyle:"single",borderColor:s.borderMuted,paddingX:1,width:St?"100%":"50%"},e.createElement(u,{marginBottom:0},e.createElement(i,{color:s.primary,bold:!0},"\u25C6 ",he)),To("Daily",je,qe.tokenLimit||99999999999999,Q,2,9),To("Monthly",pe,qe.monthlyTokenLimit||99999999999999,Q,2,9),(!vo(qe.dailyCostLimit)||!vo(qe.monthlyCostLimit))&&e.createElement(e.Fragment,null,To("Daily Cost",et,qe.dailyCostLimit||99999999999999,Q,2,11),To("Monthly Cost",Ge,qe.monthlyCostLimit||99999999999999,Q,2,11)))})))})(),$e?e.createElement(u,{marginLeft:2,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.accent||"magenta",bold:!0},$e),_e?e.createElement(i,{color:s.textMuted},` ${_e}`):null):e.createElement(u,{marginLeft:2,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.secondary||"blue",bold:!0},"Rolling 30-Day Window"))):e.createElement(u,{flexDirection:"column",borderStyle:"single",borderColor:s.borderMuted,paddingX:1,width:"100%"},To("Daily Tokens",h,x,"green"),To("Monthly Tokens",c,g,"yellow"),(!vo(B)||!vo(G))&&e.createElement(e.Fragment,null,To("Daily Cost",b,B,"cyan"),To("Monthly Cost",v,G,"magenta")),$e?e.createElement(u,{marginLeft:4,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.accent||"magenta",bold:!0},$e),_e?e.createElement(i,{color:s.textMuted},` ${_e}`):null):e.createElement(u,{marginLeft:4,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.secondary||"blue",bold:!0},"Rolling 30-Day Window"))))}case"input":return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:0,width:"100%"},e.createElement(u,{paddingX:1},e.createElement(i,{color:s.text,bold:!0},"DATA CONFIGURATION")),$o?.note&&e.createElement(u,{paddingX:1,marginBottom:1},e.createElement(i,{color:s.textMuted,italic:!0},$o.note)),e.createElement(u,{paddingX:1,flexDirection:"row"},e.createElement(i,{color:s.text,bold:!0},$o?.label," "),e.createElement(sr,{value:$o?.value||"",onChange:o=>fo(n=>({...n,value:o})),onSubmit:async o=>{let{key:n,subKey:h,next:x,onDone:c}=$o,g={...De},b={};if(n==="quotas"){let B;h.toLowerCase().includes("costlimit")?B=parseFloat(o)||0:h.toLowerCase().includes("limit")||h==="resetDay"?B=parseInt(o)||0:B=o,h==="resetDay"&&(B=Math.max(1,Math.min(30,B))),g[h]=B,ao(g),b.quotas=g}else if(n==="providerBudgets"){let B=$o.providerKey,v=h.toLowerCase().includes("limit")?parseInt(o)||0:o,G=g.providerBudgets||{};g.providerBudgets={...G,[B]:{...G[B]||{},[h]:v}},ao(g),b.quotas=g}else if(n==="activeModel")Qt(o),b.activeModel=o;else if(n==="janitorModel")Te(o),b.janitorModel=o;else if(n==="autoApproveCommands"||n==="autoDisallowCommands"||n==="alwaysAskCommands"){let B={...re,[n]:o.trim(),sandboxPreset:"Custom"};_t(B),b.systemSettings=B}else if(n==="externalDataPath"){let B={...re,useExternalData:!0,externalDataPath:o.trim()};_t(B),b.systemSettings=B,L(v=>[...v,{id:Date.now(),role:"system",text:"[EXTERNAL STORAGE] Flux Flow will use "+o.trim()+" for data after restart."}])}else if(n==="customOpenAIBaseUrl"){let B=o.trim().replace(/\/+$/,""),v={...re,customOpenAIBaseUrl:B,memory:!1};_t(v),b.systemSettings=v;let G=(De.providerTiers||{}).c_openai||"Free",ee=po("c_openai",G)||"";rn("c_openai"),Qt(ee),Pt(G),b.aiProvider="c_openai",b.activeModel=ee,b.apiTier=G;let V=await mn("c_openai")||"";Ut(V),Mo(V,{aiProvider:"c_openai",onIDEApproval:Uo}),L(q=>[...q,{id:Date.now(),role:"system",text:`\u2726 Custom OpenAI Base URL saved!
305
+ \u2800`,isMeta:!0}]),le(sn)}else fo({label:`Enter ${n==="c_openai"?"Custom (OpenAI)":n} API Key:`,key:"providerKey",provider:n,value:"",returnView:sn}),le("input")},onClose:()=>le(sn)});case"apiTier":return e.createElement(Ht,{title:`Show Paid models from ${U.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] ${ot==="Paid"?"\u25CF":""}`,value:"Paid"},{label:"Back",value:"settings"}],theme:re.theme,onSelect:o=>{if(o.value==="settings"||o.value==="Back"){le("settings");return}let n=o.value;Pt(n);let h={...De.providerTiers||{},[U]:n},x={...De,providerTiers:h};ao(x),zt({apiTier:n,quotas:x}),le("settings")}});case"resetMode":return e.createElement(Ht,{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:re.theme,onSelect:o=>{if(o.value==="apiTier"||o.value==="Back"){le("apiTier");return}let n=o.value,h={...De,resetMode:n};ao(h),n==="Custom"?(fo({label:"Enter monthly reset day (1-30):",key:"quotas",subKey:"resetDay",value:String(De.resetDay||1),returnView:"settings"}),le("input")):(zt({apiTier:ot,quotas:h}),le("settings"))},onClose:()=>le("apiTier")});case"budgetTypeSelect":return e.createElement(Ht,{title:"SELECT BUDGET TYPE",items:[{label:`Global Budget (single limit for all providers) ${ot==="Paid"&&!De.providerBudgets?.__useProvider?"\u25CF":""}`,value:"global"},{label:`Provider Budgets (set limits per provider individually) ${De.providerBudgets?.__useProvider?"\u25CF":""}`,value:"provider"},{label:"Back",value:Yo}],theme:re.theme,onSelect:o=>{if(o.value===Yo||o.value==="Back"){le(Yo);return}if(o.value==="global"){let n={...De,agentLimit:99999999,tokenLimit:99999999999999,monthlyTokenLimit:99999999999999,providerBudgets:{__useProvider:!1}};ao(n);let h=Yo==="settings"?"resetMode":"budgetResetMode";fo({label:"Enter Agent daily budget (tokens used):",key:"quotas",subKey:"tokenLimit",value:nn(n.tokenLimit),returnView:Yo,next:x=>({label:"Enter Agent monthly budget (tokens used):",key:"quotas",subKey:"monthlyTokenLimit",value:nn(x.monthlyTokenLimit),returnView:Yo,next:c=>({label:"Enter Daily Cost Limit ($ or 0 for unlimited):",key:"quotas",subKey:"dailyCostLimit",value:nn(c.dailyCostLimit),returnView:Yo,next:g=>({label:"Enter Monthly Cost Limit ($ or 0 for unlimited):",key:"quotas",subKey:"monthlyCostLimit",value:nn(g.monthlyCostLimit),returnView:h})})})}),le("input")}else if(o.value==="provider"){let n={...De,agentLimit:99999999,tokenLimit:99999999999999,monthlyTokenLimit:99999999999999,providerBudgets:{...De.providerBudgets||{},__useProvider:!0}};ao(n),le("providerBudgetSelect")}},onClose:()=>le(Yo)});case"providerBudgetSelect":{let o=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside","ExpLabs","TokenHarbor","Infron","APInex","xKiro"],n=o.some(h=>As[h]);return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:0,width:"100%"},e.createElement(u,{paddingX:1,marginBottom:1},e.createElement(i,{color:s.text,bold:!0},"SELECT PROVIDERS TO SET LIMITS FOR")),o.map((h,x)=>{let c=x===_i,g=!!As[h];return e.createElement(u,{key:h,backgroundColor:c?s.highlightBg||"#2a2a2a":void 0,paddingX:1,width:"100%",flexDirection:"row"},e.createElement(i,{color:c?s.text:s.textMuted,bold:c},c?"\u276F ":" "),e.createElement(i,{color:g?s.success||"green":s.textMuted},g?"\u2611":"\u2610"),e.createElement(i,{color:c?s.text:s.textMuted,bold:c}," ",h),g&&(De.providerBudgets?.[h]?.agentLimit||De.providerBudgets?.[h]?.tokenLimit||De.providerBudgets?.[h]?.monthlyTokenLimit||De.providerBudgets?.[h]?.dailyCostLimit||De.providerBudgets?.[h]?.monthlyCostLimit)?e.createElement(i,{color:s.primary||"cyan"}," (budget set)"):null)}),e.createElement(u,{paddingX:1,marginTop:1,flexDirection:"column"},e.createElement(i,{color:s.textMuted,italic:!0},"\u2191\u2193 Navigate \u2022 Space to toggle \u2022 Enter to confirm \u2022 ESC to go back"),!n&&e.createElement(i,{color:s.warning||"yellow",italic:!0}," Select at least one provider to continue")))}case"providerBudgetFlow":{let o=Fn.length,n=o*4;return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:0,width:"100%"},e.createElement(u,{paddingX:1,marginBottom:0,justifyContent:"space-between",flexDirection:"row"},e.createElement(i,{color:s.text,bold:!0},"PROVIDER BUDGET CONFIGURATION"),e.createElement(i,{color:s.textMuted,italic:!0},"(0 or blank = unlimited)")),e.createElement(u,{paddingX:1,marginTop:1,flexDirection:"row"},e.createElement(u,{width:13},e.createElement(i,{color:s.textMuted,bold:!0},"PROVIDER")),e.createElement(u,{width:20,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"DAILY TOKENS")),e.createElement(u,{width:22,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"MONTHLY TOKENS")),e.createElement(u,{width:18,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"DAILY COST ($)")),e.createElement(u,{width:20,paddingLeft:1},e.createElement(i,{color:s.textMuted,bold:!0},"MONTHLY COST ($)"))),e.createElement(u,{paddingX:1},e.createElement(i,{color:s.borderMuted},"\u2500".repeat(93))),Fn.map((h,x)=>{let c=x*4,g=x*4+1,b=x*4+2,B=x*4+3,v=$n===c,G=$n===g,ee=$n===b,z=$n===B,V=v||G||ee||z,q=ar[h]?.tokenLimit??"",J=ar[h]?.monthlyTokenLimit??"",$e=ar[h]?.dailyCostLimit??"",_e=ar[h]?.monthlyCostLimit??"";return e.createElement(u,{key:h,flexDirection:"row",paddingX:1,marginY:0,backgroundColor:V?s.highlightBg||"#2a2a2a":void 0},e.createElement(u,{width:13,flexDirection:"row"},e.createElement(i,{color:V?s.primary||"cyan":s.text,bold:V},V?"\u276F ":" ",h)),e.createElement(u,{width:20,paddingLeft:1,flexDirection:"row"},v?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ "),e.createElement(sr,{value:q,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},tokenLimit:ke}}))},onSubmit:()=>Eo(g)}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:q?s.text:s.textMuted},"[ ",q||"0 (\u221E)"," ]")),e.createElement(u,{width:22,paddingLeft:1,flexDirection:"row"},G?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ "),e.createElement(sr,{value:J,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},monthlyTokenLimit:ke}}))},onSubmit:()=>Eo(b)}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:J?s.text:s.textMuted},"[ ",J||"0 (\u221E)"," ]")),e.createElement(u,{width:18,paddingLeft:1,flexDirection:"row"},ee?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ $"),e.createElement(sr,{value:$e,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},dailyCostLimit:ke}}))},onSubmit:()=>Eo(B)}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:$e?s.warning||"yellow":s.textMuted},"[ ",$e?`$${$e}`:"0 (\u221E)"," ]")),e.createElement(u,{width:20,paddingLeft:1,flexDirection:"row"},z?e.createElement(u,{flexDirection:"row"},e.createElement(i,{color:s.primary||"cyan",bold:!0},"[ $"),e.createElement(sr,{value:_e,onChange:ke=>{cr(Ze=>({...Ze,[h]:{...Ze[h]||{},monthlyCostLimit:ke}}))},onSubmit:()=>{x+1<o?Eo((x+1)*4):Eo(n)}}),e.createElement(i,{color:s.primary||"cyan",bold:!0}," ]")):e.createElement(i,{color:_e?s.warning||"yellow":s.textMuted},"[ ",_e?`$${_e}`:"0 (\u221E)"," ]")))}),e.createElement(u,{paddingX:1,marginTop:1},$n===n?e.createElement(u,{backgroundColor:s.highlightBg||"#2a2a2a",paddingX:1},e.createElement(i,{color:s.success||"green",bold:!0},"\u276F [ Save & Apply Budgets ]")):e.createElement(i,{color:s.textMuted}," [ Save & Apply Budgets ]")),e.createElement(u,{paddingX:1,marginTop:1,flexDirection:"column"},e.createElement(i,{color:s.textMuted,italic:!0},"\u2191\u2193/\u2190\u2192 Navigate \u2022 Enter next / save \u2022 ESC to go back")))}case"budgetResetMode":return e.createElement(Ht,{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:re.theme,onSelect:o=>{if(o.value==="chat"||o.value==="Back"){le("chat");return}let n=o.value,h={...De,resetMode:n};ao(h),n==="Custom"?(fo({label:"Enter monthly reset day (1-30):",key:"quotas",subKey:"resetDay",value:String(De.resetDay||1),returnView:"chat"}),le("input")):(zt({apiTier:ot,quotas:h}),le("chat"))},onClose:()=>le("chat")});case"budgetView":{let o=jn?.agent||0,n=De.agentLimit||99999999,h=jn?.tokens||0,x=De.tokenLimit||99999999999999,c=De.resetMode==="Custom"?qr?.tokens||0:ur?.tokens||0,g=De.monthlyTokenLimit||99999999999999,b=jn?.cost||0,B=De.dailyCostLimit||99999999999999,v=De.resetMode==="Custom"?qr?.cost||0:ur?.cost||0,G=De.monthlyCostLimit||99999999999999,ee=ot!=="Paid",z=!!De.providerBudgets?.__useProvider,V=De.providerBudgets||{},q=["Google","DeepSeek","Mistral","NVIDIA","OpenRouter","Ollama","InferX","SenseNova","AIHubMix","Poolside","ExpLabs","TokenHarbor","Infron","APInex","xKiro"].filter(ke=>V[ke]&&(V[ke].agentLimit||V[ke].tokenLimit||V[ke].monthlyTokenLimit||V[ke].dailyCostLimit||V[ke].monthlyCostLimit)),J=!z&&(vo(x)||vo(g))&&(vo(B)||vo(G)),$e="",_e="";if(De.resetMode==="Custom"){let ke=new Date,Ze=De.resetDay||1,Wt=ke.getFullYear(),lt=ke.getMonth();ke.getDate()>=Ze&&(lt+=1,lt>11&&(lt=0,Wt+=1));let se=new Date(Wt,lt,Ze,0,0,0);$e=`${se.toLocaleString("default",{month:"short"}).toUpperCase()}-${Ze}`;let qe=Math.max(0,se.getTime()-ke.getTime()),je=Math.floor(qe/(1e3*60*60)),N=Math.floor(je/24),pe=je%24;_e=`(${N} days: ${pe} hrs left)`}return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:1,paddingBottom:0,paddingTop:0,width:"100%"},e.createElement(u,{marginBottom:1,justifyContent:"space-between",width:"100%"},e.createElement(i,{color:s.text,bold:!0,underline:!0},"USAGE LIMITS"),e.createElement(i,{color:s.textMuted},"[ ESC to Close ]")),J?e.createElement(u,{padding:1,justifyContent:"center",alignItems:"center",width:"100%"},e.createElement(i,{color:s.text,bold:!0},"LIMITS NOT SET")):z&&q.length>0?e.createElement(u,{flexDirection:"column",gap:0,width:"100%"},(()=>{let ke=r?.columns||_?.columns||80;if(ke<115){let lt=Math.max(5,Math.min(30,ke-50));return q.map(se=>{let he=V[se],qe=0,je=jn?.models?.[se]||{};for(let Ke in je)qe+=je[Ke]?.tokens||0;let N=0,Ce=(De.resetMode==="Custom"?qr:ur)?.models?.[se]||{};for(let Ke in Ce)N+=Ce[Ke]?.tokens||0;let ve=0;for(let Ke in je)ve+=je[Ke]?.cost||0;let et=0;for(let Ke in Ce)et+=Ce[Ke]?.cost||0;return e.createElement(u,{key:se,flexDirection:"column",borderStyle:"single",borderColor:s.borderMuted,paddingX:1,width:"100%"},e.createElement(u,{marginBottom:0},e.createElement(i,{color:s.primary,bold:!0},"\u25C6 ",se)),To("Daily",qe,he.tokenLimit||99999999999999,lt,2,9),To("Monthly",N,he.monthlyTokenLimit||99999999999999,lt,2,9),(!vo(he.dailyCostLimit)||!vo(he.monthlyCostLimit))&&e.createElement(e.Fragment,null,To("Daily Cost",ve,he.dailyCostLimit||99999999999999,lt,2,11),To("Monthly Cost",et,he.monthlyCostLimit||99999999999999,lt,2,11)))})}let Wt=[];for(let lt=0;lt<q.length;lt+=2)Wt.push(q.slice(lt,lt+2));return Wt.map((lt,se)=>e.createElement(u,{key:se,flexDirection:"row",width:"100%"},lt.map(he=>{let qe=V[he],je=0,N=jn?.models?.[he]||{};for(let me in N)je+=N[me]?.tokens||0;let pe=0,ve=(De.resetMode==="Custom"?qr:ur)?.models?.[he]||{};for(let me in ve)pe+=ve[me]?.tokens||0;let et=0;for(let me in N)et+=N[me]?.cost||0;let Ke=0;for(let me in ve)Ke+=ve[me]?.cost||0;let St=lt.length===1,bt=St?ke:Math.floor(ke/2),Q=Math.max(5,Math.min(25,bt-36));return e.createElement(u,{key:he,flexDirection:"column",borderStyle:"single",borderColor:s.borderMuted,paddingX:1,width:St?"100%":"50%"},e.createElement(u,{marginBottom:0},e.createElement(i,{color:s.primary,bold:!0},"\u25C6 ",he)),To("Daily",je,qe.tokenLimit||99999999999999,Q,2,9),To("Monthly",pe,qe.monthlyTokenLimit||99999999999999,Q,2,9),(!vo(qe.dailyCostLimit)||!vo(qe.monthlyCostLimit))&&e.createElement(e.Fragment,null,To("Daily Cost",et,qe.dailyCostLimit||99999999999999,Q,2,11),To("Monthly Cost",Ke,qe.monthlyCostLimit||99999999999999,Q,2,11)))})))})(),$e?e.createElement(u,{marginLeft:2,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.accent||"magenta",bold:!0},$e),_e?e.createElement(i,{color:s.textMuted},` ${_e}`):null):e.createElement(u,{marginLeft:2,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.secondary||"blue",bold:!0},"Rolling 30-Day Window"))):e.createElement(u,{flexDirection:"column",borderStyle:"single",borderColor:s.borderMuted,paddingX:1,width:"100%"},To("Daily Tokens",h,x,"green"),To("Monthly Tokens",c,g,"yellow"),(!vo(B)||!vo(G))&&e.createElement(e.Fragment,null,To("Daily Cost",b,B,"cyan"),To("Monthly Cost",v,G,"magenta")),$e?e.createElement(u,{marginLeft:4,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.accent||"magenta",bold:!0},$e),_e?e.createElement(i,{color:s.textMuted},` ${_e}`):null):e.createElement(u,{marginLeft:4,marginTop:1},e.createElement(i,{color:s.textMuted},"Monthly Reset: "),e.createElement(i,{color:s.secondary||"blue",bold:!0},"Rolling 30-Day Window"))))}case"input":return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,padding:0,width:"100%"},e.createElement(u,{paddingX:1},e.createElement(i,{color:s.text,bold:!0},"DATA CONFIGURATION")),$o?.note&&e.createElement(u,{paddingX:1,marginBottom:1},e.createElement(i,{color:s.textMuted,italic:!0},$o.note)),e.createElement(u,{paddingX:1,flexDirection:"row"},e.createElement(i,{color:s.text,bold:!0},$o?.label," "),e.createElement(sr,{value:$o?.value||"",onChange:o=>fo(n=>({...n,value:o})),onSubmit:async o=>{let{key:n,subKey:h,next:x,onDone:c}=$o,g={...De},b={};if(n==="quotas"){let B;h.toLowerCase().includes("costlimit")?B=parseFloat(o)||0:h.toLowerCase().includes("limit")||h==="resetDay"?B=parseInt(o)||0:B=o,h==="resetDay"&&(B=Math.max(1,Math.min(30,B))),g[h]=B,ao(g),b.quotas=g}else if(n==="providerBudgets"){let B=$o.providerKey,v=h.toLowerCase().includes("limit")?parseInt(o)||0:o,G=g.providerBudgets||{};g.providerBudgets={...G,[B]:{...G[B]||{},[h]:v}},ao(g),b.quotas=g}else if(n==="activeModel")Qt(o),b.activeModel=o;else if(n==="janitorModel")Te(o),b.janitorModel=o;else if(n==="autoApproveCommands"||n==="autoDisallowCommands"||n==="alwaysAskCommands"){let B={...re,[n]:o.trim(),sandboxPreset:"Custom"};_t(B),b.systemSettings=B}else if(n==="externalDataPath"){let B={...re,useExternalData:!0,externalDataPath:o.trim()};_t(B),b.systemSettings=B,L(v=>[...v,{id:Date.now(),role:"system",text:"[EXTERNAL STORAGE] Flux Flow will use "+o.trim()+" for data after restart."}])}else if(n==="customOpenAIBaseUrl"){let B=o.trim().replace(/\/+$/,""),v={...re,customOpenAIBaseUrl:B,memory:!1};_t(v),b.systemSettings=v;let G=(De.providerTiers||{}).c_openai||"Free",ee=po("c_openai",G)||"";rn("c_openai"),Qt(ee),Pt(G),b.aiProvider="c_openai",b.activeModel=ee,b.apiTier=G;let V=await mn("c_openai")||"";Ut(V),Mo(V,{aiProvider:"c_openai",onIDEApproval:Uo}),L(q=>[...q,{id:Date.now(),role:"system",text:`\u2726 Custom OpenAI Base URL saved!
306
306
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Switched to Custom (OpenAI)
307
307
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Endpoint: ${B}${ee?`
308
308
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Model: ${ee}`:""}
@@ -314,7 +314,7 @@ ${Ke}`,color:"cyan",isSteeringHint:!0,hintType:Ie?"QUESTION":"STEERING HINT",hin
314
314
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Ollama Endpoint automatically switched to Local`:""}${v==="Ollama"||v==="CrofAI"||v==="InferX"||v==="SenseNova"||v==="AIHubMix"||v==="Poolside"||v==="9router"||v==="ExpLabs"||v==="TokenHarbor"||v==="Infron"||v==="APInex"||v==="xKiro"?`
315
315
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available with ${v}`:""}${v==="NVIDIA"&&process.env.NVIDIA_BASE_URL?`
316
316
  \u2800\u2800\x1B[2m\u2514\u2500\x1B[22m Memory is not available`:""}${G}
317
- \u2800\u2800`,isMeta:!0}]))}if(x){let B=x(n==="quotas"||n==="providerBudgets"?g:o);fo(B)}else c?(zt({...b,apiTier:ot,quotas:g,imageSettings:b.imageSettings||qo}),fo(null),c(g)):(zt({...b,apiTier:ot,quotas:g,imageSettings:b.imageSettings||qo}),fo(null),le($o?.returnView||"settings"))}})),e.createElement(u,{paddingX:1,marginTop:1},e.createElement(i,{color:s.textMuted,dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":{let o=Yn==="modelBreakdown"||Yn==="dailyModelBreakdown",n=Yn==="daily"||Yn==="dailyModelBreakdown",h=n?jn:ur,x=n?"TODAY's USAGE":"LAST 30 DAYS USAGE",c=n?"TODAY'S MODEL TOKEN BREAKDOWN":"30-DAY MODEL TOKEN BREAKDOWN",g="Wall Time:",b="Tokens Used:",B="Images Made:",v="Image Credits:",G="Code Changes:",ee="Tool Calls:",z=Math.max(4,(r?.rows||_?.rows||24)-15),V=(se,he,qe,je,N,pe=0,Ce=!1)=>{let ve=r?.columns||_?.columns||80,et=Math.min(125,ve-2),Ge=Math.max(20,et-6),St=Math.max(5,Ge-pe-qe.length-5),bt=he;bt.length>St&&(bt=bt.substring(0,St-1)+"\u2026");let Q=Math.max(2,Ge-pe-bt.length-qe.length-2),me=" "+".".repeat(Q)+" ",Ie=" ".repeat(pe);return e.createElement(u,{key:se,width:Ge},e.createElement(i,{wrap:"truncate"},e.createElement(i,null,Ie),e.createElement(i,{color:je,bold:Ce},bt),e.createElement(i,{color:s.textMuted,dimColor:!0},me),e.createElement(i,{color:N,bold:Ce},qe)))},q=se=>{let he=Number(se)||0;return he<=0?"":he<.001?" [<$0.001]":` [$${he.toFixed(he<.01?4:3)}]`},J=se=>{let he=Number(se)||0;return he<=0?"":he<.001?"<$0.001":`$${he.toFixed(he<.01?4:3)}`},$e=[],_e=h?.models;if(!_e||Object.keys(_e).length===0)$e.push(e.createElement(u,{key:"empty",marginTop:1},e.createElement(i,{color:s.textMuted,italic:!0},"No model token usage recorded for ",n?"today":"the last 30 days",".")));else{let se=(fr||"").trim(),he="",qe="";if(se.includes(":")){let N=se.indexOf(":");he=se.substring(0,N).trim().toLowerCase(),qe=se.substring(N+1).trim().toLowerCase()}else he=se.toLowerCase();let je=Object.entries(_e).sort(([N],[pe])=>N.localeCompare(pe,void 0,{sensitivity:"base"})).filter(([N,pe])=>he&&!N.toLowerCase().includes(he)?!1:qe?Object.keys(pe).some(Ce=>Ce.toLowerCase().includes(qe)):!0);je.length===0?$e.push(e.createElement(u,{key:"no-matches",marginTop:1},e.createElement(i,{color:s.textMuted,italic:!0},'No results found matching "',fr,'".'))):je.forEach(([N,pe],Ce)=>{let ve=Object.entries(pe).sort(([Q],[me])=>Q.localeCompare(me,void 0,{sensitivity:"base"})).filter(([Q])=>!qe||Q.toLowerCase().includes(qe));if(ve.length===0)return;let et=ve.reduce((Q,[,me])=>Q+(me.tokens||0),0),Ge=ve.reduce((Q,[me,Ie])=>{if((Ie.cost||0)>0)return Q+Ie.cost;let Ke=Cr(N,me);if(!Ke)return Q;let Ne=(Ie.tokens||0)-(Ie.candidateTokens||0),Mt=Ie.cachedTokens||0,to=Math.max(0,Ne-Mt),Xt=Ie.candidateTokens||0,Ot=to/1e6*Ke.IN+Mt/1e6*Ke.CR+Xt/1e6*Ke.OUT;return Q+Ot},0),St=h?.providerRequests&&h.providerRequests[N]||0;Ce>0&&$e.length>0&&$e.push(e.createElement(u,{key:`space-prov-${N}`},e.createElement(i,null," ")));let bt=q(Ge);$e.push(V(`prov-${N}`,`${N}:`,`${Ft(et)} (${St})${bt}`,s.primary,s.text,0,!0)),ve.forEach(([Q,me],Ie)=>{Ie>0&&$e.push(e.createElement(u,{key:`space-mod-${N}-${Q}`},e.createElement(i,null," ")));let Ke=Cr(N,Q),Ne=(me.tokens||0)-(me.candidateTokens||0),Mt=me.cachedTokens||0,to=Math.max(0,Ne-Mt),Xt=me.candidateTokens||0,Ot=0,eo=0,Ao=0;Ke&&(Ot=to/1e6*Ke.IN,eo=Mt/1e6*Ke.CR,Ao=Xt/1e6*Ke.OUT);let _o=(me.cost||0)>0?me.cost:Ot+eo+Ao,Lo=q(_o);$e.push(V(`mod-${N}-${Q}`,`\xBB ${Q}:`,`${Ft(me.tokens||0)}${Lo}`,s.secondary,s.text,2,!0));let dt=q(Ot),vt=q(eo),xt=q(Ao);$e.push(V(`in-${N}-${Q}`,"\xBB Input Tokens:",`${Ft(Ne)}${dt}`,s.textMuted,s.text,5,!1)),Mt>0&&$e.push(V(`cache-${N}-${Q}`,"\xBB Cached:",`${Ft(Mt)}${vt}`,s.textMuted,s.text,7,!1)),$e.push(V(`out-${N}-${Q}`,"\xBB Output Tokens:",`${Ft(Xt)}${xt}`,s.textMuted,s.text,5,!1))})})}let ke=$e.length,Ze=Math.max(0,ke-z);oe.current=Ze;let Wt=Math.min(vc,Ze),lt=$e.slice(Wt,Wt+z);return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,paddingX:3,paddingY:1,paddingBottom:0,width:Math.min(125,(r?.columns||100)-2)},o?e.createElement(u,{flexDirection:"column"},e.createElement(u,{justifyContent:"space-between"},e.createElement(i,{color:s.text,bold:!0,underline:!0},c),ke>z&&e.createElement(i,{color:s.textMuted,dimColor:!0},"[",Wt+1,"-",Math.min(ke,Wt+z)," of ",ke,"] \u25B2\u25BC")),e.createElement(u,{marginTop:1},e.createElement(i,{color:s.secondary,bold:!0},"Filter (provider:model): "),e.createElement(i,{color:s.text},fr),e.createElement(i,{color:s.primary,bold:!0},"\u258A"),fr.length>0&&e.createElement(i,{color:s.textMuted,dimColor:!0,italic:!0}," (Type to search, Esc/Backspace to clear)")),e.createElement(u,{flexDirection:"column",height:z,marginTop:1},lt)):e.createElement(e.Fragment,null,e.createElement(u,{marginBottom:1},e.createElement(i,{color:s.text,bold:!0,underline:!0},"SESSION TELEMETRY")),e.createElement(u,{flexDirection:"column"},e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Session Duration:")),e.createElement(i,{color:s.text},kn(Date.now()-$i))),Gi>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Model Requests:")),e.createElement(i,{color:s.text},Gi)),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB API Time:")),e.createElement(i,{color:s.text},kn(Vr))),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Tool Time:")),e.createElement(i,{color:s.text},kn(jr)))),Vi>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Memory Agent:")),e.createElement(i,{color:s.text},Vi)),xo>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Tokens Consumed:")),e.createElement(i,{color:s.text},Ft(xo))),(It?.cost||0)>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Cost Estimate:")),e.createElement(i,{color:s.success||"green"},J(It.cost))),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Input Tokens:")),e.createElement(i,{color:s.text},Ft(xo-Vn))),ko>0&&e.createElement(u,{marginLeft:4},e.createElement(u,{width:21},e.createElement(i,{color:s.textMuted},"\xBB Cached:")),e.createElement(i,{color:s.text},Ft(ko))),Vn>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Output Tokens:")),e.createElement(i,{color:s.text},Ft(Vn)))),Sn?.tokens>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Active Context:")),e.createElement(i,{color:s.text},Ft(Sn.tokens)," ",(()=>{let he={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[re?.contextLength]||256e3,qe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1;(U==="NVIDIA"&&(Ye?.includes("gpt")||Ye?.includes("qwen")||Ye?.includes("medium")||Ye.includes("muse"))||U==="Mistral")&&(he=126e3),U==="Google"&&Ye?.includes("gemma")&&qe&&(he=16e3);let je=Sn.tokens/he*100,N=je<60?s.text:je<80?s.warning:s.danger;return e.createElement(i,{color:N,dimColor:!0},"(",je.toFixed(0),"%)")})())),Yr>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Images Made:")),e.createElement(i,{color:s.text},Yr)),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Image Credits:")),e.createElement(i,{color:s.text},Number(((zi||0)*1e3).toFixed(0))," credits"))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Code Changes (Sess):")),e.createElement(i,{color:s.text},e.createElement(i,{color:s.success||"green"},"+",It.linesAdded)," ",e.createElement(i,{color:s.danger||"red"},"-",It.linesRemoved))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Tool Calls (Sess):")),e.createElement(i,{color:s.text},It.toolSuccess+It.toolFailure+It.toolDenied," ( "),e.createElement(i,{color:s.success||"green"},"\u2714 ",It.toolSuccess),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.warning||"yellow"},"\u{1F6C7} ",It.toolDenied),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.danger||"red"},"\u2718 ",It.toolFailure),e.createElement(i,{color:s.text}," )"))),e.createElement(u,{flexDirection:"column",marginTop:1},e.createElement(i,{color:s.text,bold:!0,underline:!0},x),e.createElement(u,{marginTop:1},e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},g)),e.createElement(i,{color:s.text},sl(h?.duration||0))),(h?.agent||0)>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Model Requests:")),e.createElement(i,{color:s.text},h?.agent||0)),(h?.background||0)>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Memory Agent:")),e.createElement(i,{color:s.text},h?.background||0)),(h?.tokens||0)>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},b)),e.createElement(i,{color:s.text},Ft(h?.tokens||0))),(h?.cost||0)>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Cost Estimate:")),e.createElement(i,{color:s.success||"green"},J(h.cost))),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Input Tokens:")),e.createElement(i,{color:s.text},Ft((h?.tokens||0)-(h?.candidateTokens||0)))),(h?.cachedTokens||0)>0&&e.createElement(u,{marginLeft:4},e.createElement(u,{width:21},e.createElement(i,{color:s.textMuted},"\xBB Cached:")),e.createElement(i,{color:s.text},Ft(h.cachedTokens))),(h?.candidateTokens||0)>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Output Tokens:")),e.createElement(i,{color:s.text},Ft(h.candidateTokens)))),(h?.imageCalls?.length||0)>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},B)),e.createElement(i,{color:s.text},h.imageCalls.length)),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},v)),e.createElement(i,{color:s.text},Number(((h.imageCalls.reduce((se,he)=>se+he.cost,0)||0)*1e3).toFixed(0))," credits"))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},G)),e.createElement(i,{color:s.text},e.createElement(i,{color:s.success||"green"},"+",h?.linesAdded||0)," ",e.createElement(i,{color:s.danger||"red"},"-",h?.linesRemoved||0))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},ee)),e.createElement(i,{color:s.text},(h?.toolSuccess||0)+(h?.toolFailure||0)+(h?.toolDenied||0)," ( "),e.createElement(i,{color:s.success||"green"},"\u2714 ",h?.toolSuccess||0),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.warning||"yellow"},"\u{1F6C7} ",h?.toolDenied||0),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.danger||"red"},"\u2718 ",h?.toolFailure||0),e.createElement(i,{color:s.text}," )")))),e.createElement(i,{color:s.textMuted,dimColor:!0,italic:!0},`
317
+ \u2800\u2800`,isMeta:!0}]))}if(x){let B=x(n==="quotas"||n==="providerBudgets"?g:o);fo(B)}else c?(zt({...b,apiTier:ot,quotas:g,imageSettings:b.imageSettings||qo}),fo(null),c(g)):(zt({...b,apiTier:ot,quotas:g,imageSettings:b.imageSettings||qo}),fo(null),le($o?.returnView||"settings"))}})),e.createElement(u,{paddingX:1,marginTop:1},e.createElement(i,{color:s.textMuted,dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":{let o=Yn==="modelBreakdown"||Yn==="dailyModelBreakdown",n=Yn==="daily"||Yn==="dailyModelBreakdown",h=n?jn:ur,x=n?"TODAY's USAGE":"LAST 30 DAYS USAGE",c=n?"TODAY'S MODEL TOKEN BREAKDOWN":"30-DAY MODEL TOKEN BREAKDOWN",g="Wall Time:",b="Tokens Used:",B="Images Made:",v="Image Credits:",G="Code Changes:",ee="Tool Calls:",z=Math.max(4,(r?.rows||_?.rows||24)-15),V=(se,he,qe,je,N,pe=0,Ce=!1)=>{let ve=r?.columns||_?.columns||80,et=Math.min(125,ve-2),Ke=Math.max(20,et-6),St=Math.max(5,Ke-pe-qe.length-5),bt=he;bt.length>St&&(bt=bt.substring(0,St-1)+"\u2026");let Q=Math.max(2,Ke-pe-bt.length-qe.length-2),me=" "+".".repeat(Q)+" ",Ie=" ".repeat(pe);return e.createElement(u,{key:se,width:Ke},e.createElement(i,{wrap:"truncate"},e.createElement(i,null,Ie),e.createElement(i,{color:je,bold:Ce},bt),e.createElement(i,{color:s.textMuted,dimColor:!0},me),e.createElement(i,{color:N,bold:Ce},qe)))},q=se=>{let he=Number(se)||0;return he<=0?"":he<.001?" [<$0.001]":` [$${he.toFixed(he<.01?4:3)}]`},J=se=>{let he=Number(se)||0;return he<=0?"":he<.001?"<$0.001":`$${he.toFixed(he<.01?4:3)}`},$e=[],_e=h?.models;if(!_e||Object.keys(_e).length===0)$e.push(e.createElement(u,{key:"empty",marginTop:1},e.createElement(i,{color:s.textMuted,italic:!0},"No model token usage recorded for ",n?"today":"the last 30 days",".")));else{let se=(fr||"").trim(),he="",qe="";if(se.includes(":")){let N=se.indexOf(":");he=se.substring(0,N).trim().toLowerCase(),qe=se.substring(N+1).trim().toLowerCase()}else he=se.toLowerCase();let je=Object.entries(_e).sort(([N],[pe])=>N.localeCompare(pe,void 0,{sensitivity:"base"})).filter(([N,pe])=>he&&!N.toLowerCase().includes(he)?!1:qe?Object.keys(pe).some(Ce=>Ce.toLowerCase().includes(qe)):!0);je.length===0?$e.push(e.createElement(u,{key:"no-matches",marginTop:1},e.createElement(i,{color:s.textMuted,italic:!0},'No results found matching "',fr,'".'))):je.forEach(([N,pe],Ce)=>{let ve=Object.entries(pe).sort(([Q],[me])=>Q.localeCompare(me,void 0,{sensitivity:"base"})).filter(([Q])=>!qe||Q.toLowerCase().includes(qe));if(ve.length===0)return;let et=ve.reduce((Q,[,me])=>Q+(me.tokens||0),0),Ke=ve.reduce((Q,[me,Ie])=>{if((Ie.cost||0)>0)return Q+Ie.cost;let Ge=Cr(N,me);if(!Ge)return Q;let Ne=(Ie.tokens||0)-(Ie.candidateTokens||0),Mt=Ie.cachedTokens||0,to=Math.max(0,Ne-Mt),Xt=Ie.candidateTokens||0,Ot=to/1e6*Ge.IN+Mt/1e6*Ge.CR+Xt/1e6*Ge.OUT;return Q+Ot},0),St=h?.providerRequests&&h.providerRequests[N]||0;Ce>0&&$e.length>0&&$e.push(e.createElement(u,{key:`space-prov-${N}`},e.createElement(i,null," ")));let bt=q(Ke);$e.push(V(`prov-${N}`,`${N}:`,`${Ft(et)} (${St})${bt}`,s.primary,s.text,0,!0)),ve.forEach(([Q,me],Ie)=>{Ie>0&&$e.push(e.createElement(u,{key:`space-mod-${N}-${Q}`},e.createElement(i,null," ")));let Ge=Cr(N,Q),Ne=(me.tokens||0)-(me.candidateTokens||0),Mt=me.cachedTokens||0,to=Math.max(0,Ne-Mt),Xt=me.candidateTokens||0,Ot=0,eo=0,Ao=0;Ge&&(Ot=to/1e6*Ge.IN,eo=Mt/1e6*Ge.CR,Ao=Xt/1e6*Ge.OUT);let _o=(me.cost||0)>0?me.cost:Ot+eo+Ao,Lo=q(_o);$e.push(V(`mod-${N}-${Q}`,`\xBB ${Q}:`,`${Ft(me.tokens||0)}${Lo}`,s.secondary,s.text,2,!0));let dt=q(Ot),vt=q(eo),xt=q(Ao);$e.push(V(`in-${N}-${Q}`,"\xBB Input Tokens:",`${Ft(Ne)}${dt}`,s.textMuted,s.text,5,!1)),Mt>0&&$e.push(V(`cache-${N}-${Q}`,"\xBB Cached:",`${Ft(Mt)}${vt}`,s.textMuted,s.text,7,!1)),$e.push(V(`out-${N}-${Q}`,"\xBB Output Tokens:",`${Ft(Xt)}${xt}`,s.textMuted,s.text,5,!1))})})}let ke=$e.length,Ze=Math.max(0,ke-z);oe.current=Ze;let Wt=Math.min(vc,Ze),lt=$e.slice(Wt,Wt+z);return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,paddingX:3,paddingY:1,paddingBottom:0,width:Math.min(125,(r?.columns||100)-2)},o?e.createElement(u,{flexDirection:"column"},e.createElement(u,{justifyContent:"space-between"},e.createElement(i,{color:s.text,bold:!0,underline:!0},c),ke>z&&e.createElement(i,{color:s.textMuted,dimColor:!0},"[",Wt+1,"-",Math.min(ke,Wt+z)," of ",ke,"] \u25B2\u25BC")),e.createElement(u,{marginTop:1},e.createElement(i,{color:s.secondary,bold:!0},"Filter (provider:model): "),e.createElement(i,{color:s.text},fr),e.createElement(i,{color:s.primary,bold:!0},"\u258A"),fr.length>0&&e.createElement(i,{color:s.textMuted,dimColor:!0,italic:!0}," (Type to search, Esc/Backspace to clear)")),e.createElement(u,{flexDirection:"column",height:z,marginTop:1},lt)):e.createElement(e.Fragment,null,e.createElement(u,{marginBottom:1},e.createElement(i,{color:s.text,bold:!0,underline:!0},"SESSION TELEMETRY")),e.createElement(u,{flexDirection:"column"},e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Session Duration:")),e.createElement(i,{color:s.text},kn(Date.now()-$i))),Gi>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Model Requests:")),e.createElement(i,{color:s.text},Gi)),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB API Time:")),e.createElement(i,{color:s.text},kn(Vr))),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Tool Time:")),e.createElement(i,{color:s.text},kn(jr)))),Vi>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Memory Agent:")),e.createElement(i,{color:s.text},Vi)),xo>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Tokens Consumed:")),e.createElement(i,{color:s.text},Ft(xo))),(It?.cost||0)>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Cost Estimate:")),e.createElement(i,{color:s.success||"green"},J(It.cost))),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Input Tokens:")),e.createElement(i,{color:s.text},Ft(xo-Vn))),ko>0&&e.createElement(u,{marginLeft:4},e.createElement(u,{width:21},e.createElement(i,{color:s.textMuted},"\xBB Cached:")),e.createElement(i,{color:s.text},Ft(ko))),Vn>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Output Tokens:")),e.createElement(i,{color:s.text},Ft(Vn)))),Sn?.tokens>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Active Context:")),e.createElement(i,{color:s.text},Ft(Sn.tokens)," ",(()=>{let he={"16k":16e3,"32k":32e3,"64k":64e3,"128k":128e3,"256k":256e3,"512k":512e3,"1M":1e6}[re?.contextLength]||256e3,qe=process.env.GOOGLE_GEMMA_NONSENSE==="true"||process.env.GOOGLE_GEMMA_NONSENSE===!0||!1;(U==="NVIDIA"&&(Ye?.includes("gpt")||Ye?.includes("qwen")||Ye?.includes("medium")||Ye.includes("muse"))||U==="Mistral")&&(he=126e3),U==="Google"&&Ye?.includes("gemma")&&qe&&(he=16e3);let je=Sn.tokens/he*100,N=je<60?s.text:je<80?s.warning:s.danger;return e.createElement(i,{color:N,dimColor:!0},"(",je.toFixed(0),"%)")})())),Yr>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Images Made:")),e.createElement(i,{color:s.text},Yr)),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Image Credits:")),e.createElement(i,{color:s.text},Number(((zi||0)*1e3).toFixed(0))," credits"))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Code Changes (Sess):")),e.createElement(i,{color:s.text},e.createElement(i,{color:s.success||"green"},"+",It.linesAdded)," ",e.createElement(i,{color:s.danger||"red"},"-",It.linesRemoved))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Tool Calls (Sess):")),e.createElement(i,{color:s.text},It.toolSuccess+It.toolFailure+It.toolDenied," ( "),e.createElement(i,{color:s.success||"green"},"\u2714 ",It.toolSuccess),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.warning||"yellow"},"\u{1F6C7} ",It.toolDenied),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.danger||"red"},"\u2718 ",It.toolFailure),e.createElement(i,{color:s.text}," )"))),e.createElement(u,{flexDirection:"column",marginTop:1},e.createElement(i,{color:s.text,bold:!0,underline:!0},x),e.createElement(u,{marginTop:1},e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},g)),e.createElement(i,{color:s.text},sl(h?.duration||0))),(h?.agent||0)>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Model Requests:")),e.createElement(i,{color:s.text},h?.agent||0)),(h?.background||0)>0&&e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},"Memory Agent:")),e.createElement(i,{color:s.text},h?.background||0)),(h?.tokens||0)>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},b)),e.createElement(i,{color:s.text},Ft(h?.tokens||0))),(h?.cost||0)>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Cost Estimate:")),e.createElement(i,{color:s.success||"green"},J(h.cost))),e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Input Tokens:")),e.createElement(i,{color:s.text},Ft((h?.tokens||0)-(h?.candidateTokens||0)))),(h?.cachedTokens||0)>0&&e.createElement(u,{marginLeft:4},e.createElement(u,{width:21},e.createElement(i,{color:s.textMuted},"\xBB Cached:")),e.createElement(i,{color:s.text},Ft(h.cachedTokens))),(h?.candidateTokens||0)>0&&e.createElement(u,{marginLeft:2},e.createElement(u,{width:23},e.createElement(i,{color:s.textMuted},"\xBB Output Tokens:")),e.createElement(i,{color:s.text},Ft(h.candidateTokens)))),(h?.imageCalls?.length||0)>0&&e.createElement(e.Fragment,null,e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},B)),e.createElement(i,{color:s.text},h.imageCalls.length)),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},v)),e.createElement(i,{color:s.text},Number(((h.imageCalls.reduce((se,he)=>se+he.cost,0)||0)*1e3).toFixed(0))," credits"))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},G)),e.createElement(i,{color:s.text},e.createElement(i,{color:s.success||"green"},"+",h?.linesAdded||0)," ",e.createElement(i,{color:s.danger||"red"},"-",h?.linesRemoved||0))),e.createElement(u,null,e.createElement(u,{width:25},e.createElement(i,{color:s.secondary},ee)),e.createElement(i,{color:s.text},(h?.toolSuccess||0)+(h?.toolFailure||0)+(h?.toolDenied||0)," ( "),e.createElement(i,{color:s.success||"green"},"\u2714 ",h?.toolSuccess||0),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.warning||"yellow"},"\u{1F6C7} ",h?.toolDenied||0),e.createElement(i,{color:s.text}," "),e.createElement(i,{color:s.danger||"red"},"\u2718 ",h?.toolFailure||0),e.createElement(i,{color:s.text}," )")))),e.createElement(i,{color:s.textMuted,dimColor:!0,italic:!0},`
318
318
  `,"(Press TAB to toggle Today/30-Day views, SPACE to toggle Model Breakdown, ESC to return)"))}case"dynamicDirDanger":return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,paddingX:2,paddingY:1,width:"100%"},e.createElement(i,{color:s.warning||"yellow",bold:!0,underline:!0},"DYNAMIC DIRECTORY AWARENESS"),e.createElement(i,{marginTop:1,color:s.text},"Enabling this keeps the agent aware of filesystem state in real time, but may reduce prompt cache efficiency."),e.createElement(i,{color:s.text},`
319
319
  `,"RECOMMENDED SCENARIOS TO TURN ON:"),e.createElement(i,{color:s.textMuted},"\u2022 Repo is small."),e.createElement(i,{color:s.textMuted},"\u2022 The task benefits from real-time filesystem awareness."),e.createElement(i,{color:s.textMuted},"\u2022 Files are often created, renamed, or deleted."),e.createElement(i,{color:s.textMuted},"\u2022 You know exactly what you're signing up for."),e.createElement(i,{color:s.textMuted},"\u2022 You don't have conflicting decisions regarding token bills."),e.createElement(i,{color:s.textMuted},"\u2022 You want to see your wallet crying at 3am."),e.createElement(u,{marginTop:1},e.createElement(Ht,{title:"Confirm Intent",theme:re.theme,items:[{label:"Turn On Dynamic Directory Awareness",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:o=>{o.value==="on"&&_t(n=>{let h={...n,dynamicDirAwareness:!0};return zt({systemSettings:h,apiTier:ot,quotas:De}),h}),le("settings")}})));case"dynamicDirHelp":return e.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:s.borderMuted,paddingX:2,paddingY:1,width:"100%"},e.createElement(i,{color:s.text,bold:!0,underline:!0},"DYNAMIC DIRECTORY AWARENESS \u2014 HELP & EXPLANATION"),e.createElement(i,{color:s.text,bold:!0},`
320
320
  `,"OFF (Default):"),e.createElement(i,{color:s.textMuted},"\u2022 Takes a static directory snapshot at conversation/session start and places it in System Context."),e.createElement(i,{color:s.textMuted},"\u2022 Prompt cache remains stable across user turns, saving tokens and money."),e.createElement(i,{color:s.text,bold:!0},`