fluxflow-cli 2.3.1 → 2.4.1

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 (3) hide show
  1. package/README.md +1 -7
  2. package/dist/fluxflow.js +229 -229
  3. package/package.json +2 -2
package/dist/fluxflow.js CHANGED
@@ -1,60 +1,60 @@
1
1
  #!/usr/bin/env node
2
- var fc=Object.defineProperty;var re=(e,o)=>()=>(e&&(o=e(e=0)),o);var qr=(e,o)=>{for(var t in o)fc(e,t,{get:o[t],enumerable:!0})};var na={};qr(na,{BACKUPS_DIR:()=>wn,DATA_DIR:()=>Er,FLUXFLOW_DIR:()=>Un,HISTORY_FILE:()=>Rn,LEDGER_FILE:()=>nn,LOGS_DIR:()=>Io,MEMORIES_FILE:()=>Nt,PARSER_DIR:()=>Tn,PATHS_FILE:()=>Vr,SECRET_DIR:()=>ro,SETTINGS_FILE:()=>no,TEMP_MEM_CHAT_FILE:()=>Go,TEMP_MEM_FILE:()=>Eo,USAGE_FILE:()=>Ht});import pc from"os";import So from"path";import ea from"fs";import ta from"crypto";var Un,no,oa,Er,Io,ro,Rn,Ht,Nt,Eo,Go,wn,nn,Vr,Tn,Bt=re(()=>{Un=So.join(pc.homedir(),".fluxflow"),no=So.join(Un,"settings.json"),oa=null;try{if(ea.existsSync(no)){let e=ea.readFileSync(no,"utf8").trim(),o;if(e.startsWith("{"))o=JSON.parse(e);else{let t=e.split(":");if(t.length===2){let n=Buffer.from(t[0],"hex"),s=t[1],r=ta.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),l=ta.createDecipheriv("aes-256-cbc",r,n),u=l.update(s,"hex","utf8");u+=l.final("utf8"),o=JSON.parse(u)}}if(o){let t=o.systemSettings||{};t.useExternalData&&t.externalDataPath&&(oa=t.externalDataPath)}}}catch{}Er=oa||Un,Io=So.join(Er,"logs"),ro=So.join(Er,"secret"),Rn=So.join(ro,"history.json"),Ht=So.join(Un,"usage.json"),Nt=So.join(ro,"memories.json"),Eo=So.join(ro,"memory-temp.json"),Go=So.join(ro,"temp-memory-chat.json"),wn=So.join(Er,"backups"),nn=So.join(ro,"ledger.json"),Vr=So.join(ro,"path.json"),Tn=So.join(Er,"parsers")});import br from"fs";import Ps from"path";import zr from"crypto";var hc,gc,ra,sa,Cr,Sn,xe,ke,Jr,Qr,Lo=re(()=>{hc=66,gc=e=>{let o=Buffer.isBuffer(e)?e:Buffer.from(e),t=Buffer.alloc(o.length);for(let n=0;n<o.length;n++)t[n]=o[n]^hc;return t},ra="aes-256-cbc",sa=zr.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),Cr=e=>{let o=zr.randomBytes(16),t=zr.createCipheriv(ra,sa,o),n=t.update(e,"utf8","hex");return n+=t.final("hex"),o.toString("hex")+":"+n},Sn=e=>{let o=e.split(":");if(o.length!==2)throw new Error("Invalid AES format");let t=Buffer.from(o[0],"hex"),n=o[1],s=zr.createDecipheriv(ra,sa,t),r=s.update(n,"hex","utf8");return r+=s.final("utf8"),r},xe=(e,o={})=>{try{if(!br.existsSync(e))return o;let t=br.readFileSync(e),n=t.toString("utf8").trim();if(n.startsWith("{")||n.startsWith("["))return JSON.parse(n);try{let r=Sn(n);return JSON.parse(r)}catch{}let s=gc(t).toString("utf8");if(s.startsWith("{")||s.startsWith("["))return JSON.parse(s);throw new Error("Unsupported or corrupt encryption format")}catch(t){return console.error(`Vault Read Error [${Ps.basename(e)}]:`,t.message),o}},ke=(e,o)=>{try{let t=Ps.dirname(e);br.existsSync(t)||br.mkdirSync(t,{recursive:!0});let n=JSON.stringify(o,null,2),s=Cr(n);br.writeFileSync(e,s,"utf8")}catch(t){console.error(`Vault Write Error [${Ps.basename(e)}]:`,t.message)}},Jr=xe,Qr=ke});var ts={};qr(ts,{getAPIKey:()=>wc,getProviderAPIKey:()=>Zr,getSearchSecrets:()=>Sc,getSecret:()=>Tc,removeAPIKey:()=>_s,removeSecret:()=>ia,saveAPIKey:()=>Ec,saveProviderAPIKey:()=>es,saveSearchId:()=>Cc,saveSearchKey:()=>bc,saveSecret:()=>En});import xc from"fs-extra";import yc from"path";var bn,wc,Zr,es,Tc,En,Sc,Ec,bc,Cc,ia,_s,kr=re(()=>{Lo();Bt();bn=yc.join(ro,"secrets.json"),wc=async()=>{try{let e=xe(bn,{});if(e.API_KEY)return e.API_KEY}catch{}return null},Zr=async e=>{try{let o=xe(bn,{});if(e==="Google")return o.GOOGLE_API_KEY||o.API_KEY||null;if(e==="DeepSeek")return o.DEEPSEEK_API_KEY||null;if(e==="OpenRouter")return o.OPENROUTER_API_KEY||null}catch{}return null},es=async(e,o)=>{e==="Google"?(await En("GOOGLE_API_KEY",o),await En("API_KEY",o)):e==="DeepSeek"?await En("DEEPSEEK_API_KEY",o):e==="OpenRouter"&&await En("OPENROUTER_API_KEY",o)},Tc=async e=>{try{return xe(bn,{})[e]||null}catch{return null}},En=async(e,o)=>{await xc.ensureDir(ro);let t=xe(bn,{});t[e]=o,ke(bn,t)},Sc=async()=>{try{let e=xe(bn,{});return{key:e.GOOGLE_API_KEY||e.API_KEY,cx:e.SEARCH_ID}}catch{}return{key:null,cx:null}},Ec=async e=>En("API_KEY",e),bc=async e=>En("GOOGLE_API_KEY",e),Cc=async e=>En("SEARCH_ID",e),ia=async e=>{try{let o=xe(bn,{});delete o[e],ke(bn,o)}catch{}},_s=async()=>ia("API_KEY")});var aa={};qr(aa,{loadSettings:()=>or,saveSettings:()=>Cn});import Ir from"fs-extra";import Ns from"path";var tr,or,kc,Cn,os=re(()=>{Bt();Lo();tr={mode:"Flux",thinkingLevel:"Medium",aiProvider:"Google",activeModel:"gemma-4-31b-it",showFullThinking:!0,apiTier:"Free",quotas:{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0},systemSettings:{memory:!0,compression:0,autoExec:!1,allowExternalAccess:!1,autoDeleteHistory:"7d",useExternalData:!1,externalDataPath:""},profileData:{name:null,nickname:null,instructions:null},imageSettings:{keyType:"Default",quality:"Low-High",apiKey:""}},or=async()=>{let e={...tr};try{if(await Ir.exists(no)){let o=Jr(no);if(o.imageSettings&&o.imageSettings.apiKey)try{let t=o.imageSettings.apiKey,{saveSecret:n}=await Promise.resolve().then(()=>(kr(),ts));await n("POLLINATIONS_API_KEY",t),o.imageSettings.apiKey="",Qr(no,o)}catch{}e={...tr,...o,quotas:{...tr.quotas,...o.quotas},systemSettings:{...tr.systemSettings,...o.systemSettings},profileData:{...tr.profileData,...o.profileData},imageSettings:{...tr.imageSettings,...o.imageSettings}}}}catch(o){console.error("Failed to load settings:",o)}try{let{getSecret:o}=await Promise.resolve().then(()=>(kr(),ts)),t=await o("POLLINATIONS_API_KEY");t&&(e.imageSettings.apiKey=t)}catch{}if(e.showFullThinking===!1){e.showFullThinking=!0;try{Qr(no,e)}catch{}}return e},kc=async e=>{let{FLUXFLOW_DIR:o}=await Promise.resolve().then(()=>(Bt(),na)),t=["logs","secret"];for(let n of t){let s=Ns.join(o,n),r=Ns.join(e,n);try{await Ir.exists(s)&&(await Ir.ensureDir(r),await Ir.copy(s,r,{overwrite:!0}))}catch(l){console.error(`Migration failed for ${n}:`,l)}}},Cn=async e=>{try{let o=await or();if(!o.systemSettings.useExternalData&&e.systemSettings?.useExternalData&&e.systemSettings?.externalDataPath&&await kc(e.systemSettings.externalDataPath),e.imageSettings&&e.imageSettings.apiKey!==void 0){let{saveSecret:n,removeSecret:s}=await Promise.resolve().then(()=>(kr(),ts)),r=e.imageSettings.apiKey;r?await n("POLLINATIONS_API_KEY",r):await s("POLLINATIONS_API_KEY")}let t={...o,...e};return t.imageSettings&&(t.imageSettings={...t.imageSettings,apiKey:""}),await Ir.ensureDir(Ns.dirname(no)),Qr(no,t),!0}catch(o){return console.error("Failed to save settings:",o),!1}}});import mo,{useState as Ar,useEffect as Rs,useMemo as Bs,useCallback as ns,useRef as la}from"react";import{Box as vr,Spacer as Ic,Text as Mr,useInput as Mc,measureElement as vc}from"ink";function Ac(e,o){return e.replace(/\t/g," ".repeat(o))}function Us(e){return e==null?"":e.replace(/\r\n/g,`
2
+ var pc=Object.defineProperty;var re=(e,o)=>()=>(e&&(o=e(e=0)),o);var Xr=(e,o)=>{for(var t in o)pc(e,t,{get:o[t],enumerable:!0})};var sa={};Xr(sa,{BACKUPS_DIR:()=>hn,DATA_DIR:()=>Er,FLUXFLOW_DIR:()=>Bn,HISTORY_FILE:()=>Un,LEDGER_FILE:()=>on,LOGS_DIR:()=>ko,MEMORIES_FILE:()=>Wt,PARSER_DIR:()=>gn,PATHS_FILE:()=>Kr,SECRET_DIR:()=>ro,SETTINGS_FILE:()=>no,TEMP_MEM_CHAT_FILE:()=>Yo,TEMP_MEM_FILE:()=>To,USAGE_FILE:()=>Vt});import hc from"os";import wo from"path";import oa from"fs";import na from"crypto";var Bn,no,ra,Er,ko,ro,Un,Vt,Wt,To,Yo,hn,on,Kr,gn,Yt=re(()=>{Bn=wo.join(hc.homedir(),".fluxflow"),no=wo.join(Bn,"settings.json"),ra=null;try{if(oa.existsSync(no)){let e=oa.readFileSync(no,"utf8").trim(),o;if(e.startsWith("{"))o=JSON.parse(e);else{let t=e.split(":");if(t.length===2){let n=Buffer.from(t[0],"hex"),s=t[1],r=na.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),l=na.createDecipheriv("aes-256-cbc",r,n),u=l.update(s,"hex","utf8");u+=l.final("utf8"),o=JSON.parse(u)}}if(o){let t=o.systemSettings||{};t.useExternalData&&t.externalDataPath&&(ra=t.externalDataPath)}}}catch{}Er=ra||Bn,ko=wo.join(Er,"logs"),ro=wo.join(Er,"secret"),Un=wo.join(ro,"history.json"),Vt=wo.join(Bn,"usage.json"),Wt=wo.join(ro,"memories.json"),To=wo.join(ro,"memory-temp.json"),Yo=wo.join(ro,"temp-memory-chat.json"),hn=wo.join(Er,"backups"),on=wo.join(ro,"ledger.json"),Kr=wo.join(ro,"path.json"),gn=wo.join(Er,"parsers")});import br from"fs";import $s from"path";import Vr from"crypto";var gc,xc,ia,aa,Cr,xn,Te,De,qr,zr,Lo=re(()=>{gc=66,xc=e=>{let o=Buffer.isBuffer(e)?e:Buffer.from(e),t=Buffer.alloc(o.length);for(let n=0;n<o.length;n++)t[n]=o[n]^gc;return t},ia="aes-256-cbc",aa=Vr.createHash("sha256").update("fluxflow-cli-sanctuary-key").digest(),Cr=e=>{let o=Vr.randomBytes(16),t=Vr.createCipheriv(ia,aa,o),n=t.update(e,"utf8","hex");return n+=t.final("hex"),o.toString("hex")+":"+n},xn=e=>{let o=e.split(":");if(o.length!==2)throw new Error("Invalid AES format");let t=Buffer.from(o[0],"hex"),n=o[1],s=Vr.createDecipheriv(ia,aa,t),r=s.update(n,"hex","utf8");return r+=s.final("utf8"),r},Te=(e,o={})=>{try{if(!br.existsSync(e))return o;let t=br.readFileSync(e),n=t.toString("utf8").trim();if(n.startsWith("{")||n.startsWith("["))return JSON.parse(n);try{let r=xn(n);return JSON.parse(r)}catch{}let s=xc(t).toString("utf8");if(s.startsWith("{")||s.startsWith("["))return JSON.parse(s);throw new Error("Unsupported or corrupt encryption format")}catch(t){return console.error(`Vault Read Error [${$s.basename(e)}]:`,t.message),o}},De=(e,o)=>{try{let t=$s.dirname(e);br.existsSync(t)||br.mkdirSync(t,{recursive:!0});let n=JSON.stringify(o,null,2),s=Cr(n);br.writeFileSync(e,s,"utf8")}catch(t){console.error(`Vault Write Error [${$s.basename(e)}]:`,t.message)}},qr=Te,zr=De});var Zr={};Xr(Zr,{getAPIKey:()=>Tc,getProviderAPIKey:()=>Jr,getSearchSecrets:()=>Ec,getSecret:()=>Sc,removeAPIKey:()=>Ps,removeSecret:()=>la,saveAPIKey:()=>bc,saveProviderAPIKey:()=>Qr,saveSearchId:()=>kc,saveSearchKey:()=>Cc,saveSecret:()=>nn});import yc from"fs-extra";import wc from"path";var yn,Tc,Jr,Qr,Sc,nn,Ec,bc,Cc,kc,la,Ps,kr=re(()=>{Lo();Yt();yn=wc.join(ro,"secrets.json"),Tc=async()=>{try{let e=Te(yn,{});if(e.API_KEY)return e.API_KEY}catch{}return null},Jr=async e=>{try{let o=Te(yn,{});if(e==="Google")return o.GOOGLE_API_KEY||o.API_KEY||null;if(e==="DeepSeek")return o.DEEPSEEK_API_KEY||null;if(e==="OpenRouter")return o.OPENROUTER_API_KEY||null;if(e==="NVIDIA")return o.NVIDIA_API_KEY||null}catch{}return null},Qr=async(e,o)=>{e==="Google"?(await nn("GOOGLE_API_KEY",o),await nn("API_KEY",o)):e==="DeepSeek"?await nn("DEEPSEEK_API_KEY",o):e==="OpenRouter"?await nn("OPENROUTER_API_KEY",o):e==="NVIDIA"&&await nn("NVIDIA_API_KEY",o)},Sc=async e=>{try{return Te(yn,{})[e]||null}catch{return null}},nn=async(e,o)=>{await yc.ensureDir(ro);let t=Te(yn,{});t[e]=o,De(yn,t)},Ec=async()=>{try{let e=Te(yn,{});return{key:e.GOOGLE_API_KEY||e.API_KEY,cx:e.SEARCH_ID}}catch{}return{key:null,cx:null}},bc=async e=>nn("API_KEY",e),Cc=async e=>nn("GOOGLE_API_KEY",e),kc=async e=>nn("SEARCH_ID",e),la=async e=>{try{let o=Te(yn,{});delete o[e],De(yn,o)}catch{}},Ps=async()=>la("API_KEY")});var ca={};Xr(ca,{loadSettings:()=>Zn,saveSettings:()=>wn});import Ir from"fs-extra";import _s from"path";var Qn,Zn,Ic,wn,es=re(()=>{Yt();Lo();Qn={mode:"Flux",thinkingLevel:"Medium",aiProvider:"Google",activeModel:"gemma-4-31b-it",showFullThinking:!0,apiTier:"Free",quotas:{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0},systemSettings:{memory:!0,compression:0,autoExec:!1,allowExternalAccess:!1,autoDeleteHistory:"7d",useExternalData:!1,externalDataPath:""},profileData:{name:null,nickname:null,instructions:null},imageSettings:{keyType:"Default",quality:"Low-High",apiKey:""}},Zn=async()=>{let e={...Qn};try{if(await Ir.exists(no)){let o=qr(no);if(o.imageSettings&&o.imageSettings.apiKey)try{let t=o.imageSettings.apiKey,{saveSecret:n}=await Promise.resolve().then(()=>(kr(),Zr));await n("POLLINATIONS_API_KEY",t),o.imageSettings.apiKey="",zr(no,o)}catch{}e={...Qn,...o,quotas:{...Qn.quotas,...o.quotas},systemSettings:{...Qn.systemSettings,...o.systemSettings},profileData:{...Qn.profileData,...o.profileData},imageSettings:{...Qn.imageSettings,...o.imageSettings}}}}catch(o){console.error("Failed to load settings:",o)}try{let{getSecret:o}=await Promise.resolve().then(()=>(kr(),Zr)),t=await o("POLLINATIONS_API_KEY");t&&(e.imageSettings.apiKey=t)}catch{}if(e.showFullThinking===!1){e.showFullThinking=!0;try{zr(no,e)}catch{}}return e},Ic=async e=>{let{FLUXFLOW_DIR:o}=await Promise.resolve().then(()=>(Yt(),sa)),t=["logs","secret"];for(let n of t){let s=_s.join(o,n),r=_s.join(e,n);try{await Ir.exists(s)&&(await Ir.ensureDir(r),await Ir.copy(s,r,{overwrite:!0}))}catch(l){console.error(`Migration failed for ${n}:`,l)}}},wn=async e=>{try{let o=await Zn();if(!o.systemSettings.useExternalData&&e.systemSettings?.useExternalData&&e.systemSettings?.externalDataPath&&await Ic(e.systemSettings.externalDataPath),e.imageSettings&&e.imageSettings.apiKey!==void 0){let{saveSecret:n,removeSecret:s}=await Promise.resolve().then(()=>(kr(),Zr)),r=e.imageSettings.apiKey;r?await n("POLLINATIONS_API_KEY",r):await s("POLLINATIONS_API_KEY")}let t={...o,...e};return t.imageSettings&&(t.imageSettings={...t.imageSettings,apiKey:""}),await Ir.ensureDir(_s.dirname(no)),zr(no,t),!0}catch(o){return console.error("Failed to save settings:",o),!1}}});import mo,{useState as vr,useEffect as Us,useMemo as Ns,useCallback as ts,useRef as ua}from"react";import{Box as Mr,Spacer as Ac,Text as Ar,useInput as Mc,measureElement as vc}from"ink";function Dc(e,o){return e.replace(/\t/g," ".repeat(o))}function Bs(e){return e==null?"":e.replace(/\r\n/g,`
3
3
  `).replace(/\r/g,`
4
- `)}var ca,Oc,ua,da=re(()=>{ca=({children:e,onHeightChange:o})=>{let t=la(null),n=la(void 0);return Rs(()=>{if(t.current){let{height:s}=vc(t.current);n.current!==s&&(n.current=s,o?.(s))}}),mo.createElement(vr,{ref:t,flexShrink:0,flexGrow:0,width:"100%"},e)},Oc=({value:e,rows:o,maxRows:t,highlightStyle:n,textStyle:s,placeholder:r="",mask:l,showCursor:u=!0,focus:f=!0,tabSize:m=4,cursorIndex:c=0,highlight:a,refreshKey:d})=>{let[p,h]=Ar(0),[S,T]=Ar(0),[w,I]=Ar(0),L=ns((A,F=!1)=>{let Q=Us(A);if(!F&&l)return Q.replace(/[^\n]/g,l);let j=Ac(Q,m);return F?j:j.replace(/@\[(.*?)\]/g,(Z,B)=>{let z=B.indexOf("#"),mt=B.indexOf(":L"),ce=B,Le="";z!==-1?(ce=B.slice(0,z),Le=B.slice(z)):mt!==-1&&(ce=B.slice(0,mt),Le=B.slice(mt));let Je=ce.replace(/\\/g,"/"),ue=(process.cwd()||"").replace(/\\/g,"/");ue&&Je.toLowerCase().startsWith(ue.toLowerCase()+"/")?Je=Je.slice(ue.length+1):Je.startsWith("./")&&(Je=Je.slice(2));let tt=Je.split("/");return`[${tt[tt.length-1]}${Le}]`})},[m,l]),{preCursor:_,postCursor:R}=Bs(()=>{if(!e)return r&&!f?{preCursor:[{value:L(r,!0),type:"placeholder"}],postCursor:[]}:{preCursor:[{value:u&&f?" ":"",type:"cursor"}],postCursor:[]};let A=e.slice(0,c),F=e.slice(c);if(!f)return{preCursor:[{value:L(e)}],postCursor:[]};if(a&&a.end>a.start&&a.start>=0&&a.end<=e.length)return{preCursor:[{value:L(A.slice(0,a.start))},{value:L(A.slice(a.start,Math.min(a.end,c))),type:"highlight"},{value:L(A.slice(a.end))},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:L(F.slice(0,Math.max(a.start-c,0)))},{value:L(F.slice(Math.max(a.start-c,0),Math.max(a.end-c,0))),type:"highlight"},{value:L(F.slice(Math.max(a.end-c,0)))}]};{let j=L(A),Z=L(F),B=j.lastIndexOf(`
5
- `)+1,z=Z.indexOf(`
6
- `);return{preCursor:[{value:j.slice(0,B)},{value:j.slice(B),type:"highlight"},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:Z.slice(0,z),type:"highlight"},{value:Z.slice(z)}]}}},[c,u,f,e,r,l,a,L,d]),v=Bs(()=>S!==void 0?Math.max(o??t??1,Math.min(t??o??1,S)):1,[o,t,S]);Rs(()=>{if(w!==void 0&&v!==void 0){let A=w;h(F=>{let Q=F,j=F+v;if(A<=Q)return Math.max(0,A-1);if(A>j)return A-v;if(S){if(S<v)return 0;if(S<j)return S-v}return F})}},[w,v,S]);let b=ns(A=>{switch(A){case"placeholder":return{...s,dimColor:!0};case"highlight":return n??s;case"cursor":return{...s,color:u&&f?"cyan":void 0,bold:u&&f,inverse:u&&f};default:return s}},[s,n,u,f]);return mo.createElement(vr,{height:v,overflow:"hidden",flexDirection:"column",flexGrow:0,flexShrink:0},mo.createElement(vr,{flexDirection:"column"},mo.createElement(vr,{height:v,overflowY:"hidden",flexShrink:0,flexDirection:"column"},mo.createElement(vr,{marginTop:-p,flexDirection:"column"},mo.createElement(ca,{onHeightChange:T},mo.createElement(Mr,null,_?.map((A,F)=>mo.createElement(Mr,{key:F,...b(A.type)},A.value)),R?.map((A,F)=>mo.createElement(Mr,{key:F,...b(A.type)},A.value))))),mo.createElement(Ic,null)),mo.createElement(ca,{onHeightChange:I},mo.createElement(Mr,null,_?.map((A,F)=>mo.createElement(Mr,{key:F,...b(A.type)},A.value))))))},ua=({value:e,onChange:o,onSubmit:t,keyBindings:n,showCursor:s=!0,highlightPastedText:r=!1,focus:l=!0,lastFocusEventTime:u=0,columns:f=80,useCustomInput:m=(a,d)=>Mc(a,{isActive:d}),...c})=>{let[a,d]=Ar(e.length),[p,h]=Ar(0);Rs(()=>{a>e.length&&d(e.length)},[e,a]);let S=ns(I=>{let _=Us(e).split(`
7
- `),R=Math.max(20,f-10),v=0,b=0,A=0;for(let F=0;F<_.length;F++){let j=_[F].length;if(I>=A&&I<=A+j){let B=I-A;return v+=Math.floor(B/R),b=B%R,{visualLine:v,visualCol:b}}let Z=Math.max(1,Math.ceil(j/R));v+=Z,A+=j+1}return{visualLine:v,visualCol:b}},[e,f]),T=ns((I,L)=>{let R=Us(e).split(`
8
- `),v=Math.max(20,f-10),b=0,A=0;for(let F=0;F<R.length;F++){let j=R[F].length,Z=Math.max(1,Math.ceil(j/v));if(I>=b&&I<b+Z){let B=(I-b)*v,z=Math.min(L,j-B),mt=Math.max(0,z);return Math.min(A+B+mt,A+j)}b+=Z,A+=j+1}return e.length},[e,f]);m((I,L)=>{if(I==="\x1B[I"||I==="\x1B[O"||I==="[I"||I==="[O")return;let _=n?.submit??(b=>b.return&&b.ctrl),R=n?.newline??(b=>b.return);if(_(L)){t?.(e);return}else if(R(L)){let b=e.slice(0,a)+`
9
- `+e.slice(a);o(b),d(a+1),h(0);return}if(L.tab||L.shift&&L.tab||L.ctrl&&I==="c")return;let v=0;if(I.length>1&&(v=I.length),L.upArrow){if(s){let{visualLine:b,visualCol:A}=S(a);if(b>0){let F=T(b-1,A);d(F),h(0)}}}else if(L.downArrow){if(s){let{visualLine:b,visualCol:A}=S(a),F=T(b+1,A);F!==a&&(d(F),h(0))}}else if(L.leftArrow)s&&(d(Math.max(0,a-1)),h(0));else if(L.rightArrow)s&&(d(Math.min(e.length,a+1)),h(0));else if(L.return){let b=e.slice(0,a)+`
10
- `+e.slice(a);o(b),d(a+1),h(0)}else if(L.backspace||L.delete){if(a>0){let b=e.slice(0,a-1)+e.slice(a);o(b),d(a-1),h(0)}}else if(I){let b=e.slice(0,a)+I+e.slice(a);o(b),d(a+I.length),h(v)}},l);let w=Bs(()=>{if(r&&p>1)return{start:Math.max(0,a-p),end:a}},[a,p,r]);return mo.createElement(Oc,{...c,value:e,cursorIndex:a,highlight:w,showCursor:s,focus:l})}});import Dc from"os";var Ho,so,ma,rs,ss,is,Wn=re(()=>{Ho=(e,o)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,n=e.split(`
11
- `),s=[];if(o<=5)return e;let r=l=>l.replace(t,"").length;return n.forEach(l=>{if(r(l)<=o){s.push(l);return}let f=l.split(/(\s+)/),m="",c=0,a=l.match(/^(\s*)/),d=a?a[1]:"";f.forEach((p,h)=>{if(p.length===0)return;let S=r(p);if(c+S>o)if(m.trim().length>0)s.push(m.trimEnd()),m=d+p,c=r(m);else if(t.test(p))s.push(p),m=d,c=r(m);else{let T=p;for(;r(T)>o&&o>10;)s.push(T.substring(0,o)),T=T.substring(o);m=T,c=r(m)}else m+=p,c+=S}),(m.trimEnd().length>0||m===d)&&s.push(m.trimEnd())}),s.join(`
12
- `)},so=e=>{if(!e&&e!==0)return"0.0k";let o=typeof e=="string"?parseFloat(e):e;return o>=1e6?`${(o/1e6).toFixed(1)}m`:o>=1e3?`${(o/1e3).toFixed(1)}k`:o.toString()},ma=(e,o=40)=>{if(e=e.replace(Dc.homedir(),"~"),!e||e.length<=o)return e;let t=Math.floor((o-3)/2);return e.substring(0,t)+"..."+e.substring(e.length-t)},rs=e=>{let o=[],t=new Set;Object.keys(e).forEach(s=>{let r=s.match(/^(replaceContent|newContent|content_to_replace|content_to_add)(\d+)?$/);if(r){let l=r[2]?parseInt(r[2]):1;t.add(l)}});let n=Array.from(t).sort((s,r)=>s-r);for(let s of n){let r,l;if(s===1?(r=e.replaceContent1??e.content_to_replace??e.replaceContent,l=e.newContent1??e.content_to_add??e.newContent):(r=e[`replaceContent${s}`]??e[`content_to_replace${s}`],l=e[`newContent${s}`]??e[`content_to_add${s}`]),r!==void 0&&l!==void 0)o.push({replace:r,new:l});else if(r!==void 0||l!==void 0)return{error:`Mismatched replacement pair for index ${s}. Both replacement and new content must be provided.`}}return{patchPairs:o}},ss=(e,o)=>{let t=[],n=e.replace(/\r\n/g,`
4
+ `)}var da,Oc,ma,fa=re(()=>{da=({children:e,onHeightChange:o})=>{let t=ua(null),n=ua(void 0);return Us(()=>{if(t.current){let{height:s}=vc(t.current);n.current!==s&&(n.current=s,o?.(s))}}),mo.createElement(Mr,{ref:t,flexShrink:0,flexGrow:0,width:"100%"},e)},Oc=({value:e,rows:o,maxRows:t,highlightStyle:n,textStyle:s,placeholder:r="",mask:l,showCursor:u=!0,focus:f=!0,tabSize:m=4,cursorIndex:c=0,highlight:a,refreshKey:d})=>{let[p,h]=vr(0),[E,w]=vr(0),[T,I]=vr(0),O=ts((v,F=!1)=>{let V=Bs(v);if(!F&&l)return V.replace(/[^\n]/g,l);let Y=Dc(V,m);return F?Y:Y.replace(/@\[(.*?)\]/g,(Z,N)=>{let J=N.indexOf("#"),ft=N.indexOf(":L"),de=N,$e="";J!==-1?(de=N.slice(0,J),$e=N.slice(J)):ft!==-1&&(de=N.slice(0,ft),$e=N.slice(ft));let qe=de.replace(/\\/g,"/"),me=(process.cwd()||"").replace(/\\/g,"/");me&&qe.toLowerCase().startsWith(me.toLowerCase()+"/")?qe=qe.slice(me.length+1):qe.startsWith("./")&&(qe=qe.slice(2));let Ze=qe.split("/");return`[${Ze[Ze.length-1]}${$e}]`})},[m,l]),{preCursor:P,postCursor:U}=Ns(()=>{if(!e)return r&&!f?{preCursor:[{value:O(r,!0),type:"placeholder"}],postCursor:[]}:{preCursor:[{value:u&&f?" ":"",type:"cursor"}],postCursor:[]};let v=e.slice(0,c),F=e.slice(c);if(!f)return{preCursor:[{value:O(e)}],postCursor:[]};if(a&&a.end>a.start&&a.start>=0&&a.end<=e.length)return{preCursor:[{value:O(v.slice(0,a.start))},{value:O(v.slice(a.start,Math.min(a.end,c))),type:"highlight"},{value:O(v.slice(a.end))},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:O(F.slice(0,Math.max(a.start-c,0)))},{value:O(F.slice(Math.max(a.start-c,0),Math.max(a.end-c,0))),type:"highlight"},{value:O(F.slice(Math.max(a.end-c,0)))}]};{let Y=O(v),Z=O(F),N=Y.lastIndexOf(`
5
+ `)+1,J=Z.indexOf(`
6
+ `);return{preCursor:[{value:Y.slice(0,N)},{value:Y.slice(N),type:"highlight"},{value:u&&f?" ":"",type:"cursor"}],postCursor:[{value:Z.slice(0,J),type:"highlight"},{value:Z.slice(J)}]}}},[c,u,f,e,r,l,a,O,d]),A=Ns(()=>E!==void 0?Math.max(o??t??1,Math.min(t??o??1,E)):1,[o,t,E]);Us(()=>{if(T!==void 0&&A!==void 0){let v=T;h(F=>{let V=F,Y=F+A;if(v<=V)return Math.max(0,v-1);if(v>Y)return v-A;if(E){if(E<A)return 0;if(E<Y)return E-A}return F})}},[T,A,E]);let S=ts(v=>{switch(v){case"placeholder":return{...s,dimColor:!0};case"highlight":return n??s;case"cursor":return{...s,color:u&&f?"cyan":void 0,bold:u&&f,inverse:u&&f};default:return s}},[s,n,u,f]);return mo.createElement(Mr,{height:A,overflow:"hidden",flexDirection:"column",flexGrow:0,flexShrink:0},mo.createElement(Mr,{flexDirection:"column"},mo.createElement(Mr,{height:A,overflowY:"hidden",flexShrink:0,flexDirection:"column"},mo.createElement(Mr,{marginTop:-p,flexDirection:"column"},mo.createElement(da,{onHeightChange:w},mo.createElement(Ar,null,P?.map((v,F)=>mo.createElement(Ar,{key:F,...S(v.type)},v.value)),U?.map((v,F)=>mo.createElement(Ar,{key:F,...S(v.type)},v.value))))),mo.createElement(Ac,null)),mo.createElement(da,{onHeightChange:I},mo.createElement(Ar,null,P?.map((v,F)=>mo.createElement(Ar,{key:F,...S(v.type)},v.value))))))},ma=({value:e,onChange:o,onSubmit:t,keyBindings:n,showCursor:s=!0,highlightPastedText:r=!1,focus:l=!0,lastFocusEventTime:u=0,columns:f=80,useCustomInput:m=(a,d)=>Mc(a,{isActive:d}),...c})=>{let[a,d]=vr(e.length),[p,h]=vr(0);Us(()=>{a>e.length&&d(e.length)},[e,a]);let E=ts(I=>{let P=Bs(e).split(`
7
+ `),U=Math.max(20,f-10),A=0,S=0,v=0;for(let F=0;F<P.length;F++){let Y=P[F].length;if(I>=v&&I<=v+Y){let N=I-v;return A+=Math.floor(N/U),S=N%U,{visualLine:A,visualCol:S}}let Z=Math.max(1,Math.ceil(Y/U));A+=Z,v+=Y+1}return{visualLine:A,visualCol:S}},[e,f]),w=ts((I,O)=>{let U=Bs(e).split(`
8
+ `),A=Math.max(20,f-10),S=0,v=0;for(let F=0;F<U.length;F++){let Y=U[F].length,Z=Math.max(1,Math.ceil(Y/A));if(I>=S&&I<S+Z){let N=(I-S)*A,J=Math.min(O,Y-N),ft=Math.max(0,J);return Math.min(v+N+ft,v+Y)}S+=Z,v+=Y+1}return e.length},[e,f]);m((I,O)=>{if(I==="\x1B[I"||I==="\x1B[O"||I==="[I"||I==="[O")return;let P=n?.submit??(S=>S.return&&S.ctrl),U=n?.newline??(S=>S.return);if(P(O)){t?.(e);return}else if(U(O)){let S=e.slice(0,a)+`
9
+ `+e.slice(a);o(S),d(a+1),h(0);return}if(O.tab||O.shift&&O.tab||O.ctrl&&I==="c")return;let A=0;if(I.length>1&&(A=I.length),O.upArrow){if(s){let{visualLine:S,visualCol:v}=E(a);if(S>0){let F=w(S-1,v);d(F),h(0)}}}else if(O.downArrow){if(s){let{visualLine:S,visualCol:v}=E(a),F=w(S+1,v);F!==a&&(d(F),h(0))}}else if(O.leftArrow)s&&(d(Math.max(0,a-1)),h(0));else if(O.rightArrow)s&&(d(Math.min(e.length,a+1)),h(0));else if(O.return){let S=e.slice(0,a)+`
10
+ `+e.slice(a);o(S),d(a+1),h(0)}else if(O.backspace||O.delete){if(a>0){let S=e.slice(0,a-1)+e.slice(a);o(S),d(a-1),h(0)}}else if(I){let S=e.slice(0,a)+I+e.slice(a);o(S),d(a+I.length),h(A)}},l);let T=Ns(()=>{if(r&&p>1)return{start:Math.max(0,a-p),end:a}},[a,p,r]);return mo.createElement(Oc,{...c,value:e,cursorIndex:a,highlight:T,showCursor:s,focus:l})}});import Lc from"os";var jo,so,pa,os,ns,rs,Rn=re(()=>{jo=(e,o)=>{if(!e)return"";let t=/\x1B\[[0-?]*[ -/]*[@-~]/g,n=e.split(`
11
+ `),s=[];if(o<=5)return e;let r=l=>l.replace(t,"").length;return n.forEach(l=>{if(r(l)<=o){s.push(l);return}let f=l.split(/(\s+)/),m="",c=0,a=l.match(/^(\s*)/),d=a?a[1]:"";f.forEach((p,h)=>{if(p.length===0)return;let E=r(p);if(c+E>o)if(m.trim().length>0)s.push(m.trimEnd()),m=d+p,c=r(m);else if(t.test(p))s.push(p),m=d,c=r(m);else{let w=p;for(;r(w)>o&&o>10;)s.push(w.substring(0,o)),w=w.substring(o);m=w,c=r(m)}else m+=p,c+=E}),(m.trimEnd().length>0||m===d)&&s.push(m.trimEnd())}),s.join(`
12
+ `)},so=e=>{if(!e&&e!==0)return"0.0k";let o=typeof e=="string"?parseFloat(e):e;return o>=1e6?`${(o/1e6).toFixed(1)}m`:o>=1e3?`${(o/1e3).toFixed(1)}k`:o.toString()},pa=(e,o=40)=>{if(e=e.replace(Lc.homedir(),"~"),!e||e.length<=o)return e;let t=Math.floor((o-3)/2);return e.substring(0,t)+"..."+e.substring(e.length-t)},os=e=>{let o=[],t=new Set;Object.keys(e).forEach(s=>{let r=s.match(/^(replaceContent|newContent|content_to_replace|content_to_add)(\d+)?$/);if(r){let l=r[2]?parseInt(r[2]):1;t.add(l)}});let n=Array.from(t).sort((s,r)=>s-r);for(let s of n){let r,l;if(s===1?(r=e.replaceContent1??e.content_to_replace??e.replaceContent,l=e.newContent1??e.content_to_add??e.newContent):(r=e[`replaceContent${s}`]??e[`content_to_replace${s}`],l=e[`newContent${s}`]??e[`content_to_add${s}`]),r!==void 0&&l!==void 0)o.push({replace:r,new:l});else if(r!==void 0||l!==void 0)return{error:`Mismatched replacement pair for index ${s}. Both replacement and new content must be provided.`}}return{patchPairs:o}},ns=(e,o)=>{let t=[],n=e.replace(/\r\n/g,`
13
13
  `).replace(/\r/g,`
14
14
  `),s=m=>m.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
15
15
  `).replace(/\r/g,`
16
16
  `),r=m=>m.match(/^\s*/)[0],l=m=>{let c=m.split(`
17
- `).filter(d=>d.trim()!=="");if(c.length===0)return"";let a=r(c[0]);for(let d of c){let p=r(d);p.length<a.length&&(a=p)}return a},u=(m,c,a="")=>{if(!m||c===void 0)return m;let d=v=>{let b=v.split(`
18
- `).filter(Z=>Z.trim()!=="");if(b.length===0)return{char:" ",size:4};let A=b[0].match(/^\s*/)[0];if(A.includes(" "))return{char:" ",size:1};let F=b.map(Z=>Z.match(/^\s*/)[0].length).filter(Z=>Z>0);if(F.length===0)return{char:" ",size:A.length||4};let Q=(Z,B)=>B?Q(B,Z%B):Z;return{char:" ",size:F.reduce((Z,B)=>Q(Z,B))||4}},p=d(c),h=d(m),S=l(c).length,T=(a.match(/^\s*/)||[""])[0].length,I=(T+S)/p.size,L=l(m).length/h.size,_=I-L;return m.split(`
19
- `).map((v,b)=>{if(v.trim()===""&&b!==0)return"";let A=v.match(/^\s*/)[0].length/h.size,F=Math.max(0,A+_),Q=F;if(b===0){let j=T/p.size;Q=Math.max(0,F-j)}return p.char.repeat(Q*p.size)+v.trimStart()}).join(`
20
- `)},f=n;for(let m=0;m<o.length;m++){let c=o[m],a=s(c.replace||""),d=s(c.new||"");if(a===""&&d===""){t.push({success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let p=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=null;if(a!==""&&f.includes(a))h=new RegExp(p,"g");else{let j=a.split(`
21
- `).map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(j.length>0){let Z=j.join("\\s*");try{h=new RegExp(Z,"g")}catch{h=new RegExp(p,"g")}}else h=new RegExp(p,"g")}let S=[...f.matchAll(h)];if(S.length===0){t.push({success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(S.length>1){t.push({success:!1,error:`Block ${m+1}: Found ${S.length} matches (must be unique).`});continue}let T=S[0].index,w=S[0][0],I=f.lastIndexOf(`
22
- `,T)+1,L=f.substring(I,T),_=u(d,w,L),R=f.split(`
23
- `),v=f.substring(0,T).split(`
24
- `).length,b=[];for(let j=Math.max(0,v-4);j<v-1;j++)b.push({num:j+1,text:R[j]});let A=w.split(`
25
- `),F=[],Q=v+A.length-1;for(let j=Q;j<Math.min(R.length,Q+3);j++)F.push({num:j+1,text:R[j]});t.push({success:!0,oldContent:w,newContent:_,originalStartLine:v,contextBefore:b,contextAfter:F}),f=f.substring(0,T)+_+f.substring(T+w.length)}return{content:f,results:t}},is=(e,o,t,n=8)=>{if(!t||t.length===0)return"";let s=e.split(/\r?\n/),r=o.split(/\r?\n/),l=`[DIFF_START]
17
+ `).filter(d=>d.trim()!=="");if(c.length===0)return"";let a=r(c[0]);for(let d of c){let p=r(d);p.length<a.length&&(a=p)}return a},u=(m,c,a="")=>{if(!m||c===void 0)return m;let d=A=>{let S=A.split(`
18
+ `).filter(Z=>Z.trim()!=="");if(S.length===0)return{char:" ",size:4};let v=S[0].match(/^\s*/)[0];if(v.includes(" "))return{char:" ",size:1};let F=S.map(Z=>Z.match(/^\s*/)[0].length).filter(Z=>Z>0);if(F.length===0)return{char:" ",size:v.length||4};let V=(Z,N)=>N?V(N,Z%N):Z;return{char:" ",size:F.reduce((Z,N)=>V(Z,N))||4}},p=d(c),h=d(m),E=l(c).length,w=(a.match(/^\s*/)||[""])[0].length,I=(w+E)/p.size,O=l(m).length/h.size,P=I-O;return m.split(`
19
+ `).map((A,S)=>{if(A.trim()===""&&S!==0)return"";let v=A.match(/^\s*/)[0].length/h.size,F=Math.max(0,v+P),V=F;if(S===0){let Y=w/p.size;V=Math.max(0,F-Y)}return p.char.repeat(V*p.size)+A.trimStart()}).join(`
20
+ `)},f=n;for(let m=0;m<o.length;m++){let c=o[m],a=s(c.replace||""),d=s(c.new||"");if(a===""&&d===""){t.push({success:!1,error:`Block ${m+1}: Empty replace and add content.`});continue}let p=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h=null;if(a!==""&&f.includes(a))h=new RegExp(p,"g");else{let Y=a.split(`
21
+ `).map(Z=>Z.trim()).filter(Z=>Z.length>0).map(Z=>Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s*"));if(Y.length>0){let Z=Y.join("\\s*");try{h=new RegExp(Z,"g")}catch{h=new RegExp(p,"g")}}else h=new RegExp(p,"g")}let E=[...f.matchAll(h)];if(E.length===0){t.push({success:!1,error:`Block ${m+1}: Could not find match.`});continue}if(E.length>1){t.push({success:!1,error:`Block ${m+1}: Found ${E.length} matches (must be unique).`});continue}let w=E[0].index,T=E[0][0],I=f.lastIndexOf(`
22
+ `,w)+1,O=f.substring(I,w),P=u(d,T,O),U=f.split(`
23
+ `),A=f.substring(0,w).split(`
24
+ `).length,S=[];for(let Y=Math.max(0,A-4);Y<A-1;Y++)S.push({num:Y+1,text:U[Y]});let v=T.split(`
25
+ `),F=[],V=A+v.length-1;for(let Y=V;Y<Math.min(U.length,V+3);Y++)F.push({num:Y+1,text:U[Y]});t.push({success:!0,oldContent:T,newContent:P,originalStartLine:A,contextBefore:S,contextAfter:F}),f=f.substring(0,w)+P+f.substring(w+T.length)}return{content:f,results:t}},rs=(e,o,t,n=8)=>{if(!t||t.length===0)return"";let s=e.split(/\r?\n/),r=o.split(/\r?\n/),l=`[DIFF_START]
26
26
  `,u="\u2550".repeat(88),f=0,m=null;if(t.forEach((c,a)=>{if(!c.success)return;if(m===null)for(f=Math.max(0,c.originalStartLine-4);f<c.originalStartLine-1;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
27
- `,f++;else{let T=m,w=T.originalStartLine+T.oldContent.split(`
28
- `).length-1;if(c.originalStartLine-w-1>=n){let L=Math.min(r.length,f+3);for(;f<L;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
27
+ `,f++;else{let w=m,T=w.originalStartLine+w.oldContent.split(`
28
+ `).length-1;if(c.originalStartLine-T-1>=n){let O=Math.min(r.length,f+3);for(;f<O;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
29
29
  `,f++;for(l+=`[UI_CONTEXT] ${u}
30
30
  `,f=Math.max(f,c.originalStartLine-4);f<c.originalStartLine-1;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
31
31
  `,f++}else for(;f<c.originalStartLine-1;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
32
32
  `,f++}let d=c.oldContent.split(`
33
- `);d.forEach((T,w)=>{l+=`-${c.originalStartLine+w}|${T}
34
- `});let p=c.originalStartLine+d.length-1,h=s[p]||null,S=f;if(h!==null){let T=a<t.length-1?(t[a+1].originalStartLine||r.length)+10:r.length;for(let w=f;w<T;w++){if(r[w]===h){S=w;break}w===r.length-1&&(S=r.length)}}else S=r.length;for(;f<S;)l+=`+${f+1}|${r[f]||""}
33
+ `);d.forEach((w,T)=>{l+=`-${c.originalStartLine+T}|${w}
34
+ `});let p=c.originalStartLine+d.length-1,h=s[p]||null,E=f;if(h!==null){let w=a<t.length-1?(t[a+1].originalStartLine||r.length)+10:r.length;for(let T=f;T<w;T++){if(r[T]===h){E=T;break}T===r.length-1&&(E=r.length)}}else E=r.length;for(;f<E;)l+=`+${f+1}|${r[f]||""}
35
35
  `,f++;m=c}),m!==null){let c=Math.min(r.length,f+3);for(;f<c;)l+=`[UI_CONTEXT] ${f+1} |${r[f]||""}
36
- `,f++}return l+="[DIFF_END]",l}});import Ut from"react";import{Box as kn,Text as In}from"ink";var as,Ws=re(()=>{Wn();as=Ut.memo(({command:e,output:o,completed:t=!1,isFocused:n=!1,columns:s=80,isPty:r=!1})=>{let u=(m=>{if(!m)return"";let c=[[]],a=0,d=0,p="",h=/\x1b\[([0-9;]*?)([a-zA-Z])/g,S=0,T,w=L=>{for(let _=0;_<L.length;_++){let R=L[_];if(R===`
37
- `)for(a++,d=0;a>=c.length;)c.push([]);else if(R==="\r")d=0;else{for(;a>=c.length;)c.push([]);let v=c[a];for(;d>v.length;)v.push({char:" ",style:""});v[d]={char:R,style:p},d++}}};for(;(T=h.exec(m))!==null;){w(m.substring(S,T.index));let L=T[1],_=T[2],R=L?L.split(";").map(Number):[];if(_==="A"){let v=R[0]||1;a=Math.max(0,a-v)}else if(_==="B"){let v=R[0]||1;for(a=a+v;a>=c.length;)c.push([])}else if(_==="C"){let v=R[0]||1;d=d+v}else if(_==="D"){let v=R[0]||1;d=Math.max(0,d-v)}else if(_==="G"){let v=(R[0]||1)-1;d=Math.max(0,v)}else if(_==="H"||_==="f"){let v=(R[0]||1)-1,b=(R[1]||1)-1;for(a=Math.max(0,v),d=Math.max(0,b);a>=c.length;)c.push([])}else if(_==="K"){let v=R[0]||0;if(a<c.length){let b=c[a];if(v===0)b.length=d;else if(v===1)for(let A=0;A<d&&A<b.length;A++)b[A]={char:" ",style:""};else v===2&&(b.length=0)}}else if(_==="J"){let v=R[0]||0;(v===2||v===3)&&(c.length=0,c.push([]),a=0,d=0)}else if(_==="m"){let v=T[0];v==="\x1B[0m"?p="":p=v}S=h.lastIndex}w(m.substring(S));let I=c.map(L=>{let _="",R="";for(let v=0;v<L.length;v++){let b=L[v]||{char:" ",style:""};b.style!==R&&(R&&(_+="\x1B[0m"),_+=b.style,R=b.style),_+=b.char}return R&&(_+="\x1B[0m"),_});for(;I.length>0&&I[I.length-1]==="";)I.pop();return I.join(`
36
+ `,f++}return l+="[DIFF_END]",l}});import jt from"react";import{Box as Tn,Text as Sn}from"ink";var ss,Rs=re(()=>{Rn();ss=jt.memo(({command:e,output:o,completed:t=!1,isFocused:n=!1,columns:s=80,isPty:r=!1})=>{let u=(m=>{if(!m)return"";let c=[[]],a=0,d=0,p="",h=/\x1b\[([0-9;]*?)([a-zA-Z])/g,E=0,w,T=O=>{for(let P=0;P<O.length;P++){let U=O[P];if(U===`
37
+ `)for(a++,d=0;a>=c.length;)c.push([]);else if(U==="\r")d=0;else{for(;a>=c.length;)c.push([]);let A=c[a];for(;d>A.length;)A.push({char:" ",style:""});A[d]={char:U,style:p},d++}}};for(;(w=h.exec(m))!==null;){T(m.substring(E,w.index));let O=w[1],P=w[2],U=O?O.split(";").map(Number):[];if(P==="A"){let A=U[0]||1;a=Math.max(0,a-A)}else if(P==="B"){let A=U[0]||1;for(a=a+A;a>=c.length;)c.push([])}else if(P==="C"){let A=U[0]||1;d=d+A}else if(P==="D"){let A=U[0]||1;d=Math.max(0,d-A)}else if(P==="G"){let A=(U[0]||1)-1;d=Math.max(0,A)}else if(P==="H"||P==="f"){let A=(U[0]||1)-1,S=(U[1]||1)-1;for(a=Math.max(0,A),d=Math.max(0,S);a>=c.length;)c.push([])}else if(P==="K"){let A=U[0]||0;if(a<c.length){let S=c[a];if(A===0)S.length=d;else if(A===1)for(let v=0;v<d&&v<S.length;v++)S[v]={char:" ",style:""};else A===2&&(S.length=0)}}else if(P==="J"){let A=U[0]||0;(A===2||A===3)&&(c.length=0,c.push([]),a=0,d=0)}else if(P==="m"){let A=w[0];A==="\x1B[0m"?p="":p=A}E=h.lastIndex}T(m.substring(E));let I=c.map(O=>{let P="",U="";for(let A=0;A<O.length;A++){let S=O[A]||{char:" ",style:""};S.style!==U&&(U&&(P+="\x1B[0m"),P+=S.style,U=S.style),P+=S.char}return U&&(P+="\x1B[0m"),P});for(;I.length>0&&I[I.length-1]==="";)I.pop();return I.join(`
38
38
  `)})(o).replace(/\n{3,}/g,`
39
39
 
40
- `),f=r?u:u?Ho(u,s-6):"";return Ut.createElement(kn,{flexDirection:"column",borderStyle:n?"double":"round",borderColor:t?"#334155":n?"yellow":"cyan",paddingX:2,paddingY:t?0:1,width:"100%"},Ut.createElement(kn,{marginBottom:1,justifyContent:"space-between",width:"100%"},Ut.createElement(kn,{flexShrink:1,paddingRight:2},Ut.createElement(In,null,Ut.createElement(In,{color:t?"gray":n?"yellow":"cyan",bold:!0},t?"\u{1F3C1} FINISHED:":"\u26A1 EXECUTING:"," "),Ut.createElement(In,{color:t?"gray":"white"},e))),r&&Ut.createElement(kn,{flexShrink:0,paddingX:1},Ut.createElement(In,{color:t?"gray":"magenta",bold:!0},"ADVANCE"))),f?Ut.createElement(kn,{marginTop:t?0:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},Ut.createElement(In,{color:t?"gray":void 0},f)):!t&&Ut.createElement(kn,{marginTop:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},Ut.createElement(In,{color:"gray",italic:!0},"Waiting for output...")),Ut.createElement(kn,{justifyContent:"space-between",marginTop:1},t?Ut.createElement(kn,null):Ut.createElement(In,{color:"gray",dimColor:!0,italic:!0},n?"Press TAB to unfocus, then double-press ESC to terminate.":"Double-press ESC to terminate if hanging."),Ut.createElement(In,{color:t?"#475569":n?"yellow":"cyan",bold:!0},t?"\u25CF ARCHIVED":n?"\u25B6 TERMINAL FOCUSED":"\u25CF LIVE (Press TAB to focus)")))})});var Lc,Ie,rn=re(()=>{Lc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Ie=(e=2)=>{let o=Lc();return o==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)}});import C from"react";import{Box as X,Text as oe}from"ink";var Fc,$c,Pc,_c,fa,Mn,Nc,pa,Bc,Uc,ha,ga,Ys,Rc,xa,ya=re(()=>{Ws();Wn();rn();Fc={write_file:"WriteFile",update_file:"UpdateFile",read_folder:"ReadFolder",view_file:"ViewFile",exec_command:"ExecuteCommand",web_search:"WebSearch",web_scrape:"ReadSite",search_keyword:"SearchKeyword",write_pdf:"CreatePDF",write_docx:"CreateDocument",generate_image:"GenerateImage",WriteFile:"WriteFile",PatchFile:"PatchFile",ReadFolder:"ReadFolder",ReadFile:"ReadFile",Run:"RunCommand",WebSearch:"WebSearch",WebScrape:"WebScrape",SearchKeyword:"SearchKeyword",WritePDF:"WritePDF",WriteDoc:"WriteDoc",Memory:"Memory",Chat:"Chat",GenerateImage:"GenerateImage"},$c=e=>{if(!e)return e;let o=e.replace(/<\/think>(\r?\n){2}/gi,"</think>").replace(/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|\s*turn\s*:))/gi,""),t="tool:functions.";for(;;){let s=o.toLowerCase().indexOf(t);if(s===-1)break;let r=s,l=!1,u=s-1;for(;u>=0&&/\s/.test(o[u]);)u--;u>=0&&o[u]==="["&&(r=u,l=!0);let f=0,m=!1,c=null,a=s;for(;a<o.length;){let d=o[a];if(!c&&(d==="'"||d==='"'||d==="`")?c=d:c&&d===c&&o[a-1]!=="\\"&&(c=null),c||(d==="("?(f++,m=!0):d===")"&&f--),m&&f===0&&!c){let p=a;if(l){let h=a+1;for(;h<o.length&&/\s/.test(o[h]);)h++;h<o.length&&o[h]==="]"&&(p=h)}o=o.substring(0,r)+o.substring(p+1);break}if(a++,a===o.length)return o=o.substring(0,r),o}}return o.replace(/\[TOOL RESULT\]:?\s*/gi,"").split(`
40
+ `),f=r?u:u?jo(u,s-6):"";return jt.createElement(Tn,{flexDirection:"column",borderStyle:n?"double":"round",borderColor:t?"#334155":n?"yellow":"cyan",paddingX:2,paddingY:t?0:1,width:"100%"},jt.createElement(Tn,{marginBottom:1,justifyContent:"space-between",width:"100%"},jt.createElement(Tn,{flexShrink:1,paddingRight:2},jt.createElement(Sn,null,jt.createElement(Sn,{color:t?"gray":n?"yellow":"cyan",bold:!0},t?"\u{1F3C1} FINISHED:":"\u26A1 EXECUTING:"," "),jt.createElement(Sn,{color:t?"gray":"white"},e))),r&&jt.createElement(Tn,{flexShrink:0,paddingX:1},jt.createElement(Sn,{color:t?"gray":"magenta",bold:!0},"ADVANCE"))),f?jt.createElement(Tn,{marginTop:t?0:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},jt.createElement(Sn,{color:t?"gray":void 0},f)):!t&&jt.createElement(Tn,{marginTop:1,backgroundColor:r?void 0:"#0a0a0a",paddingX:1},jt.createElement(Sn,{color:"gray",italic:!0},"Waiting for output...")),jt.createElement(Tn,{justifyContent:"space-between",marginTop:1},t?jt.createElement(Tn,null):jt.createElement(Sn,{color:"gray",dimColor:!0,italic:!0},n?"Press TAB to unfocus, then double-press ESC to terminate.":"Double-press ESC to terminate if hanging."),jt.createElement(Sn,{color:t?"#475569":n?"yellow":"cyan",bold:!0},t?"\u25CF ARCHIVED":n?"\u25B6 TERMINAL FOCUSED":"\u25CF LIVE (Press TAB to focus)")))})});var Fc,Oe,rn=re(()=>{Fc=()=>process.env.TERM_PROGRAM==="vscode"?"vscode":process.env.WT_SESSION?"wt":"default",Oe=(e=2)=>{let o=Fc();return o==="wt"?" ".repeat(Math.max(1,e-1)):" ".repeat(e)}});import b from"react";import{Box as K,Text as oe}from"ink";var $c,Pc,_c,Nc,ha,En,Bc,ga,Uc,Rc,xa,ya,Ws,Wc,wa,Ta=re(()=>{Rs();Rn();rn();$c={write_file:"WriteFile",update_file:"UpdateFile",read_folder:"ReadFolder",view_file:"ViewFile",exec_command:"ExecuteCommand",web_search:"WebSearch",web_scrape:"ReadSite",search_keyword:"SearchKeyword",write_pdf:"CreatePDF",write_docx:"CreateDocument",generate_image:"GenerateImage",WriteFile:"WriteFile",PatchFile:"PatchFile",ReadFolder:"ReadFolder",ReadFile:"ReadFile",Run:"RunCommand",WebSearch:"WebSearch",WebScrape:"WebScrape",SearchKeyword:"SearchKeyword",WritePDF:"WritePDF",WriteDoc:"WriteDoc",Memory:"Memory",Chat:"Chat",GenerateImage:"GenerateImage"},Pc=e=>{if(!e)return e;let o=e.replace(/<\/think>(\r?\n){2}/gi,"</think>").replace(/(\r?\n){2}(?=\[?(?:tool:functions|tool\.functions|\s*turn\s*:))/gi,""),t="tool:functions.";for(;;){let s=o.toLowerCase().indexOf(t);if(s===-1)break;let r=s,l=!1,u=s-1;for(;u>=0&&/\s/.test(o[u]);)u--;u>=0&&o[u]==="["&&(r=u,l=!0);let f=0,m=!1,c=null,a=s;for(;a<o.length;){let d=o[a];if(!c&&(d==="'"||d==='"'||d==="`")?c=d:c&&d===c&&o[a-1]!=="\\"&&(c=null),c||(d==="("?(f++,m=!0):d===")"&&f--),m&&f===0&&!c){let p=a;if(l){let h=a+1;for(;h<o.length&&/\s/.test(o[h]);)h++;h<o.length&&o[h]==="]"&&(p=h)}o=o.substring(0,r)+o.substring(p+1);break}if(a++,a===o.length)return o=o.substring(0,r),o}}return o.replace(/\[TOOL RESULT\]:?\s*/gi,"").split(`
41
41
  `).filter(n=>!n.trim().startsWith("SUCCESS:")&&!n.trim().startsWith("ERROR:")).join(`
42
- `).replace(/\[\s*turn\s*:\s*(continue|finish)\s*\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[\s*turn\s*:?.*?$/gi,"").replace(/\n\s*turn\s*:?.*?$/gi,"").replace(/\[\s*$/gi,"").replace(/\n\nResponded on .*/g,"").replace(/\n\n\[Prompted on: .*\]/g,"").replace(/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)/gi,"\u2192").replace(/(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)/gi,"\u2190").replace(/(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)/gi,"\u2191").replace(/(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)/gi,"\u2193").replace(/(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,"\u2194").replace(/@\[TerminalName:.*?, ProcessId:.*?\]/gi,"").replace(/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,n=>Fc[n.toLowerCase()]||n).trim()},Pc=(e,o=80)=>{if(!e)return null;let t=o-10,n=Ho(e.trim(),t);return C.createElement(X,{width:"100%"},C.createElement(oe,{italic:!0},C.createElement(Mn,{text:n,color:"gray"})))},_c=e=>e.replace(/\\multiply|\\mul|\\times/g,"\xD7").replace(/\\div/g,"\xF7").replace(/\\cdot/g,"\u22C5").replace(/\\infty/g,"\u221E").replace(/\\pm/g,"\xB1").replace(/\\leq/g,"\u2264").replace(/\\geq/g,"\u2265").replace(/\\neq/g,"\u2260").replace(/\\sqrt\s*\{([^}]+)\}/g,"\u221A($1)").replace(/\\sqrt\s*(\w+|\d+)/g,"\u221A($1)").replace(/\\alpha/g,"\u03B1").replace(/\\beta/g,"\u03B2").replace(/\\theta/g,"\u03B8").replace(/\\pi/g,"\u03C0").replace(/\\approx/g,"\u2248").replace(/\\Delta/g,"\u0394").replace(/\\sigma/g,"\u03C3").replace(/\\sum/g,"\u03A3").replace(/\\prod/g,"\u03A0").replace(/\\rightarrow|\\to/g,"\u2192").replace(/\\left\b|\\right\b/g,"").replace(/\\left\(|\\right\)/g,o=>o.includes("left")?"(":")").replace(/\\left\[|\\right\]/g,o=>o.includes("left")?"[":"]").replace(/\\\{|\\\}/g,o=>o.includes("{")?"{":"}").replace(/\\text\s*\{([^}]+)\}/g,"$1").replace(/\\text\s+(\w+)/g,"$1").replace(/\\%/g,"%"),fa=(e,o)=>{if(!e)return null;let t=e.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g,"($1/$2)");t=_c(t);let n=t.split(/(\\(?:mathbf|textbf|textit|underline|texttt)\{[^{}]*\})/g);return C.createElement(C.Fragment,{key:o},n.map((s,r)=>{if(s.startsWith("\\")){let l=s.match(/\\(\w+)\{([^{}]*)\}/);if(l){let u=l[1],f=l[2];return C.createElement(oe,{key:r,bold:u==="mathbf"||u==="textbf",italic:u==="textit",underline:u==="underline",color:u==="texttt"?"cyan":void 0},f)}}return s}))},Mn=C.memo(({text:e,color:o})=>{if(!e)return null;let t=e.split(/(```[\s\S]*?```|`[^`]+`|@\[.*?\]|\*\*.*?\*\*|\*.*?\*|\$.*?\$|\[.*?\]\s*\(.*?\)|\[.*?\]\s*\[.*?\]|https?:\/\/[^\s]+)/g);return C.createElement(oe,{color:o,wrap:"anywhere"},t.map((n,s)=>{if(!n)return null;if(n.startsWith("```")&&n.endsWith("```")){let r=n.slice(3,-3);return C.createElement(oe,{key:s,color:"cyan",backgroundColor:"#003333"}," ",r," ")}if(n.startsWith("**")&&n.endsWith("**"))return C.createElement(oe,{key:s,bold:!0,color:"white"},C.createElement(Mn,{text:n.slice(2,-2),color:"white"}));if(n.startsWith("*")&&n.endsWith("*"))return C.createElement(oe,{key:s,italic:!0,color:"gray"},C.createElement(Mn,{text:n.slice(1,-1),color:"gray"}));if(n.startsWith("`")&&n.endsWith("`")){let r=n.slice(1,-1),l=r.replace(/@\[(.*?)\]/g,(f,m)=>m.split("/").pop().split("\\").pop().replace(/:L/gi,"#L")),u=r.includes("@[");return C.createElement(oe,{key:s,color:"cyan",bold:u,backgroundColor:u?"#111124":"#003333"}," ",l," ")}if(n.startsWith("@[")&&n.endsWith("]")){let l=n.slice(2,-1).split("/").pop().split("\\").pop().replace(/:L/gi,"#L");return C.createElement(oe,{key:s,color:"cyan",bold:!0,backgroundColor:"#111124"}," ",l," ")}if(n.startsWith("$")&&n.endsWith("$")){let r=n.slice(1,-1);return C.createElement(oe,{key:s,color:"yellow"},fa(r,s))}if(n.startsWith("[")&&(n.includes("](")||n.includes("] ("))){let r=n.match(/\[(.*?)\]\s*\((.*?)\)/);if(r)return C.createElement(oe,{key:s},C.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),C.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," (",r[2],")"))}if(n.startsWith("[")&&(n.includes("][")||n.includes("] ["))){let r=n.match(/\[(.*?)\]\s*\[(.*?)\]/);if(r)return C.createElement(oe,{key:s},C.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),C.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," [",r[2],"]"))}return n.startsWith("http")?C.createElement(oe,{key:s,color:"cyan",underline:!0,italic:!0},n):fa(n,s)}))}),Nc=C.memo(({buffer:e,terminalWidth:o=80})=>{if(e.length<2)return null;let t=e.map(f=>{let m=f.split("|");return m[0]!==void 0&&m[0].trim()===""&&m.shift(),m.length>0&&m[m.length-1].trim()===""&&m.pop(),m.map(c=>c.trim())}),n=t[0],s=t.slice(2),r=Math.floor(100/n.length),l=o-8,u=Math.floor(l/n.length)-2;return C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"#454545ff",paddingX:1,marginY:0,width:"100%",flexGrow:1},C.createElement(X,{flexDirection:"row",borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:"#444",marginBottom:1,paddingBottom:0,width:"100%"},n.map((f,m)=>C.createElement(X,{key:m,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2},C.createElement(Mn,{text:Ho(f,u),color:"cyan"})))),s.map((f,m)=>C.createElement(X,{key:m,flexDirection:"row",marginBottom:m===s.length-1?0:1,width:"100%"},f.map((c,a)=>C.createElement(X,{key:a,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2,flexDirection:"column"},C.createElement(Mn,{text:Ho(c,u),color:"white"}))))))}),pa=C.memo(({text:e,color:o="white",columns:t=80})=>{if(!e)return null;let n=e.split(`
43
- `),s=[],r=[],l=[],u=f=>{r.length>0&&(s.push(C.createElement(Nc,{key:`table-${f}`,buffer:[...r],terminalWidth:t})),r=[]),l.length>0&&(s.push(C.createElement(X,{key:`quote-${f}`,borderStyle:"bold",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:"gray",paddingLeft:1,marginY:1,flexDirection:"column"},l.map((m,c)=>C.createElement(Mn,{key:c,text:m,color:"gray"})))),l=[])};return n.forEach((f,m)=>{let c=f.trim(),a=c.startsWith("|"),d=c.startsWith(">");if(a)l.length>0&&u(m),r.push(f);else if(d)r.length>0&&u(m),l.push(c.replace(/^>\s*/,""));else{if(u(m),c===""){s.push(C.createElement(X,{key:m,height:1}));return}if(c==="---"||c==="***"||c==="___"){s.push(C.createElement(X,{key:m,marginY:1,borderStyle:"single",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%",borderColor:"#333"}));return}let p=c.match(/^(#{1,6})\s+(.*)/);if(p){let I=p[1].length,L=p[2];s.push(C.createElement(X,{key:m,marginTop:1,marginBottom:1,width:"100%"},C.createElement(oe,{bold:!0,color:I===1?"cyan":I===2?"magenta":I===3?"yellow":I===4?"green":I===5?"blue":"white",underline:!0},L.toUpperCase())));return}let h=c.startsWith("* ")||c.startsWith("- "),S=/^\d+\.\s/.test(c),T=f.includes("\u2588")||f.includes("\u2554")||f.includes("\u255A")||f.includes("\u2550"),w="";if(T)w=f;else if(h||S){let I=h?" \u2022 ":c.match(/^\d+\.\s/)[0],L=" ".repeat(I.length),_=Ho(c.replace(/^[\*\-\d+\.]+\s/,""),t-(I.length+6));w=I+_.split(`
42
+ `).replace(/\[\s*turn\s*:\s*(continue|finish)\s*\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[\s*turn\s*:?.*?$/gi,"").replace(/\n\s*turn\s*:?.*?$/gi,"").replace(/\[\s*$/gi,"").replace(/\n\nResponded on .*/g,"").replace(/\n\n\[Prompted on: .*\]/g,"").replace(/(\$?\\?\/?\\rightarrow\$?|\$\\rightarrow\$)/gi,"\u2192").replace(/(\$?\\?\/?\\leftarrow\$?|\$\\leftarrow\$)/gi,"\u2190").replace(/(\$?\\?\/?\\uparrow\$?|\$\\uparrow\$)/gi,"\u2191").replace(/(\$?\\?\/?\\downarrow\$?|\$\\downarrow\$)/gi,"\u2193").replace(/(\$?\\?\/?\\leftrightarrow\$?|\$\\leftrightarrow\$)/gi,"\u2194").replace(/@\[TerminalName:.*?, ProcessId:.*?\]/gi,"").replace(/\b(write_file|update_file|read_folder|view_file|exec_command|web_search|web_scrape|search_keyword|write_pdf|write_docx|generate_image)\b/gi,n=>$c[n.toLowerCase()]||n).trim()},_c=(e,o=80)=>{if(!e)return null;let t=o-10,n=jo(e.trim(),t);return b.createElement(K,{width:"100%"},b.createElement(oe,{italic:!0},b.createElement(En,{text:n,color:"gray"})))},Nc=e=>e.replace(/\\multiply|\\mul|\\times/g,"\xD7").replace(/\\div/g,"\xF7").replace(/\\cdot/g,"\u22C5").replace(/\\infty/g,"\u221E").replace(/\\pm/g,"\xB1").replace(/\\leq/g,"\u2264").replace(/\\geq/g,"\u2265").replace(/\\neq/g,"\u2260").replace(/\\sqrt\s*\{([^}]+)\}/g,"\u221A($1)").replace(/\\sqrt\s*(\w+|\d+)/g,"\u221A($1)").replace(/\\alpha/g,"\u03B1").replace(/\\beta/g,"\u03B2").replace(/\\theta/g,"\u03B8").replace(/\\pi/g,"\u03C0").replace(/\\approx/g,"\u2248").replace(/\\Delta/g,"\u0394").replace(/\\sigma/g,"\u03C3").replace(/\\sum/g,"\u03A3").replace(/\\prod/g,"\u03A0").replace(/\\rightarrow|\\to/g,"\u2192").replace(/\\left\b|\\right\b/g,"").replace(/\\left\(|\\right\)/g,o=>o.includes("left")?"(":")").replace(/\\left\[|\\right\]/g,o=>o.includes("left")?"[":"]").replace(/\\\{|\\\}/g,o=>o.includes("{")?"{":"}").replace(/\\text\s*\{([^}]+)\}/g,"$1").replace(/\\text\s+(\w+)/g,"$1").replace(/\\%/g,"%"),ha=(e,o)=>{if(!e)return null;let t=e.replace(/\\frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g,"($1/$2)");t=Nc(t);let n=t.split(/(\\(?:mathbf|textbf|textit|underline|texttt)\{[^{}]*\})/g);return b.createElement(b.Fragment,{key:o},n.map((s,r)=>{if(s.startsWith("\\")){let l=s.match(/\\(\w+)\{([^{}]*)\}/);if(l){let u=l[1],f=l[2];return b.createElement(oe,{key:r,bold:u==="mathbf"||u==="textbf",italic:u==="textit",underline:u==="underline",color:u==="texttt"?"cyan":void 0},f)}}return s}))},En=b.memo(({text:e,color:o})=>{if(!e)return null;let t=e.split(/(```[\s\S]*?```|`[^`]+`|@\[.*?\]|\*\*.*?\*\*|\*.*?\*|\$.*?\$|\[.*?\]\s*\(.*?\)|\[.*?\]\s*\[.*?\]|https?:\/\/[^\s]+)/g);return b.createElement(oe,{color:o,wrap:"anywhere"},t.map((n,s)=>{if(!n)return null;if(n.startsWith("```")&&n.endsWith("```")){let r=n.slice(3,-3);return b.createElement(oe,{key:s,color:"cyan",backgroundColor:"#003333"}," ",r," ")}if(n.startsWith("**")&&n.endsWith("**"))return b.createElement(oe,{key:s,bold:!0,color:"white"},b.createElement(En,{text:n.slice(2,-2),color:"white"}));if(n.startsWith("*")&&n.endsWith("*"))return b.createElement(oe,{key:s,italic:!0,color:"gray"},b.createElement(En,{text:n.slice(1,-1),color:"gray"}));if(n.startsWith("`")&&n.endsWith("`")){let r=n.slice(1,-1),l=r.replace(/@\[(.*?)\]/g,(f,m)=>m.split("/").pop().split("\\").pop().replace(/:L/gi,"#L")),u=r.includes("@[");return b.createElement(oe,{key:s,color:"cyan",bold:u,backgroundColor:u?"#111124":"#003333"}," ",l," ")}if(n.startsWith("@[")&&n.endsWith("]")){let l=n.slice(2,-1).split("/").pop().split("\\").pop().replace(/:L/gi,"#L");return b.createElement(oe,{key:s,color:"cyan",bold:!0,backgroundColor:"#111124"}," ",l," ")}if(n.startsWith("$")&&n.endsWith("$")){let r=n.slice(1,-1);return b.createElement(oe,{key:s,color:"yellow"},ha(r,s))}if(n.startsWith("[")&&(n.includes("](")||n.includes("] ("))){let r=n.match(/\[(.*?)\]\s*\((.*?)\)/);if(r)return b.createElement(oe,{key:s},b.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),b.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," (",r[2],")"))}if(n.startsWith("[")&&(n.includes("][")||n.includes("] ["))){let r=n.match(/\[(.*?)\]\s*\[(.*?)\]/);if(r)return b.createElement(oe,{key:s},b.createElement(oe,{color:"cyan",underline:!0,bold:!0},r[1]),b.createElement(oe,{color:"gray",dimColor:!0,italic:!0}," [",r[2],"]"))}return n.startsWith("http")?b.createElement(oe,{key:s,color:"cyan",underline:!0,italic:!0},n):ha(n,s)}))}),Bc=b.memo(({buffer:e,terminalWidth:o=80})=>{if(e.length<2)return null;let t=e.map(f=>{let m=f.split("|");return m[0]!==void 0&&m[0].trim()===""&&m.shift(),m.length>0&&m[m.length-1].trim()===""&&m.pop(),m.map(c=>c.trim())}),n=t[0],s=t.slice(2),r=Math.floor(100/n.length),l=o-8,u=Math.floor(l/n.length)-2;return b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"#454545ff",paddingX:1,marginY:0,width:"100%",flexGrow:1},b.createElement(K,{flexDirection:"row",borderStyle:"single",borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderColor:"#444",marginBottom:1,paddingBottom:0,width:"100%"},n.map((f,m)=>b.createElement(K,{key:m,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2},b.createElement(En,{text:jo(f,u),color:"cyan"})))),s.map((f,m)=>b.createElement(K,{key:m,flexDirection:"row",marginBottom:m===s.length-1?0:1,width:"100%"},f.map((c,a)=>b.createElement(K,{key:a,flexBasis:`${r}%`,flexGrow:1,flexShrink:0,paddingRight:2,flexDirection:"column"},b.createElement(En,{text:jo(c,u),color:"white"}))))))}),ga=b.memo(({text:e,color:o="white",columns:t=80})=>{if(!e)return null;let n=e.split(`
43
+ `),s=[],r=[],l=[],u=f=>{r.length>0&&(s.push(b.createElement(Bc,{key:`table-${f}`,buffer:[...r],terminalWidth:t})),r=[]),l.length>0&&(s.push(b.createElement(K,{key:`quote-${f}`,borderStyle:"bold",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,borderColor:"gray",paddingLeft:1,marginY:1,flexDirection:"column"},l.map((m,c)=>b.createElement(En,{key:c,text:m,color:"gray"})))),l=[])};return n.forEach((f,m)=>{let c=f.trim(),a=c.startsWith("|"),d=c.startsWith(">");if(a)l.length>0&&u(m),r.push(f);else if(d)r.length>0&&u(m),l.push(c.replace(/^>\s*/,""));else{if(u(m),c===""){s.push(b.createElement(K,{key:m,height:1}));return}if(c==="---"||c==="***"||c==="___"){s.push(b.createElement(K,{key:m,marginY:1,borderStyle:"single",borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%",borderColor:"#333"}));return}let p=c.match(/^(#{1,6})\s+(.*)/);if(p){let I=p[1].length,O=p[2];s.push(b.createElement(K,{key:m,marginTop:1,marginBottom:1,width:"100%"},b.createElement(oe,{bold:!0,color:I===1?"cyan":I===2?"magenta":I===3?"yellow":I===4?"green":I===5?"blue":"white",underline:!0},O.toUpperCase())));return}let h=c.startsWith("* ")||c.startsWith("- "),E=/^\d+\.\s/.test(c),w=f.includes("\u2588")||f.includes("\u2554")||f.includes("\u255A")||f.includes("\u2550"),T="";if(w)T=f;else if(h||E){let I=h?" \u2022 ":c.match(/^\d+\.\s/)[0],O=" ".repeat(I.length),P=jo(c.replace(/^[\*\-\d+\.]+\s/,""),t-(I.length+6));T=I+P.split(`
44
44
  `).join(`
45
- `+L)}else w=Ho(c,t-4);s.push(C.createElement(X,{key:m,width:"100%"},C.createElement(Mn,{text:w,color:o})))}}),u("final"),C.createElement(X,{flexDirection:"column",width:t-2},s)}),Bc=C.memo(({line:e,columns:o=80})=>{let t=e.includes("[UI_CONTEXT]"),n=e.replace("[UI_CONTEXT]","");if(t&&n.includes("\u2550"))return C.createElement(X,{backgroundColor:"#1a1a1a",paddingX:1,width:"100%"},C.createElement(oe,{color:"gray",dimColor:!0},"\u2550".repeat(Math.max(10,o-4))));let s=n.startsWith("-"),r=n.startsWith("+"),l=n[0],u=n.substring(1),f=u.indexOf("|"),m=f!==-1?u.substring(0,f).trim():"",c=f!==-1?u.substring(f+1):u,a=s?"#3a0c0c":r?"#0c3a1a":"#1a1a1a",d=s?"#ff4d4d":r?"#4dff88":t?"gray":"white";return C.createElement(X,{backgroundColor:a,paddingX:1,width:"100%"},C.createElement(X,{width:5,flexShrink:0},C.createElement(oe,{color:s?"#cf3a3a":r?"#3acf65":"gray",dimColor:t},m)),C.createElement(X,{width:2,flexShrink:0,marginLeft:1},C.createElement(oe,{color:d,bold:!0},s?"-":r?"+":" ")),C.createElement(X,{flexGrow:1,marginLeft:1},C.createElement(oe,{color:d,dimColor:t},Ho(c,o-14))))}),Uc=C.memo(({text:e,columns:o=80})=>{let t=e.match(/\[DIFF_START\]([\s\S]*?)\[DIFF_END\]/),s=(t?t[1].trim():"").split(`
46
- `);return C.createElement(X,{flexDirection:"column",width:o-3,marginBottom:0},C.createElement(X,{flexDirection:"column",backgroundColor:"#1a1a1a",paddingY:0,width:"100%"},s.map((r,l)=>C.createElement(Bc,{key:l,line:r,columns:o-3}))))}),ha=C.memo(({text:e,columns:o=80})=>{if(!e)return null;if(e.includes("[DIFF_START]"))return C.createElement(Uc,{text:e,columns:o});if(e.includes("- Content Preview:")){let t=e.split("- Content Preview:"),n=t[0],s=t[1]||"",r="Check if Starting and Ending matches",l=s.split(r),u=l[0]?.trim()||"",f=l[1]?`${r}${l[1]}`:"",m=u.split(`
47
- `),c=String(m.length).length;return C.createElement(X,{flexDirection:"column",width:o-3},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"#444",paddingX:1,width:"100%"},C.createElement(X,{alignSelf:"flex-end",marginTop:-1,marginRight:1},C.createElement(oe,{backgroundColor:"#444",color:"white"}," FILE SNAPSHOT ")),C.createElement(X,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>C.createElement(X,{key:d,width:"100%"},C.createElement(X,{width:c+2,flexShrink:0},C.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),C.createElement(X,{flexGrow:1},C.createElement(oe,{color:"white"},a)))))))}if(e.includes("```")){let t=e.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return C.createElement(X,{flexDirection:"column",width:o-3},t.map((n,s)=>{if(n.startsWith("```")){let l=n.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/),u=l?l[1]:"code",m=(l?l[2]:n.replace(/^```\w*\n?/,"").replace(/```$/,"")).trimEnd().split(`
48
- `),c=String(m.length).length;return C.createElement(X,{key:s,flexDirection:"column",marginY:0,backgroundColor:"#111",borderStyle:"round",borderColor:"#333",paddingX:1,width:"100%"},C.createElement(X,{alignSelf:"flex-end",marginTop:-1,marginRight:1},C.createElement(oe,{backgroundColor:"#333",color:"white"}," ",u.toUpperCase()," ")),C.createElement(X,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>C.createElement(X,{key:d,width:"100%"},C.createElement(X,{width:c+2,flexShrink:0},C.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),C.createElement(X,{flexGrow:1},C.createElement(oe,{color:"cyan"},a))))))}let r=n;return s>0&&(r=r.replace(/^[\r\n]+/,"")),s<t.length-1&&(r=r.replace(/[\r\n]+$/,"")),r?C.createElement(pa,{key:s,text:r,columns:o-3}):null}))}return C.createElement(pa,{text:e,columns:o-3})}),ga=e=>{let o=Math.round(e/1e3);if(o<=0)return"0s";let t=Math.floor(o/60),n=o%60;return t>0?`${t}m ${n}s`:`${o}s`},Ys=C.memo(({msg:e,showFullThinking:o,columns:t=80})=>{let n=e.role==="system"&&(e.text?.includes("[DIFF_START]")||e.text?.includes("- Content Preview:")),s=e.role==="system"&&e.text?.includes("[TOOL RESULT]: ERROR:")&&!e.text?.includes("[DIFF_START]")&&(e.toolName==="update_file"||e.text?.includes("Could not find exact match")),r=e.isTerminalRecord;if(e.isHomeWarning)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"red",padding:0,width:"100%"},C.createElement(X,{paddingX:1,backgroundColor:"#3a0000"},C.createElement(oe,{color:"red",bold:!0},e.text)),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,{color:"white"},e.subText))));if(e.isLogo)return C.createElement(X,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},C.createElement(oe,null,e.text));if(e.id&&String(e.id).startsWith("welcome"))return C.createElement(X,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},C.createElement(X,{borderStyle:"round",borderColor:"gray",paddingX:3,paddingY:0},C.createElement(oe,{color:"cyan",bold:!0},e.text.trim())));if(e.isVisualFeedback)return C.createElement(X,{marginBottom:0,marginTop:0,paddingX:1,width:"100%"},C.createElement(oe,{color:"white"},e.text));if(s)return C.createElement(X,{marginBottom:1},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:1,paddingY:0},C.createElement(oe,{color:"red",bold:!0,underline:!0},"\u274C PATCH FAILED"),C.createElement(X,{marginTop:1},C.createElement(oe,{color:"red"},"Patch failed: ",C.createElement(oe,{color:"white",bold:!0},"Model generated malformed edit.")))));if(e.role==="system"&&e.text?.includes("[TOOL RESULT]")&&!n&&!r&&!s)return null;if(e.isImageStats)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},C.createElement(X,{paddingX:1,backgroundColor:"#0e1b21"},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4B3} IMAGE STATS")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"column"},e.text.split(`
49
- `).map((a,d)=>C.createElement(oe,{key:d,color:"white"},a)))));if(e.isAskRecord){let a=e.text.match(/Selection: (.*)/),d=a?a[1]:"No selection",p=Ie(2);return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(X,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: RESOLVED")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,{color:"white"},"Selection: ",C.createElement(oe,{color:"yellow",bold:!0},d)))))}if(e.isAboutRecord)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(X,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F4A0} ABOUT FLUX FLOW")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(oe,null,e.text))));if(e.isUpdateNotification)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},C.createElement(X,{paddingX:1},C.createElement(oe,{color:"cyan",bold:!0},"\u{1F680} FLUX FLOW UPDATE AVAILABLE")),C.createElement(X,{paddingX:1,marginTop:1,marginBottom:1},C.createElement(ha,{text:e.text,columns:t}))));if(e.isHelpRecord)return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(X,{flexDirection:"column",borderStyle:"round",borderColor:"magenta",paddingX:2,paddingY:1,width:"100%"},C.createElement(oe,{color:"magenta",bold:!0,underline:!0},"\u{1F4DC} COMMAND REFERENCE"),C.createElement(X,{flexDirection:"column",marginTop:1},[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase to checkpoint"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat in a .txt file"},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/image",desc:"Generate images"},{cmd:"/mode",desc:"Toggle Flux/Flow modes"},{cmd:"/thinking",desc:"Set AI reasoning depth"},{cmd:"/model",desc:"Switch AI model"},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/reset",desc:"Wipe all project data"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/fluxflow",desc:"Project management"},{cmd:"/update",desc:"Check/Install updates"}].map((d,p)=>C.createElement(X,{key:p,flexDirection:"row"},C.createElement(X,{width:15},C.createElement(oe,{color:"cyan",bold:!0},d.cmd)),C.createElement(oe,{color:"gray"}," - ",d.desc))))));if(e.isTerminalRecord){let a=e.text.match(/COMMAND: (.*)/),d=e.text.match(/PTY: (true|false)/),p=e.text.match(/OUTPUT: ([\s\S]*)/),h=a?a[1]:"Unknown",S=d?d[1]==="true":!1,T=p?p[1]:"";return C.createElement(X,{marginBottom:1,paddingX:1,width:"100%"},C.createElement(as,{command:h,output:T,completed:!0,columns:t,isPty:S}))}let[u,f]=C.useState(!e.isStreaming),m=C.useMemo(()=>$c(e.text),[e.text]);C.useEffect(()=>{e.isStreaming&&f(!1)},[e.id]);let c=C.useMemo(()=>e.role==="think"&&!o?"Thinking...":e.isStreaming?m:m.trimEnd(),[m,e.role,o,e.isStreaming]);return C.createElement(X,{marginBottom:e.role==="think"?0:e.role==="user"?1:e.role==="agent"?0:1,marginTop:(e.role==="think"||e.role==="user"||e.role==="agent",0),flexDirection:"column",flexShrink:0,width:"100%",flexGrow:1},e.role==="user"?C.createElement(X,{backgroundColor:"#262626",paddingX:1,paddingY:1,width:"100%",flexDirection:"column"},Ho(c.replace(/\r\n/g,`
45
+ `+O)}else T=jo(c,t-4);s.push(b.createElement(K,{key:m,width:"100%"},b.createElement(En,{text:T,color:o})))}}),u("final"),b.createElement(K,{flexDirection:"column",width:t-2},s)}),Uc=b.memo(({line:e,columns:o=80})=>{let t=e.includes("[UI_CONTEXT]"),n=e.replace("[UI_CONTEXT]","");if(t&&n.includes("\u2550"))return b.createElement(K,{backgroundColor:"#1a1a1a",paddingX:1,width:"100%"},b.createElement(oe,{color:"gray",dimColor:!0},"\u2550".repeat(Math.max(10,o-4))));let s=n.startsWith("-"),r=n.startsWith("+"),l=n[0],u=n.substring(1),f=u.indexOf("|"),m=f!==-1?u.substring(0,f).trim():"",c=f!==-1?u.substring(f+1):u,a=s?"#3a0c0c":r?"#0c3a1a":"#1a1a1a",d=s?"#ff4d4d":r?"#4dff88":t?"gray":"white";return b.createElement(K,{backgroundColor:a,paddingX:1,width:"100%"},b.createElement(K,{width:5,flexShrink:0},b.createElement(oe,{color:s?"#cf3a3a":r?"#3acf65":"gray",dimColor:t},m)),b.createElement(K,{width:2,flexShrink:0,marginLeft:1},b.createElement(oe,{color:d,bold:!0},s?"-":r?"+":" ")),b.createElement(K,{flexGrow:1,marginLeft:1},b.createElement(oe,{color:d,dimColor:t},jo(c,o-14))))}),Rc=b.memo(({text:e,columns:o=80})=>{let t=e.match(/\[DIFF_START\]([\s\S]*?)\[DIFF_END\]/),s=(t?t[1].trim():"").split(`
46
+ `);return b.createElement(K,{flexDirection:"column",width:o-3,marginBottom:0},b.createElement(K,{flexDirection:"column",backgroundColor:"#1a1a1a",paddingY:0,width:"100%"},s.map((r,l)=>b.createElement(Uc,{key:l,line:r,columns:o-3}))))}),xa=b.memo(({text:e,columns:o=80})=>{if(!e)return null;if(e.includes("[DIFF_START]"))return b.createElement(Rc,{text:e,columns:o});if(e.includes("- Content Preview:")){let t=e.split("- Content Preview:"),n=t[0],s=t[1]||"",r="Check if Starting and Ending matches",l=s.split(r),u=l[0]?.trim()||"",f=l[1]?`${r}${l[1]}`:"",m=u.split(`
47
+ `),c=String(m.length).length;return b.createElement(K,{flexDirection:"column",width:o-3},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"#444",paddingX:1,width:"100%"},b.createElement(K,{alignSelf:"flex-end",marginTop:-1,marginRight:1},b.createElement(oe,{backgroundColor:"#444",color:"white"}," FILE SNAPSHOT ")),b.createElement(K,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>b.createElement(K,{key:d,width:"100%"},b.createElement(K,{width:c+2,flexShrink:0},b.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),b.createElement(K,{flexGrow:1},b.createElement(oe,{color:"white"},a)))))))}if(e.includes("```")){let t=e.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);return b.createElement(K,{flexDirection:"column",width:o-3},t.map((n,s)=>{if(n.startsWith("```")){let l=n.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/),u=l?l[1]:"code",m=(l?l[2]:n.replace(/^```\w*\n?/,"").replace(/```$/,"")).trimEnd().split(`
48
+ `),c=String(m.length).length;return b.createElement(K,{key:s,flexDirection:"column",marginY:0,backgroundColor:"#111",borderStyle:"round",borderColor:"#333",paddingX:1,width:"100%"},b.createElement(K,{alignSelf:"flex-end",marginTop:-1,marginRight:1},b.createElement(oe,{backgroundColor:"#333",color:"white"}," ",u.toUpperCase()," ")),b.createElement(K,{flexDirection:"column",paddingY:1,width:"100%"},m.map((a,d)=>b.createElement(K,{key:d,width:"100%"},b.createElement(K,{width:c+2,flexShrink:0},b.createElement(oe,{color:"gray",dimColor:!0},String(d+1).padStart(c," ")," ")),b.createElement(K,{flexGrow:1},b.createElement(oe,{color:"cyan"},a))))))}let r=n;return s>0&&(r=r.replace(/^[\r\n]+/,"")),s<t.length-1&&(r=r.replace(/[\r\n]+$/,"")),r?b.createElement(ga,{key:s,text:r,columns:o-3}):null}))}return b.createElement(ga,{text:e,columns:o-3})}),ya=e=>{let o=Math.round(e/1e3);if(o<=0)return"0s";let t=Math.floor(o/60),n=o%60;return t>0?`${t}m ${n}s`:`${o}s`},Ws=b.memo(({msg:e,showFullThinking:o,columns:t=80})=>{let n=e.role==="system"&&(e.text?.includes("[DIFF_START]")||e.text?.includes("- Content Preview:")),s=e.role==="system"&&e.text?.includes("[TOOL RESULT]: ERROR:")&&!e.text?.includes("[DIFF_START]")&&(e.toolName==="update_file"||e.text?.includes("Could not find exact match")),r=e.isTerminalRecord;if(e.isHomeWarning)return b.createElement(K,{marginBottom:1,paddingX:1,width:"100%"},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"red",padding:0,width:"100%"},b.createElement(K,{paddingX:1,backgroundColor:"#3a0000"},b.createElement(oe,{color:"red",bold:!0},e.text)),b.createElement(K,{paddingX:1,marginTop:1,marginBottom:1},b.createElement(oe,{color:"white"},e.subText))));if(e.isLogo)return b.createElement(K,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},b.createElement(oe,null,e.text));if(e.id&&String(e.id).startsWith("welcome"))return b.createElement(K,{flexDirection:"column",alignItems:"center",width:"100%",marginY:1},b.createElement(K,{borderStyle:"round",borderColor:"gray",paddingX:3,paddingY:0},b.createElement(oe,{color:"cyan",bold:!0},e.text.trim())));if(e.isVisualFeedback)return b.createElement(K,{marginBottom:0,marginTop:0,paddingX:1,width:"100%"},b.createElement(oe,{color:"white"},e.text));if(s)return b.createElement(K,{marginBottom:1},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:1,paddingY:0},b.createElement(oe,{color:"red",bold:!0,underline:!0},"\u274C PATCH FAILED"),b.createElement(K,{marginTop:1},b.createElement(oe,{color:"red"},"Patch failed: ",b.createElement(oe,{color:"white",bold:!0},"Model generated malformed edit.")))));if(e.role==="system"&&e.text?.includes("[TOOL RESULT]")&&!n&&!r&&!s)return null;if(e.isImageStats)return b.createElement(K,{marginBottom:1,paddingX:1,width:"100%"},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},b.createElement(K,{paddingX:1,backgroundColor:"#0e1b21"},b.createElement(oe,{color:"cyan",bold:!0},"\u{1F4B3} IMAGE STATS")),b.createElement(K,{paddingX:1,marginTop:1,marginBottom:1,flexDirection:"column"},e.text.split(`
49
+ `).map((a,d)=>b.createElement(oe,{key:d,color:"white"},a)))));if(e.isAskRecord){let a=e.text.match(/Selection: (.*)/),d=a?a[1]:"No selection",p=Oe(2);return b.createElement(K,{marginBottom:1,paddingX:1,width:"100%"},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},b.createElement(K,{paddingX:1},b.createElement(oe,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: RESOLVED")),b.createElement(K,{paddingX:1,marginTop:1,marginBottom:1},b.createElement(oe,{color:"white"},"Selection: ",b.createElement(oe,{color:"yellow",bold:!0},d)))))}if(e.isAboutRecord)return b.createElement(K,{marginBottom:1,paddingX:1,width:"100%"},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},b.createElement(K,{paddingX:1},b.createElement(oe,{color:"cyan",bold:!0},"\u{1F4A0} ABOUT FLUX FLOW")),b.createElement(K,{paddingX:1,marginTop:1,marginBottom:1},b.createElement(oe,null,e.text))));if(e.isUpdateNotification)return b.createElement(K,{marginBottom:1,paddingX:1,width:"100%"},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},b.createElement(K,{paddingX:1},b.createElement(oe,{color:"cyan",bold:!0},"\u{1F680} FLUX FLOW UPDATE AVAILABLE")),b.createElement(K,{paddingX:1,marginTop:1,marginBottom:1},b.createElement(xa,{text:e.text,columns:t}))));if(e.isHelpRecord)return b.createElement(K,{marginBottom:1,paddingX:1,width:"100%"},b.createElement(K,{flexDirection:"column",borderStyle:"round",borderColor:"magenta",paddingX:2,paddingY:1,width:"100%"},b.createElement(oe,{color:"magenta",bold:!0,underline:!0},"\u{1F4DC} COMMAND REFERENCE"),b.createElement(K,{flexDirection:"column",marginTop:1},[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase to checkpoint"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat in a .txt file"},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/image",desc:"Generate images"},{cmd:"/mode",desc:"Toggle Flux/Flow modes"},{cmd:"/thinking",desc:"Set AI reasoning depth"},{cmd:"/model",desc:"Switch AI model"},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/reset",desc:"Wipe all project data"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/fluxflow",desc:"Project management"},{cmd:"/update",desc:"Check/Install updates"}].map((d,p)=>b.createElement(K,{key:p,flexDirection:"row"},b.createElement(K,{width:15},b.createElement(oe,{color:"cyan",bold:!0},d.cmd)),b.createElement(oe,{color:"gray"}," - ",d.desc))))));if(e.isTerminalRecord){let a=e.text.match(/COMMAND: (.*)/),d=e.text.match(/PTY: (true|false)/),p=e.text.match(/OUTPUT: ([\s\S]*)/),h=a?a[1]:"Unknown",E=d?d[1]==="true":!1,w=p?p[1]:"";return b.createElement(K,{marginBottom:1,paddingX:1,width:"100%"},b.createElement(ss,{command:h,output:w,completed:!0,columns:t,isPty:E}))}let[u,f]=b.useState(!e.isStreaming),m=b.useMemo(()=>Pc(e.text),[e.text]);b.useEffect(()=>{e.isStreaming&&f(!1)},[e.id]);let c=b.useMemo(()=>e.role==="think"&&!o?"Thinking...":e.isStreaming?m:m.trimEnd(),[m,e.role,o,e.isStreaming]);return b.createElement(K,{marginBottom:e.role==="think"?0:e.role==="user"?1:e.role==="agent"?0:1,marginTop:(e.role==="think"||e.role==="user"||e.role==="agent",0),flexDirection:"column",flexShrink:0,width:"100%",flexGrow:1},e.role==="user"?b.createElement(K,{backgroundColor:"#262626",paddingX:1,paddingY:1,width:"100%",flexDirection:"column"},jo(c.replace(/\r\n/g,`
50
50
  `).replace(/\r/g,`
51
51
  `).replace(/\\\n/g,`
52
52
  `).replace(/\\$/,""),t-6).split(`
53
- `).map((a,d)=>C.createElement(X,{key:d,flexDirection:"row",width:"100%"},C.createElement(X,{flexShrink:0,width:2},C.createElement(oe,{bold:!0,color:"white"},d===0?"\u276F":" ")),C.createElement(X,{flexGrow:1,marginLeft:1},C.createElement(Mn,{text:a,color:e.color||"white"}))))):e.role==="think"?C.createElement(X,{flexDirection:"column",marginTop:0,marginBottom:0,paddingX:1,width:"100%"},e.isStreaming&&!e.duration?C.createElement(oe,{bold:!0,color:"white"},"\u2727 Thinking..."):C.createElement(oe,{bold:!0,color:"white"},"\u2726 Thought",e.duration?C.createElement(oe,{color:"gray"}," for ",C.createElement(oe,{bold:!0,color:"cyan"},ga(e.duration))):""),C.createElement(X,{borderStyle:"single",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingTop:1,paddingBottom:1,flexDirection:"column",width:"100%"},Pc(c,t))):C.createElement(X,{flexDirection:"column",paddingX:1,marginTop:0,width:"100%"},C.createElement(ha,{text:c.replace(/ \|\n\n/g,` |
54
- `),columns:t}),e.memoryUpdated&&C.createElement(X,{marginTop:1,width:"100%"},C.createElement(oe,{color:"yellow",italic:!0},"\u2728 [Memory Updated]")),e.role==="agent"&&e.workedDuration?C.createElement(X,{marginTop:1,marginBottom:2,width:"100%"},C.createElement(oe,null,"["),C.createElement(oe,{color:"gray"},"\u26A1 Worked for ",C.createElement(oe,{bold:!0,color:"cyan"},ga(e.workedDuration))),C.createElement(oe,null,"]")):null))}),Rc=C.memo(({messages:e,showFullThinking:o,columns:t=80})=>C.createElement(X,{flexDirection:"column",width:"100%"},e.map((n,s)=>C.createElement(Ys,{key:n.id||s,msg:n,showFullThinking:o,columns:t})))),xa=Rc});import We from"react";import{Box as sn,Text as Rt}from"ink";var Wc,wa,Ta=re(()=>{Wn();Wc=We.memo(({mode:e,thinkingLevel:o,tokens:t="0.0k",tokensTotal:n="0.0k",chatId:s="NEW-SESSION",isMemoryEnabled:r=!0,apiTier:l="Free",aiProvider:u="Google"})=>{let f=e==="Flux"?"yellow":"cyan",m=e==="Flux"?"\u26A1":"\u{1F30A}",c=256e3;return(u==="DeepSeek"||u==="Google"&&l==="Paid")&&(c=4e5),We.createElement(sn,{borderStyle:"round",borderColor:"gray",flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},We.createElement(sn,null,We.createElement(sn,{marginRight:1},We.createElement(Rt,{color:f,bold:!0},m," ",e.toUpperCase())),We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginX:1},We.createElement(Rt,{color:"magenta"},"\u{1F9E0} ",o)),We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginX:1},We.createElement(Rt,{color:"gray"},"MEM: "),We.createElement(Rt,{color:r?"green":"red",bold:!0},r?"ON":"OFF"))),We.createElement(sn,{flexGrow:1,justifyContent:"center",paddingX:2},We.createElement(Rt,null,"\u{1F4C1}"),We.createElement(Rt,{color:"gray",italic:!0}," ",ma(process.cwd(),35))),We.createElement(sn,null,We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginX:1},We.createElement(Rt,null,"\u2728"),We.createElement(Rt,{color:"blue"}," ",so(n)," ",We.createElement(Rt,{dimColor:!0},"(",(t/c*100).toFixed(0),"%)"))),We.createElement(Rt,{color:"gray",dimColor:!0},"\u2503 "),We.createElement(sn,{marginLeft:1},We.createElement(Rt,null,"\u{1F194}"),We.createElement(Rt,{color:"gray",dimColor:!0,italic:!0}," ",s),(l==="Custom"||l==="Paid")&&We.createElement(Rt,{color:"gray",dimColor:!0}," | ",We.createElement(Rt,{color:"green",bold:!0},"PAID")))))}),wa=Wc});import Fo from"react";import{Box as nr,Text as ls}from"ink";import Yc from"ink-select-input";function fo({title:e,subtitle:o,items:t,onSelect:n}){return Fo.createElement(nr,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,width:"100%"},Fo.createElement(nr,{paddingX:1,paddingY:0,marginBottom:o?0:1},Fo.createElement(ls,{color:"magenta",bold:!0},"\u{1F527} ",typeof e=="string"?e.toUpperCase():e)),o&&Fo.createElement(nr,{paddingX:1,marginBottom:1},Fo.createElement(ls,{color:"yellow",dimColor:!0,italic:!0}," ",o)),Fo.createElement(nr,{flexDirection:"column",width:"100%"},Fo.createElement(Yc,{items:t,onSelect:n,itemComponent:jc,indicatorComponent:()=>null})),Fo.createElement(nr,{paddingX:1,marginTop:1},Fo.createElement(ls,{color:"gray",dimColor:!0,italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}var jc,Sa=re(()=>{jc=({label:e,isSelected:o})=>{let t=e==="Cancel"||e==="Back"||e.toLowerCase().includes("exit")||e.toLowerCase().includes("back");return Fo.createElement(nr,{marginTop:t?1:0,backgroundColor:o?"#2a2a2a":void 0,paddingX:1,width:"100%"},Fo.createElement(ls,{color:o?"cyan":"white",bold:o},o?"\u276F ":" ",e))}});var ne,Xt=re(()=>{ne=e=>{let o={};if(!e)return o;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let n=e.substring(t).match(/^(\w+)\s*=\s*/);if(!n){t++;continue}let s=n[1];t+=n[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let l=e[t];t++;let u=t,f=-1,m=t;for(;m<e.length;){let a=e.indexOf(l,m);if(a===-1)break;let d=0;for(let T=a-1;T>=0&&e[T]==="\\";T--)d++;if(d%2!==0){m=a+1;continue}let p=e.substring(a+1),h=p.trim(),S=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|tool:)/i.test(h));if(S&&p.startsWith(`
55
- `)){let T=h.split(`
56
- `)[0];if(!T.includes("=")&&!T.includes(")")){m=a+1;continue}}if(S){f=a;break}m=a+1}f!==-1?(r=e.substring(u,f),t=f+1):(r=e.substring(u),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(a,d)=>{switch(d){case"n":return`
57
- `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return d===l?l:a}})}else if(t<e.length&&e[t]==="["){let l=0,u=null,f=t,m=-1;for(let c=t;c<e.length;c++){let a=e[c];if(u&&a===u){let d=0;for(let p=c-1;p>=0&&e[p]==="\\";p--)d++;d%2===0&&(u=null)}else!u&&(a==='"'||a==="'"||a==="`")&&(u=a);if(!u&&(a==="["?l++:a==="]"&&l--,l===0)){m=c;break}}if(m!==-1){r=e.substring(f,m+1),t=m+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(f),t=e.length}else{let l=e.substring(t),u=l.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]))/);if(u){let f=u.index;r=l.substring(0,f).trim(),t+=f}else r=l.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),o[s]=r}return o}});import{execSync as Gc}from"child_process";var Or,rr,Ea,js=re(async()=>{await Dr();Or=null,rr=()=>{if(process.platform!=="win32")return!1;if(Or!==null)return Or;try{Gc('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Or=!0}catch{Or=!1}return Or},Ea=(e,o,t,n)=>`
53
+ `).map((a,d)=>b.createElement(K,{key:d,flexDirection:"row",width:"100%"},b.createElement(K,{flexShrink:0,width:2},b.createElement(oe,{bold:!0,color:"white"},d===0?"\u276F":" ")),b.createElement(K,{flexGrow:1,marginLeft:1},b.createElement(En,{text:a,color:e.color||"white"}))))):e.role==="think"?b.createElement(K,{flexDirection:"column",marginTop:0,marginBottom:0,paddingX:1,width:"100%"},e.isStreaming&&!e.duration?b.createElement(oe,{bold:!0,color:"white"},"\u2727 Thinking..."):b.createElement(oe,{bold:!0,color:"white"},"\u2726 Thought",e.duration?b.createElement(oe,{color:"gray"}," for ",b.createElement(oe,{bold:!0,color:"cyan"},ya(e.duration))):""),b.createElement(K,{borderStyle:"single",borderLeft:!0,borderRight:!1,borderTop:!1,borderBottom:!1,paddingLeft:2,paddingTop:1,paddingBottom:1,flexDirection:"column",width:"100%"},_c(c,t))):b.createElement(K,{flexDirection:"column",paddingX:1,marginTop:0,width:"100%"},b.createElement(xa,{text:c.replace(/ \|\n\n/g,` |
54
+ `),columns:t}),e.memoryUpdated&&b.createElement(K,{marginTop:1,width:"100%"},b.createElement(oe,{color:"yellow",italic:!0},"\u2728 [Memory Updated]")),e.role==="agent"&&e.workedDuration?b.createElement(K,{marginTop:1,marginBottom:2,width:"100%"},b.createElement(oe,null,"["),b.createElement(oe,{color:"gray"},"\u26A1 Worked for ",b.createElement(oe,{bold:!0,color:"cyan"},ya(e.workedDuration))),b.createElement(oe,null,"]")):null))}),Wc=b.memo(({messages:e,showFullThinking:o,columns:t=80})=>b.createElement(K,{flexDirection:"column",width:"100%"},e.map((n,s)=>b.createElement(Ws,{key:n.id||s,msg:n,showFullThinking:o,columns:t})))),wa=Wc});import Ye from"react";import{Box as sn,Text as Gt}from"ink";var Yc,Sa,Ea=re(()=>{Rn();Yc=Ye.memo(({mode:e,thinkingLevel:o,tokens:t="0.0k",tokensTotal:n="0.0k",chatId:s="NEW-SESSION",isMemoryEnabled:r=!0,apiTier:l="Free",aiProvider:u="Google"})=>{let f=e==="Flux"?"yellow":"cyan",m=e==="Flux"?"\u26A1":"\u{1F30A}",c=256e3;return(u==="DeepSeek"||u==="NVIDIA"||u==="Google"&&l==="Paid")&&(c=4e5),Ye.createElement(sn,{borderStyle:"round",borderColor:"gray",flexDirection:"row",justifyContent:"space-between",paddingX:1,width:"100%"},Ye.createElement(sn,null,Ye.createElement(sn,{marginRight:1},Ye.createElement(Gt,{color:f,bold:!0},m," ",e.toUpperCase())),Ye.createElement(Gt,{color:"gray",dimColor:!0},"\u2503 "),Ye.createElement(sn,{marginX:1},Ye.createElement(Gt,{color:"magenta"},"\u{1F9E0} ",o)),Ye.createElement(Gt,{color:"gray",dimColor:!0},"\u2503 "),Ye.createElement(sn,{marginX:1},Ye.createElement(Gt,{color:"gray"},"MEM: "),Ye.createElement(Gt,{color:r?"green":"red",bold:!0},r?"ON":"OFF"))),Ye.createElement(sn,{flexGrow:1,justifyContent:"center",paddingX:2},Ye.createElement(Gt,null,"\u{1F4C1}"),Ye.createElement(Gt,{color:"gray",italic:!0}," ",pa(process.cwd(),35))),Ye.createElement(sn,null,Ye.createElement(Gt,{color:"gray",dimColor:!0},"\u2503 "),Ye.createElement(sn,{marginX:1},Ye.createElement(Gt,null,"\u2728"),Ye.createElement(Gt,{color:"blue"}," ",so(n)," ",Ye.createElement(Gt,{dimColor:!0},"(",(t/c*100).toFixed(0),"%)"))),Ye.createElement(Gt,{color:"gray",dimColor:!0},"\u2503 "),Ye.createElement(sn,{marginLeft:1},Ye.createElement(Gt,null,"\u{1F194}"),Ye.createElement(Gt,{color:"gray",dimColor:!0,italic:!0}," ",s),(l==="Custom"||l==="Paid")&&Ye.createElement(Gt,{color:"gray",dimColor:!0}," | ",Ye.createElement(Gt,{color:"green",bold:!0},"PAID")))))}),Sa=Yc});import Fo from"react";import{Box as er,Text as is}from"ink";import jc from"ink-select-input";function fo({title:e,subtitle:o,items:t,onSelect:n}){return Fo.createElement(er,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,width:"100%"},Fo.createElement(er,{paddingX:1,paddingY:0,marginBottom:o?0:1},Fo.createElement(is,{color:"magenta",bold:!0},"\u{1F527} ",typeof e=="string"?e.toUpperCase():e)),o&&Fo.createElement(er,{paddingX:1,marginBottom:1},Fo.createElement(is,{color:"yellow",dimColor:!0,italic:!0}," ",o)),Fo.createElement(er,{flexDirection:"column",width:"100%"},Fo.createElement(jc,{items:t,onSelect:n,itemComponent:Gc,indicatorComponent:()=>null})),Fo.createElement(er,{paddingX:1,marginTop:1},Fo.createElement(is,{color:"gray",dimColor:!0,italic:!0},"(Arrows to select \u2022 Enter to confirm)")))}var Gc,ba=re(()=>{Gc=({label:e,isSelected:o})=>{let t=e==="Cancel"||e==="Back"||e.toLowerCase().includes("exit")||e.toLowerCase().includes("back");return Fo.createElement(er,{marginTop:t?1:0,backgroundColor:o?"#2a2a2a":void 0,paddingX:1,width:"100%"},Fo.createElement(is,{color:o?"cyan":"white",bold:o},o?"\u276F ":" ",e))}});var ne,qt=re(()=>{ne=e=>{let o={};if(!e)return o;let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t++;if(t>=e.length)break;let n=e.substring(t).match(/^(\w+)\s*=\s*/);if(!n){t++;continue}let s=n[1];t+=n[0].length;let r="";if(t<e.length&&(e[t]==='"'||e[t]==="'"||e[t]==="`")){let l=e[t];t++;let u=t,f=-1,m=t;for(;m<e.length;){let a=e.indexOf(l,m);if(a===-1)break;let d=0;for(let w=a-1;w>=0&&e[w]==="\\";w--)d++;if(d%2!==0){m=a+1;continue}let p=e.substring(a+1),h=p.trim(),E=h===""||/^,\s*\w+\s*=/.test(h)||h.startsWith(")")&&(h.length===1||/^\)\s*([,\]\s]|tool:)/i.test(h));if(E&&p.startsWith(`
55
+ `)){let w=h.split(`
56
+ `)[0];if(!w.includes("=")&&!w.includes(")")){m=a+1;continue}}if(E){f=a;break}m=a+1}f!==-1?(r=e.substring(u,f),t=f+1):(r=e.substring(u),t=e.length);let c=s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase());r=r.replace(/\\(.)/g,(a,d)=>{switch(d){case"n":return`
57
+ `;case"r":return"\r";case"t":return" ";case"\\":return"\\";default:return d===l?l:a}})}else if(t<e.length&&e[t]==="["){let l=0,u=null,f=t,m=-1;for(let c=t;c<e.length;c++){let a=e[c];if(u&&a===u){let d=0;for(let p=c-1;p>=0&&e[p]==="\\";p--)d++;d%2===0&&(u=null)}else!u&&(a==='"'||a==="'"||a==="`")&&(u=a);if(!u&&(a==="["?l++:a==="]"&&l--,l===0)){m=c;break}}if(m!==-1){r=e.substring(f,m+1),t=m+1;try{let c=r.trim();c.startsWith("'")||c.includes("'")}catch{}}else r=e.substring(f),t=e.length}else{let l=e.substring(t),u=l.match(/,\s*\w+\s*=|(?:\s*\)\s*(?:$|\]))/);if(u){let f=u.index;r=l.substring(0,f).trim(),t+=f}else r=l.trim(),t=e.length}r==="true"?r=!0:r==="false"?r=!1:typeof r=="string"&&!isNaN(r)&&r.trim()!==""&&(r=Number(r)),typeof r=="string"&&(s.toLowerCase().includes("path")||["dest","source","to","from"].includes(s.toLowerCase()))&&(r=r.replace(/\x0C/g,"\\f").replace(/\x0D/g,"\\r").replace(/\x0B/g,"\\v").replace(/\x08/g,"\\b")),o[s]=r}return o}});import{execSync as Hc}from"child_process";var Dr,tr,Ca,Ys=re(async()=>{await Or();Dr=null,tr=()=>{if(process.platform!=="win32")return!1;if(Dr!==null)return Dr;try{Hc('powershell.exe -NoProfile -Command "exit"',{stdio:"ignore"}),Dr=!0}catch{Dr=!1}return Dr},Ca=(e,o,t,n)=>`
58
58
  -- TOOL DEFINITIONS --
59
59
  Access to internal tools. MUST use the exact syntax on a new line: [tool:functions.ToolName(args)]
60
60
 
@@ -62,7 +62,7 @@ MANDATORY TOOL USAGE POLICY:
62
62
  - **MAX 3 TOOL CALLS PER TURN. Next Turn, verify results, plan next**
63
63
  ${e==="Flux"?`- USE multiple search & replace on patch tool if editing same file/path with many edits \u2190 **MANDATORY where possible**
64
64
  - Tool execution denied? MUST use 'Ask' tool immediately to ask for reason/changes. NEVER END RESPONSE OR PROCEED BLINDLY \u2190 **MANDATORY**
65
- - FileMap >> ReadFile for understandling files efficiently
65
+ - FileMap >>> ReadFile for understandling files efficiently
66
66
  `:""}- No brute force, no spamming of tools
67
67
  ${e==="Flux"?`- **File Tools >> Code in chat**
68
68
  `:""}
@@ -75,41 +75,41 @@ ${e==="Flux"?`- **File Tools >> Code in chat**
75
75
 
76
76
  ${e==="Flux"?`- PROJECT TOOLS (path = relative to CWD, path separator: '/') -
77
77
  1. [tool:functions.ReadFile(path="...", startLine=number, endLine=number)]. ${n!=="Google"?`${t?"Supports images/docs. User gives image/doc: VIEW FIRST":"No Multimodal support"}`:"Supports images/docs. User gives image/doc: VIEW FIRST"}
78
- 2. [tool:functions.FileMap(path="...")]. Shows file structure, dependency, functions, variable maps. Token Efficient than ReadFile. Understand File? FileMap >>> ReadFile
78
+ 2. [tool:functions.FileMap(path="path/file")]. Shows file structure, dependency, functions, variable maps. Token Efficient than ReadFile. Understand File? FileMap >>> ReadFile
79
79
  3. [tool:functions.ReadFolder(path="...")]. Detailed DIR stats
80
80
  4. [tool:functions.PatchFile(path="...", replaceContent1="exact string", newContent1="...", ...MAX 10)]. Surgical Patch. **Multiple patch on same file/path? Use replaceContent2, newContent2 etc >>> multiple spams**. Unsure? ReadFile >> guessing
81
81
  5. [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile > WriteFile. Verify Imports
82
82
  6. [tool:functions.SearchKeyword(keyword="...", file="optional")]. Global project search. If 'file' is provided, searches only that file. Finds definitions/logic without reading every file
83
- 7. [tool:functions.Run(command="...")]. Runs ${o==="Windows"?rr()?`${Yn?"Interactive ":""}WINDOWS POWERSHELL ONLY`:`${Yn?"Interactive ":""}WINDOWS CMD ONLY`:`${Yn?"Interactive ":""}BASH`} command. Destructive/Irreversible ops -> Ask user. **TOOL DENY RULE APPLIES**. **1 CALL LIMIT OR 3 CONSECUTIVE RUN TOOL ONLY**
83
+ 7. [tool:functions.Run(command="...")]. Runs ${o==="Windows"?tr()?`${Wn?"Interactive ":""}WINDOWS POWERSHELL ONLY`:`${Wn?"Interactive ":""}WINDOWS CMD ONLY`:`${Wn?"Interactive ":""}BASH`} command. Destructive/Irreversible ops -> Ask user. **TOOL DENY RULE APPLIES**. **1 CALL LIMIT OR 3 CONSECUTIVE RUN TOOL ONLY**
84
84
  8. [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout
85
85
  9. [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document
86
86
 
87
87
  - VERIFY TOOL RESULT CONTENTS. Fix errors. No hallucinations
88
88
  - Escape quotes: \\" for code strings
89
89
  - Literal escapes: Double-escape sequences (e.g., \\\\n, \\\\t)
90
- - File structure: Real newlines for code formatting`.trim():"\n- FILE TOOLS ARE NOT AVAILABLE IN FLOW (Tell user to,` /mode flux` if needed)".trim()}`.trim()});import{spawn as Gs}from"child_process";var cs,Yn,us,Lr,It,$o,Mo,ba,Ca,Xs,Hs,Dr=re(async()=>{Xt();await js();cs=null;try{let e=await import("node-pty");cs=e.default||e}catch{}Yn=!!cs,us=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Lr=e=>{if(!e)return"";let o=[[]],t=0,n=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,l,u=m=>{for(let c=0;c<m.length;c++){let a=m[c];if(a===`
90
+ - File structure: Real newlines for code formatting`.trim():"\n- FILE TOOLS ARE NOT AVAILABLE IN FLOW (Tell user to,` /mode flux` if needed)".trim()}`.trim()});import{spawn as js}from"child_process";var as,Wn,ls,Lr,Dt,$o,Io,ka,Ia,Hs,Gs,Or=re(async()=>{qt();await Ys();as=null;try{let e=await import("node-pty");as=e.default||e}catch{}Wn=!!as,ls=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Lr=e=>{if(!e)return"";let o=[[]],t=0,n=0,s=/\x1b\[([0-9;]*?)([a-zA-Z])/g,r=0,l,u=m=>{for(let c=0;c<m.length;c++){let a=m[c];if(a===`
91
91
  `)for(t++,n=0;t>=o.length;)o.push([]);else if(a==="\r")n=0;else{for(;t>=o.length;)o.push([]);let d=o[t];for(;n>d.length;)d.push(" ");d[n]=a,n++}}};for(;(l=s.exec(e))!==null;){u(e.substring(r,l.index));let m=l[1],c=l[2],a=m?m.split(";").map(Number):[];if(c==="A"){let d=a[0]||1;t=Math.max(0,t-d)}else if(c==="B"){let d=a[0]||1;for(t=t+d;t>=o.length;)o.push([])}else if(c==="C"){let d=a[0]||1;n=n+d}else if(c==="D"){let d=a[0]||1;n=Math.max(0,n-d)}else if(c==="G"){let d=(a[0]||1)-1;n=Math.max(0,d)}else if(c==="H"||c==="f"){let d=(a[0]||1)-1,p=(a[1]||1)-1;for(t=Math.max(0,d),n=Math.max(0,p);t>=o.length;)o.push([])}else if(c==="K"){let d=a[0]||0;if(t<o.length){let p=o[t];if(d===0)p.length=n;else if(d===1)for(let h=0;h<n&&h<p.length;h++)p[h]=" ";else d===2&&(p.length=0)}}else if(c==="J"){let d=a[0]||0;(d===2||d===3)&&(o.length=0,o.push([]),t=0,n=0)}r=s.lastIndex}u(e.substring(r));let f=o.map(m=>m.join(""));for(;f.length>0&&f[f.length-1]==="";)f.pop();return f.join(`
92
- `)},It=null,$o=!1,Mo=e=>{try{It&&($o&&typeof It.write=="function"?It.write(e):It.stdin&&It.stdin.writable&&It.stdin.write(e))}catch{}},ba=()=>{if(It){try{$o&&typeof It.destroy=="function"?It.destroy():typeof It.kill=="function"&&(process.platform==="win32"?Gs("taskkill",["/pid",It.pid,"/f","/t"]):It.kill("SIGKILL"))}catch{}It=null,$o=!1}},Ca=(e,o=!1)=>{if(process.platform!=="win32")return e;let t=[],n="",s=null,r=!1;for(let c=0;c<e.length;c++){let a=e[c];if(r){n+=a,r=!1;continue}if(a==="\\"){if(e[c+1]===" "){n+=" ",c++;continue}n+=a,r=!0;continue}s?(a===s&&(s=null),n+=a):a==='"'||a==="'"?(s=a,n+=a):a===";"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push(o?";":"&")):a==="&"&&!n.includes("://")?e[c+1]==="&"?(n.length>0&&(t.push(n),n=""),t.push("&&"),c++):(n.length>0&&(t.push(n),n=""),t.push("&")):a==="|"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push("|")):/\s/.test(a)?n.length>0&&(t.push(n),n=""):n+=a}n.length>0&&t.push(n);let l=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),u=[];for(let c=0;c<t.length;c++){let a=t[c];if(a==="mkdir"&&o&&rr()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&d.push(h),p++}if(d.length>0){let h=d.map(S=>{let T=S.replace(/^['"]|['"]$/g,""),w=S;return l(T)&&(w=S.replace(/\//g,"\\")),w});u.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else u.push("New-Item","-ItemType","Directory","-Force");c=p-1;continue}if(a==="rm"&&o&&rr()){let d=[],p=!1,h=!1,S=c+1;for(;S<t.length;){let w=t[S];if([">",">>","<","&","&&","|","||",";"].includes(w))break;w==="-rf"||w==="-fr"?(p=!0,h=!0):w==="-r"||w==="-R"||w==="--recursive"?p=!0:w==="-f"||w==="--force"?h=!0:d.push(w),S++}let T=["Remove-Item"];if(p&&T.push("-Recurse"),h&&T.push("-Force"),d.length>0){let w=d.map(I=>{let L=I.replace(/^['"]|['"]$/g,""),_=I;return l(L)&&(_=I.replace(/\//g,"\\")),_});T.push("-Path",w.join(","))}u.push(...T),c=S-1;continue}if(a==="cp"&&o&&rr()){let d=[],p=!1,h=!1,S=c+1;for(;S<t.length;){let w=t[S];if([">",">>","<","&","&&","|","||",";"].includes(w))break;w==="-r"||w==="-R"||w==="--recursive"?p=!0:w==="-f"||w==="--force"?h=!0:d.push(w),S++}let T=["Copy-Item"];if(p&&T.push("-Recurse"),h&&T.push("-Force"),d.length>0){let w=d.map(I=>{let L=I.replace(/^['"]|['"]$/g,""),_=I;return l(L)&&(_=I.replace(/\//g,"\\")),_});if(w.length>1){let I=w.pop();T.push("-Path",w.join(","),"-Destination",I)}else T.push("-Path",w[0])}u.push(...T),c=S-1;continue}if(a==="touch"&&o&&rr()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;d.push(h),p++}if(d.length>0){let S=`(${d.map(T=>{let w=T.replace(/^['"]|['"]$/g,""),I=T;return l(w)&&(I=T.replace(/\//g,"\\")),I}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;u.push(S)}c=p-1;continue}if(a==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(u.push(">>"),c+=2):(u.push(">"),c+=1);continue}if(a==="|"&&t[c+1]==="cat"&&t[c+2]===">"){u.push(">"),c+=2;continue}if(a==="|"){let d=t[c+1];if(d){let p=d.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(p);if(l(p)&&h){u.push(">");continue}}}u.push(a)}let f=!1,m=u.map(c=>{if(c==="echo")return f=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(f=!1);let d=/^['"]|['"]$/.test(c),p=c;f&&d&&(p=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(p),S=p.replace(/^['"]|['"]$/g,"");l(S)&&(p=p.replace(/\//g,"\\"));let T=p.replace(/^['"]|['"]$/g,"");return T.includes(" ")&&!h&&(p=`"${T}"`),p});if(o){let c="",a=0;for(let d=0;d<m.length;d++){let p=m[d];p==="&&"?(c+="; if ($?) {",a++):p===";"?(c+=" }".repeat(a)+";",a=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=p)}return c+=" }".repeat(a),c}return m.join(" ")},Xs=async(e,o={})=>{let{command:t}=ne(e),{onChunk:n}=o;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=o.systemSettings||{},l={};return r.networkAccess===!1&&(l.HTTP_PROXY="http://127.0.0.1:9999",l.HTTPS_PROXY="http://127.0.0.1:9999",l.ALL_PROXY="socks5://127.0.0.1:9999",l.http_proxy="http://127.0.0.1:9999",l.https_proxy="http://127.0.0.1:9999",l.all_proxy="socks5://127.0.0.1:9999",l.NO_PROXY="localhost,127.0.0.1"),new Promise(u=>{let f=m=>{let c=Ca(t,m),a=s?m?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",d=s?m?["-NoProfile","-Command",c]:["/c",c]:["-c",c];if(cs)try{let p=cs.spawn(a,d,{name:"xterm-256color",cols:o.cols||120,rows:o.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...l}});It=p,$o=!0;let h="",S=!1;return p.onData(T=>{if(!S){h+=T,n&&n(T);let w=us(h);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(w)&&(S=!0,setTimeout(()=>u(`SUCCESS: Dev server started successfully in background.
92
+ `)},Dt=null,$o=!1,Io=e=>{try{Dt&&($o&&typeof Dt.write=="function"?Dt.write(e):Dt.stdin&&Dt.stdin.writable&&Dt.stdin.write(e))}catch{}},ka=()=>{if(Dt){try{$o&&typeof Dt.destroy=="function"?Dt.destroy():typeof Dt.kill=="function"&&(process.platform==="win32"?js("taskkill",["/pid",Dt.pid,"/f","/t"]):Dt.kill("SIGKILL"))}catch{}Dt=null,$o=!1}},Ia=(e,o=!1)=>{if(process.platform!=="win32")return e;let t=[],n="",s=null,r=!1;for(let c=0;c<e.length;c++){let a=e[c];if(r){n+=a,r=!1;continue}if(a==="\\"){if(e[c+1]===" "){n+=" ",c++;continue}n+=a,r=!0;continue}s?(a===s&&(s=null),n+=a):a==='"'||a==="'"?(s=a,n+=a):a===";"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push(o?";":"&")):a==="&"&&!n.includes("://")?e[c+1]==="&"?(n.length>0&&(t.push(n),n=""),t.push("&&"),c++):(n.length>0&&(t.push(n),n=""),t.push("&")):a==="|"&&!n.includes("://")?(n.length>0&&(t.push(n),n=""),t.push("|")):/\s/.test(a)?n.length>0&&(t.push(n),n=""):n+=a}n.length>0&&t.push(n);let l=c=>!(!c.includes("/")||/^(https?|file|ftp):\/\//i.test(c)||c.startsWith("/")&&(c.match(/\//g)||[]).length===1||/\s\/|\/\s/.test(c)||/[\(\)\{\}\;\<\>\=\'\"]/.test(c)),u=[];for(let c=0;c<t.length;c++){let a=t[c];if(a==="mkdir"&&o&&tr()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;h!=="-p"&&h!=="--parents"&&h!=="-v"&&h!=="--verbose"&&d.push(h),p++}if(d.length>0){let h=d.map(E=>{let w=E.replace(/^['"]|['"]$/g,""),T=E;return l(w)&&(T=E.replace(/\//g,"\\")),T});u.push("New-Item","-ItemType","Directory","-Force","-Path",h.join(","))}else u.push("New-Item","-ItemType","Directory","-Force");c=p-1;continue}if(a==="rm"&&o&&tr()){let d=[],p=!1,h=!1,E=c+1;for(;E<t.length;){let T=t[E];if([">",">>","<","&","&&","|","||",";"].includes(T))break;T==="-rf"||T==="-fr"?(p=!0,h=!0):T==="-r"||T==="-R"||T==="--recursive"?p=!0:T==="-f"||T==="--force"?h=!0:d.push(T),E++}let w=["Remove-Item"];if(p&&w.push("-Recurse"),h&&w.push("-Force"),d.length>0){let T=d.map(I=>{let O=I.replace(/^['"]|['"]$/g,""),P=I;return l(O)&&(P=I.replace(/\//g,"\\")),P});w.push("-Path",T.join(","))}u.push(...w),c=E-1;continue}if(a==="cp"&&o&&tr()){let d=[],p=!1,h=!1,E=c+1;for(;E<t.length;){let T=t[E];if([">",">>","<","&","&&","|","||",";"].includes(T))break;T==="-r"||T==="-R"||T==="--recursive"?p=!0:T==="-f"||T==="--force"?h=!0:d.push(T),E++}let w=["Copy-Item"];if(p&&w.push("-Recurse"),h&&w.push("-Force"),d.length>0){let T=d.map(I=>{let O=I.replace(/^['"]|['"]$/g,""),P=I;return l(O)&&(P=I.replace(/\//g,"\\")),P});if(T.length>1){let I=T.pop();w.push("-Path",T.join(","),"-Destination",I)}else w.push("-Path",T[0])}u.push(...w),c=E-1;continue}if(a==="touch"&&o&&tr()){let d=[],p=c+1;for(;p<t.length;){let h=t[p];if([">",">>","<","&","&&","|","||",";"].includes(h))break;d.push(h),p++}if(d.length>0){let E=`(${d.map(w=>{let T=w.replace(/^['"]|['"]$/g,""),I=w;return l(T)&&(I=w.replace(/\//g,"\\")),I}).join(", ")}) | ForEach-Object { if (Test-Path $_) { (Get-Item $_).LastWriteTime = [System.DateTime]::Now } else { $null | Out-File -FilePath $_ } }`;u.push(E)}c=p-1;continue}if(a==="|"&&t[c+1]==="tee"){t[c+2]==="-a"?(u.push(">>"),c+=2):(u.push(">"),c+=1);continue}if(a==="|"&&t[c+1]==="cat"&&t[c+2]===">"){u.push(">"),c+=2;continue}if(a==="|"){let d=t[c+1];if(d){let p=d.replace(/^['"]|['"]$/g,""),h=/\.(txt|md|json|log|csv|html|css|py|js|xml|yaml|yml|pdf|docx|pptx|xlsx)$/i.test(p);if(l(p)&&h){u.push(">");continue}}}u.push(a)}let f=!1,m=u.map(c=>{if(c==="echo")return f=!0,c;[">",">>","<","&","&&","|","||",";"].includes(c)&&(f=!1);let d=/^['"]|['"]$/.test(c),p=c;f&&d&&(p=c.replace(/^['"]|['"]$/g,""));let h=/^['"]|['"]$/.test(p),E=p.replace(/^['"]|['"]$/g,"");l(E)&&(p=p.replace(/\//g,"\\"));let w=p.replace(/^['"]|['"]$/g,"");return w.includes(" ")&&!h&&(p=`"${w}"`),p});if(o){let c="",a=0;for(let d=0;d<m.length;d++){let p=m[d];p==="&&"?(c+="; if ($?) {",a++):p===";"?(c+=" }".repeat(a)+";",a=0):(c&&!c.endsWith(" ")&&!c.endsWith("{")&&(c+=" "),c+=p)}return c+=" }".repeat(a),c}return m.join(" ")},Hs=async(e,o={})=>{let{command:t}=ne(e),{onChunk:n}=o;if(!t)return'ERROR: Missing "command" argument for exec_command.';let s=process.platform==="win32",r=o.systemSettings||{},l={};return r.networkAccess===!1&&(l.HTTP_PROXY="http://127.0.0.1:9999",l.HTTPS_PROXY="http://127.0.0.1:9999",l.ALL_PROXY="socks5://127.0.0.1:9999",l.http_proxy="http://127.0.0.1:9999",l.https_proxy="http://127.0.0.1:9999",l.all_proxy="socks5://127.0.0.1:9999",l.NO_PROXY="localhost,127.0.0.1"),new Promise(u=>{let f=m=>{let c=Ia(t,m),a=s?m?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",d=s?m?["-NoProfile","-Command",c]:["/c",c]:["-c",c];if(as)try{let p=as.spawn(a,d,{name:"xterm-256color",cols:o.cols||120,rows:o.rows||30,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...l}});Dt=p,$o=!0;let h="",E=!1;return p.onData(w=>{if(!E){h+=w,n&&n(w);let T=ls(h);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(T)&&(E=!0,setTimeout(()=>u(`SUCCESS: Dev server started successfully in background.
93
93
 
94
- ${w}`),500))}}),p.onExit(({exitCode:T})=>{if(S)return;It=null;let w=Lr(h||""),I=us(w).replace(/\n{3,}/g,`
94
+ ${T}`),500))}}),p.onExit(({exitCode:w})=>{if(E)return;Dt=null;let T=Lr(h||""),I=ls(T).replace(/\n{3,}/g,`
95
95
 
96
- `)||"Command executed with no output.";u(T!==0?`ERROR: Command [${t}] failed with exit code [${T}].
96
+ `)||"Command executed with no output.";u(w!==0?`ERROR: Command [${t}] failed with exit code [${w}].
97
97
 
98
98
  ${I}`:`SUCCESS: Command [${t}] completed.
99
99
 
100
- ${I}`)}),!0}catch(p){return s&&m&&p.code==="ENOENT"?!1:(Hs(u,c,t,l,n,m),!0)}else return Hs(u,c,t,l,n,m),!0};s&&f(!0)||f(!1)})},Hs=(e,o,t,n,s,r=!0)=>{let l=process.platform==="win32",u=l?r?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",m=l?Gs(u,l?r?["-NoProfile","-Command",o]:["/c",o]:["-c",o],{cwd:process.cwd(),env:{...process.env,...n}}):Gs(o,{shell:!0,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...n}});It=m,$o=!1,m.stdin&&m.stdin.on("error",()=>{It=null});let c="",a="",d=!1;m.stdout.on("data",p=>{if(!d){let h=p.toString();c+=h,s&&s(h);let S=us(c);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(S)&&(d=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
100
+ ${I}`)}),!0}catch(p){return s&&m&&p.code==="ENOENT"?!1:(Gs(u,c,t,l,n,m),!0)}else return Gs(u,c,t,l,n,m),!0};s&&f(!0)||f(!1)})},Gs=(e,o,t,n,s,r=!0)=>{let l=process.platform==="win32",u=l?r?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",m=l?js(u,l?r?["-NoProfile","-Command",o]:["/c",o]:["-c",o],{cwd:process.cwd(),env:{...process.env,...n}}):js(o,{shell:!0,cwd:process.cwd(),env:{...process.env,CI:"false",TERM:"xterm-256color",FORCE_COLOR:"1",...n}});Dt=m,$o=!1,m.stdin&&m.stdin.on("error",()=>{Dt=null});let c="",a="",d=!1;m.stdout.on("data",p=>{if(!d){let h=p.toString();c+=h,s&&s(h);let E=ls(c);/(?:Network:\s+use\s+--host\s+to|Network:\s+Type\s+--host\s+to|Local:\s+http:\/\/localhost:\d+|ready in \d+\s*ms|Compiled successfully|Development server is running|Listening on:)/i.test(E)&&(d=!0,setTimeout(()=>e(`SUCCESS: Dev server started successfully in background.
101
101
 
102
- ${S}`),500))}}),m.stderr.on("data",p=>{if(!d){let h=p.toString();a+=h,s&&s(h)}}),m.on("close",p=>{if(d)return;It=null;let h=[],S=Lr(c),T=Lr(a);S&&h.push(`STDOUT:
103
- ${S}`),T&&h.push(`STDERR:
104
- ${T}`),p!==0&&h.push(`EXIT CODE: ${p}`);let w=h.join(`
102
+ ${E}`),500))}}),m.stderr.on("data",p=>{if(!d){let h=p.toString();a+=h,s&&s(h)}}),m.on("close",p=>{if(d)return;Dt=null;let h=[],E=Lr(c),w=Lr(a);E&&h.push(`STDOUT:
103
+ ${E}`),w&&h.push(`STDERR:
104
+ ${w}`),p!==0&&h.push(`EXIT CODE: ${p}`);let T=h.join(`
105
105
 
106
- `)||"Command executed with no output.",I=us(w).replace(/\n{3,}/g,`
106
+ `)||"Command executed with no output.",I=ls(T).replace(/\n{3,}/g,`
107
107
 
108
108
  `);e(p!==0?`ERROR: Command [${t}] failed with exit code [${p}].
109
109
 
110
110
  ${I}`:`SUCCESS: Command [${t}] completed.
111
111
 
112
- ${I}`)}),m.on("error",p=>{if(l&&r&&p.code==="ENOENT"){let h=Ca(t,!1);return Hs(e,h,t,n,s,!1)}It=null,e(`ERROR: Failed to start command [${t}]: ${p.message}`)})}});import Te,{useState as Fr}from"react";import{Box as Ot,Text as Kt,useInput as Hc}from"ink";import Xc from"ink-text-input";function qs({systemSettings:e,setSystemSettings:o,apiTier:t,setActiveView:n,setInputConfig:s,saveSettings:r,quotas:l,setMessages:u,aiProvider:f}){let[m,c]=Fr("categories"),[a,d]=Fr(0),[p,h]=Fr(0),[S,T]=Fr(null),[w,I]=Fr(""),L=b=>{switch(b){case"memory":return[{label:"Toggle Memory",value:"memory",status:e.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:ka(e),section:"Sandbox"},{label:"YOLO Mode",value:"autoExec",status:e.autoExec?"ON":"OFF",section:"Sandbox"},{label:"External Workspace Access",value:"externalAccess",status:e.allowExternalAccess?"ON":"OFF",section:"Sandbox"},{label:"Network Access (Terminal)",value:"networkAccess",status:e.networkAccess!==!1?"ON":"OFF",section:"Sandbox"},{label:"Always Ask Commands",value:"alwaysAsk",status:Ks(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Ks(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Ks(e.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:e.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Auto-Delete History",value:"autoDelete",status:e.autoDeleteHistory||"30d",section:"Other"},{label:"Save AppData Externally",value:"externalData",status:e.useExternalData?"ON":"OFF",section:"Other"}];case"updater":return[{label:"Auto-Update",value:"autoUpdate",status:e.autoUpdate?"ON":"OFF"},{label:"Preferred Updater",value:"updateManager",status:(e.updateManager||"npm")==="custom"?"Custom":(e.updateManager||"npm").toUpperCase()}];case"other":return[{label:"Current Provider",value:"aiProvider",status:f},{label:"API Tier",value:"apiTier",status:t},{label:"Download Language Parsers",value:"parserDownload",status:"ACTION"}];default:return[]}},_=an[a].id,R=L(_);Hc((b,A)=>{if(S){A.escape&&T(null);return}if(m==="categories")A.upArrow?d(F=>(F-1+an.length)%an.length):A.downArrow?d(F=>(F+1)%an.length):A.return||A.rightArrow?an[a].id==="exit"?n("chat"):(c("items"),h(0)):A.escape&&n("chat");else if(m==="items"){if(A.upArrow)h(F=>(F-1+R.length)%R.length);else if(A.downArrow)h(F=>(F+1)%R.length);else if(A.leftArrow||A.escape)c("categories");else if(A.return){let F=R[p];v(F)}}});let v=b=>{if(b.value==="memory")o(A=>({...A,memory:!A.memory}));else if(b.value==="sandboxPreset"){let A=ka(e),F=["Autonomous","Balanced","Strict"],j=(F.indexOf(A)+1)%F.length,Z=F[j];o(B=>{let z={...B,sandboxPreset:Z};return Z==="Strict"?(z.autoExec=!1,z.allowExternalAccess=!1,z.networkAccess=!1,z.autoApproveCommands="",z.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",z.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",z.autoApproveGit=!1):Z==="Balanced"?(z.autoExec=!0,z.allowExternalAccess=!1,z.networkAccess=!0,z.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",z.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",z.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",z.autoApproveGit=!1):Z==="Autonomous"&&(z.autoExec=!0,z.allowExternalAccess=!0,z.networkAccess=!0,z.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",z.autoDisallowCommands="",z.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",z.autoApproveGit=!0),z})}else if(b.value==="autoExec")e.autoExec?o(A=>({...A,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(b.value==="externalAccess")e.allowExternalAccess?o(A=>({...A,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(b.value==="networkAccess")o(A=>({...A,networkAccess:A.networkAccess===!1,sandboxPreset:"Custom"}));else if(b.value==="alwaysAsk")T("alwaysAskCommands"),I(e.alwaysAskCommands||"");else if(b.value==="autoApprove")T("autoApproveCommands"),I(e.autoApproveCommands||"");else if(b.value==="autoApproveGit")o(A=>({...A,autoApproveGit:!A.autoApproveGit,sandboxPreset:"Custom"}));else if(b.value==="autoDisallow")T("autoDisallowCommands"),I(e.autoDisallowCommands||"");else if(b.value==="apiTier")n("apiTier");else if(b.value==="aiProvider")n("selectProvider");else if(b.value==="autoDelete"){let A=["1d","7d","30d"],Q=(A.indexOf(e.autoDeleteHistory||"30d")+1)%A.length;o(j=>({...j,autoDeleteHistory:A[Q]}))}else if(b.value==="autoUpdate")o(A=>({...A,autoUpdate:!A.autoUpdate}));else if(b.value==="externalData")if(!e.useExternalData)s({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:e.externalDataPath||""}),n("input");else{let A={...e,useExternalData:!1};o(A),r({systemSettings:A,apiTier:t,quotas:l}),u(F=>[...F,{id:Date.now(),role:"system",text:"\u{1F3E0} [STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else b.value==="updateManager"?n("updateManager"):b.value==="parserDownload"&&n("parserDownload")};return Te.createElement(Ot,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%",minHeight:32},Te.createElement(Ot,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"magenta",width:"100%"},Te.createElement(Kt,{color:"magenta",bold:!0},"\u{1F527} SYSTEM CONFIGURATION")),Te.createElement(Ot,{flexDirection:"row",width:"100%",minHeight:26},Te.createElement(Ot,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:m==="categories"?"cyan":"gray",padding:1,paddingY:0},Te.createElement(Ot,{marginBottom:1},Te.createElement(Kt,{color:m==="categories"?"cyan":"white",bold:!0,underline:!0},"CATEGORIES")),an.map((b,A)=>{let F=a===A,Q=b.id==="exit";return Te.createElement(Ot,{key:b.id,marginTop:Q?17:0,backgroundColor:F?m==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},Te.createElement(Kt,{color:F?m==="categories"?"cyan":"yellow":"white",bold:F},F?"\u276F ":" ",b.label))})),Te.createElement(Ot,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:m==="items"?"cyan":"gray",paddingX:1,marginLeft:1,paddingY:0},Te.createElement(Ot,{marginBottom:1},Te.createElement(Kt,{color:m==="items"?"cyan":"white",bold:!0,underline:!0},an[a].label.toUpperCase()," SETTINGS")),R.length>0?(()=>{let b=null,A=[],F=ce=>(ce||"").split(",").map(Le=>Le.trim().toLowerCase()).filter(Boolean),Q=F(e.autoApproveCommands),j=F(e.autoDisallowCommands),Z=F(e.alwaysAskCommands),B=[...Q,...j,...Z],z=new Set(B),mt=_==="security"&&B.length!==z.size;return R.forEach((ce,Le)=>{let Je=m==="items"&&p===Le,ue=ce.label.length,tt=Math.max(2,35-ue),Ye=".".repeat(tt),_e=ft=>_==="security"?(ft.value==="autoExec"||ft.value==="externalAccess")&&ft.status==="ON"?"red":"yellow":ft.status?.startsWith("\u2713")?"green":ft.status?.startsWith("\u26A0")?"yellow":ft.status==="ON"?"green":ft.status==="OFF"?"red":"yellow";ce.section&&ce.section!==b&&(b=ce.section,A.push(Te.createElement(Ot,{key:`sec-hdr-${ce.section}`,marginTop:A.length>0?1:0,marginBottom:0,paddingX:1},Te.createElement(Kt,{color:"magenta",bold:!0,underline:!0},"\u{1F4C2} ",ce.section.toUpperCase()))));let Me=Je&&S&&(S==="alwaysAskCommands"&&ce.value==="alwaysAsk"||S==="autoApproveCommands"&&ce.value==="autoApprove"||S==="autoDisallowCommands"&&ce.value==="autoDisallow"),je=ce.value==="alwaysAsk"||ce.value==="autoApprove"||ce.value==="autoDisallow",ye=ce.value==="parserDownload";A.push(Te.createElement(Ot,{key:ce.value,flexDirection:"column"},Te.createElement(Ot,{backgroundColor:Je&&!Me?"#2a2a2a":void 0,paddingX:2},Te.createElement(Kt,{color:Je?"cyan":"white",bold:Je,underline:ye},Je?"\u276F ":" ",ce.label),!je&&!ye&&Te.createElement(Te.Fragment,null,Te.createElement(Kt,{color:"gray",dimColor:!0},Ye),Te.createElement(Kt,{color:_e(ce),bold:!0},ce.value==="aiProvider"?ce.status:`[ ${ce.status} ]`))),je&&!Me&&ce.status!=="None"&&Te.createElement(Ot,{paddingX:4,marginBottom:1},Te.createElement(Kt,{color:"gray",dimColor:!0},"\u21B3 ",ce.status)),Me&&Te.createElement(Ot,{flexDirection:"column",marginLeft:4,marginBottom:1},Te.createElement(Ot,{paddingX:1,borderStyle:"single",borderColor:"cyan",flexDirection:"row"},Te.createElement(Kt,{color:"cyan",bold:!0},"> "," "),Te.createElement(Xc,{value:w,onChange:I,onSubmit:ft=>{let pt={...e,[S]:ft.trim(),sandboxPreset:"Custom"};o(pt),r({systemSettings:pt,apiTier:t,quotas:l}),T(null)}})),Te.createElement(Kt,{color:"gray",dimColor:!0,italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),_==="other"&&A.push(Te.createElement(Ot,{key:"pty-notice",marginTop:18,paddingX:1},Te.createElement(Kt,{color:Yn?"green":"yellow"},Yn?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),mt&&A.push(Te.createElement(Ot,{key:"conflict-warning",marginTop:1,paddingX:1},Te.createElement(Kt,{color:"red",dimColor:!0,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),A})():Te.createElement(Ot,{paddingX:1},Te.createElement(Kt,{color:"gray",italic:!0},an[a].desc)))),Te.createElement(Ot,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},Te.createElement(Kt,{color:"gray",dimColor:!0,italic:!0},m==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),m==="categories"&&Te.createElement(Kt,{color:"gray",dimColor:!0},an[a].desc)))}var an,ka,Ks,Ia=re(async()=>{await Dr();an=[{id:"memory",label:"\u{1F9E0} Memory",desc:"Manage system context & agent's memory"},{id:"security",label:"\u{1F512} Security",desc:"Configure permissions & data safety"},{id:"updater",label:"\u{1F504} Updater",desc:"Manage application updates"},{id:"other",label:"\u{1F4CB} Other",desc:"Miscellaneous preferences"},{id:"exit",label:"\u{1F6AA} Exit Settings",desc:"Return to chat view"}],ka=e=>{let o=e.autoApproveCommands||"",t=e.autoDisallowCommands||"",n=e.alwaysAskCommands||"",s=e.autoExec===!1&&e.allowExternalAccess===!1&&e.networkAccess===!1&&o===""&&t==="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"&&n==="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"&&e.autoApproveGit===!1,r=e.autoExec===!0&&e.allowExternalAccess===!1&&e.networkAccess!==!1&&o==="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"&&t==="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"&&n==="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"&&e.autoApproveGit===!1,l=e.autoExec===!0&&e.allowExternalAccess===!0&&e.networkAccess!==!1&&o==="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"&&t===""&&n==="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"&&e.autoApproveGit===!0;return s?"Strict":r?"Balanced":l?"Autonomous":e.sandboxPreset||"Custom"},Ks=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import Po,{useState as Vs,useEffect as Kc}from"react";import{Box as sr,Text as ds}from"ink";import qc from"ink-text-input";function zs({initialData:e,onSave:o,onCancel:t}){let[n,s]=Vs(0),[r,l]=Vs(""),[u,f]=Vs(()=>({name:e?.name||"",nickname:e?.nickname||"",instructions:e?.instructions||""})),m=[{key:"name",label:"Enter your Name: "},{key:"nickname",label:"Enter a Nickname (Agent will use this): "},{key:"instructions",label:"System Instructions (Persona overrides): "}];Kc(()=>{let a=m[n].key;l(u[a]||"")},[n,u]);let c=a=>{if(a.trim().toLowerCase()==="/cancel"){t();return}let d=m[n].key,p={...u,[d]:a.trim()};f(p),l(""),n<m.length-1?s(n+1):o(p)};return Po.createElement(sr,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},Po.createElement(sr,{paddingX:1,marginBottom:1},Po.createElement(ds,{color:"magenta",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),Po.createElement(sr,{paddingX:1,flexDirection:"column"},Po.createElement(sr,null,Po.createElement(ds,{color:"cyan",bold:!0},m[n].label),Po.createElement(qc,{value:r,onChange:l,onSubmit:c})),Po.createElement(sr,{marginTop:1},Po.createElement(ds,{color:"gray",dimColor:!0,italic:!0},"Step ",n+1," of ",m.length))),Po.createElement(sr,{paddingX:1,marginTop:1},Po.createElement(ds,{color:"gray",dimColor:!0,italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var Ma=re(()=>{});import ut,{useState as Js}from"react";import{Box as vo,Text as ln,useInput as Vc}from"ink";import zc from"ink-text-input";var Jc,va,Aa=re(()=>{rn();Jc=({question:e,options:o,onResolve:t})=>{let[n,s]=Js(!1),[r,l]=Js(""),[u,f]=Js(0),m=[...o,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];Vc((a,d)=>{if(!n&&((d.leftArrow||d.upArrow)&&f(p=>Math.max(0,p-1)),(d.rightArrow||d.downArrow)&&f(p=>Math.min(m.length-1,p+1)),d.return)){let p=m[u];p.id==="CUSTOM"?s(!0):t(p.label)}});let c=Ie(2);return n?ut.createElement(vo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ut.createElement(vo,{paddingX:1},ut.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),ut.createElement(vo,{marginTop:1,paddingX:1},ut.createElement(ln,{italic:!0,color:"gray"},"Replying to: ",e)),ut.createElement(vo,{marginTop:1,paddingX:1,flexDirection:"row"},ut.createElement(ln,{color:"cyan",bold:!0},"\u{1F4A0} "),ut.createElement(zc,{value:r,onChange:l,onSubmit:()=>t(r)})),ut.createElement(vo,{marginTop:1,paddingX:1,marginBottom:1},ut.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to send)"))):ut.createElement(vo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ut.createElement(vo,{paddingX:1,marginBottom:1},ut.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),ut.createElement(vo,{paddingX:1,marginBottom:1},ut.createElement(ln,{bold:!0,color:"white"},e)),ut.createElement(vo,{flexDirection:"column",width:"100%"},m.map((a,d)=>{let p=d===u;return ut.createElement(vo,{key:a.id,flexDirection:"column",width:"100%",backgroundColor:p?"#2a2a2a":void 0,paddingX:1,marginBottom:d===m.length-1?0:1},ut.createElement(ln,{color:p?"cyan":"white",bold:p},p?"\u276F ":" ",a.label),a.description&&ut.createElement(vo,{marginLeft:4},ut.createElement(ln,{color:"gray",italic:!0,dimColor:!0},a.description)))})),ut.createElement(vo,{paddingX:1,marginTop:1,marginBottom:1},ut.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},va=Jc});var Oa,Da=re(()=>{Oa=(e=!0,o=!0)=>`
112
+ ${I}`)}),m.on("error",p=>{if(l&&r&&p.code==="ENOENT"){let h=Ia(t,!1);return Gs(e,h,t,n,s,!1)}Dt=null,e(`ERROR: Failed to start command [${t}]: ${p.message}`)})}});import Ee,{useState as Fr}from"react";import{Box as Pt,Text as zt,useInput as Xc}from"ink";import Kc from"ink-text-input";function Ks({systemSettings:e,setSystemSettings:o,apiTier:t,setActiveView:n,setInputConfig:s,saveSettings:r,quotas:l,setMessages:u,aiProvider:f}){let[m,c]=Fr("categories"),[a,d]=Fr(0),[p,h]=Fr(0),[E,w]=Fr(null),[T,I]=Fr(""),O=S=>{switch(S){case"memory":return[{label:"Toggle Memory",value:"memory",status:e.memory?"ON":"OFF"}];case"security":return[{label:"Sandbox Preset",value:"sandboxPreset",status:Aa(e),section:"Sandbox"},{label:"YOLO Mode",value:"autoExec",status:e.autoExec?"ON":"OFF",section:"Sandbox"},{label:"External Workspace Access",value:"externalAccess",status:e.allowExternalAccess?"ON":"OFF",section:"Sandbox"},{label:"Network Access (Terminal)",value:"networkAccess",status:e.networkAccess!==!1?"ON":"OFF",section:"Sandbox"},{label:"Always Ask Commands",value:"alwaysAsk",status:Xs(e.alwaysAskCommands),section:"Sandbox"},{label:"Auto Approve Commands",value:"autoApprove",status:Xs(e.autoApproveCommands),section:"Sandbox"},{label:"Auto Disapprove Commands",value:"autoDisallow",status:Xs(e.autoDisallowCommands),section:"Sandbox"},{label:"Auto Approve Git Commits",value:"autoApproveGit",status:e.autoApproveGit?"ON":"OFF",section:"Sandbox"},{label:"Auto-Delete History",value:"autoDelete",status:e.autoDeleteHistory||"30d",section:"Other"},{label:"Save AppData Externally",value:"externalData",status:e.useExternalData?"ON":"OFF",section:"Other"}];case"updater":return[{label:"Auto-Update",value:"autoUpdate",status:e.autoUpdate?"ON":"OFF"},{label:"Preferred Updater",value:"updateManager",status:(e.updateManager||"npm")==="custom"?"Custom":(e.updateManager||"npm").toUpperCase()}];case"other":return[{label:"Current Provider",value:"aiProvider",status:f},{label:"API Tier",value:"apiTier",status:t},{label:"Download Language Parsers",value:"parserDownload",status:"ACTION"}];default:return[]}},P=an[a].id,U=O(P);Xc((S,v)=>{if(E){v.escape&&w(null);return}if(m==="categories")v.upArrow?d(F=>(F-1+an.length)%an.length):v.downArrow?d(F=>(F+1)%an.length):v.return||v.rightArrow?an[a].id==="exit"?n("chat"):(c("items"),h(0)):v.escape&&n("chat");else if(m==="items"){if(v.upArrow)h(F=>(F-1+U.length)%U.length);else if(v.downArrow)h(F=>(F+1)%U.length);else if(v.leftArrow||v.escape)c("categories");else if(v.return){let F=U[p];A(F)}}});let A=S=>{if(S.value==="memory")o(v=>({...v,memory:!v.memory}));else if(S.value==="sandboxPreset"){let v=Aa(e),F=["Autonomous","Balanced","Strict"],Y=(F.indexOf(v)+1)%F.length,Z=F[Y];o(N=>{let J={...N,sandboxPreset:Z};return Z==="Strict"?(J.autoExec=!1,J.allowExternalAccess=!1,J.networkAccess=!1,J.autoApproveCommands="",J.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",J.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",J.autoApproveGit=!1):Z==="Balanced"?(J.autoExec=!0,J.allowExternalAccess=!1,J.networkAccess=!0,J.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",J.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",J.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",J.autoApproveGit=!1):Z==="Autonomous"&&(J.autoExec=!0,J.allowExternalAccess=!0,J.networkAccess=!0,J.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",J.autoDisallowCommands="",J.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",J.autoApproveGit=!0),J})}else if(S.value==="autoExec")e.autoExec?o(v=>({...v,autoExec:!1,sandboxPreset:"Custom"})):e.allowExternalAccess?n("doubleDanger"):n("autoExecDanger");else if(S.value==="externalAccess")e.allowExternalAccess?o(v=>({...v,allowExternalAccess:!1,sandboxPreset:"Custom"})):e.autoExec?n("doubleDanger"):n("externalDanger");else if(S.value==="networkAccess")o(v=>({...v,networkAccess:v.networkAccess===!1,sandboxPreset:"Custom"}));else if(S.value==="alwaysAsk")w("alwaysAskCommands"),I(e.alwaysAskCommands||"");else if(S.value==="autoApprove")w("autoApproveCommands"),I(e.autoApproveCommands||"");else if(S.value==="autoApproveGit")o(v=>({...v,autoApproveGit:!v.autoApproveGit,sandboxPreset:"Custom"}));else if(S.value==="autoDisallow")w("autoDisallowCommands"),I(e.autoDisallowCommands||"");else if(S.value==="apiTier")n("apiTier");else if(S.value==="aiProvider")n("selectProvider");else if(S.value==="autoDelete"){let v=["1d","7d","30d"],V=(v.indexOf(e.autoDeleteHistory||"30d")+1)%v.length;o(Y=>({...Y,autoDeleteHistory:v[V]}))}else if(S.value==="autoUpdate")o(v=>({...v,autoUpdate:!v.autoUpdate}));else if(S.value==="externalData")if(!e.useExternalData)s({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:e.externalDataPath||""}),n("input");else{let v={...e,useExternalData:!1};o(v),r({systemSettings:v,apiTier:t,quotas:l}),u(F=>[...F,{id:Date.now(),role:"system",text:"\u{1F3E0} [STORAGE RESET] Flux Flow will return to default ~/.fluxflow after restart."}]),n("chat")}else S.value==="updateManager"?n("updateManager"):S.value==="parserDownload"&&n("parserDownload")};return Ee.createElement(Pt,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%",minHeight:32},Ee.createElement(Pt,{paddingX:1,paddingY:0,marginBottom:0,borderStyle:"single",borderColor:"magenta",width:"100%"},Ee.createElement(zt,{color:"magenta",bold:!0},"\u{1F527} SYSTEM CONFIGURATION")),Ee.createElement(Pt,{flexDirection:"row",width:"100%",minHeight:26},Ee.createElement(Pt,{flexDirection:"column",width:"30%",borderStyle:"round",borderColor:m==="categories"?"cyan":"gray",padding:1,paddingY:0},Ee.createElement(Pt,{marginBottom:1},Ee.createElement(zt,{color:m==="categories"?"cyan":"white",bold:!0,underline:!0},"CATEGORIES")),an.map((S,v)=>{let F=a===v,V=S.id==="exit";return Ee.createElement(Pt,{key:S.id,marginTop:V?17:0,backgroundColor:F?m==="categories"?"#2a2a2a":"#1e1e1e":void 0,paddingX:1},Ee.createElement(zt,{color:F?m==="categories"?"cyan":"yellow":"white",bold:F},F?"\u276F ":" ",S.label))})),Ee.createElement(Pt,{flexDirection:"column",width:"70%",borderStyle:"round",borderColor:m==="items"?"cyan":"gray",paddingX:1,marginLeft:1,paddingY:0},Ee.createElement(Pt,{marginBottom:1},Ee.createElement(zt,{color:m==="items"?"cyan":"white",bold:!0,underline:!0},an[a].label.toUpperCase()," SETTINGS")),U.length>0?(()=>{let S=null,v=[],F=de=>(de||"").split(",").map($e=>$e.trim().toLowerCase()).filter(Boolean),V=F(e.autoApproveCommands),Y=F(e.autoDisallowCommands),Z=F(e.alwaysAskCommands),N=[...V,...Y,...Z],J=new Set(N),ft=P==="security"&&N.length!==J.size;return U.forEach((de,$e)=>{let qe=m==="items"&&p===$e,me=de.label.length,Ze=Math.max(2,35-me),je=".".repeat(Ze),Be=pt=>P==="security"?(pt.value==="autoExec"||pt.value==="externalAccess")&&pt.status==="ON"?"red":"yellow":pt.status?.startsWith("\u2713")?"green":pt.status?.startsWith("\u26A0")?"yellow":pt.status==="ON"?"green":pt.status==="OFF"?"red":"yellow";de.section&&de.section!==S&&(S=de.section,v.push(Ee.createElement(Pt,{key:`sec-hdr-${de.section}`,marginTop:v.length>0?1:0,marginBottom:0,paddingX:1},Ee.createElement(zt,{color:"magenta",bold:!0,underline:!0},"\u{1F4C2} ",de.section.toUpperCase()))));let Le=qe&&E&&(E==="alwaysAskCommands"&&de.value==="alwaysAsk"||E==="autoApproveCommands"&&de.value==="autoApprove"||E==="autoDisallowCommands"&&de.value==="autoDisallow"),Ge=de.value==="alwaysAsk"||de.value==="autoApprove"||de.value==="autoDisallow",Se=de.value==="parserDownload";v.push(Ee.createElement(Pt,{key:de.value,flexDirection:"column"},Ee.createElement(Pt,{backgroundColor:qe&&!Le?"#2a2a2a":void 0,paddingX:2},Ee.createElement(zt,{color:qe?"cyan":"white",bold:qe,underline:Se},qe?"\u276F ":" ",de.label),!Ge&&!Se&&Ee.createElement(Ee.Fragment,null,Ee.createElement(zt,{color:"gray",dimColor:!0},je),Ee.createElement(zt,{color:Be(de),bold:!0},de.value==="aiProvider"?de.status:`[ ${de.status} ]`))),Ge&&!Le&&de.status!=="None"&&Ee.createElement(Pt,{paddingX:4,marginBottom:1},Ee.createElement(zt,{color:"gray",dimColor:!0},"\u21B3 ",de.status)),Le&&Ee.createElement(Pt,{flexDirection:"column",marginLeft:4,marginBottom:1},Ee.createElement(Pt,{paddingX:1,borderStyle:"single",borderColor:"cyan",flexDirection:"row"},Ee.createElement(zt,{color:"cyan",bold:!0},"> "," "),Ee.createElement(Kc,{value:T,onChange:I,onSubmit:pt=>{let ht={...e,[E]:pt.trim(),sandboxPreset:"Custom"};o(ht),r({systemSettings:ht,apiTier:t,quotas:l}),w(null)}})),Ee.createElement(zt,{color:"gray",dimColor:!0,italic:!0}," Comma separated \u2022 Press Enter to save, Esc to cancel"))))}),P==="other"&&v.push(Ee.createElement(Pt,{key:"pty-notice",marginTop:18,paddingX:1},Ee.createElement(zt,{color:Wn?"green":"yellow"},Wn?"\u2713 Advance Interactive Terminal Supported":"\u26A0 Interactive Terminal is Limited"))),ft&&v.push(Ee.createElement(Pt,{key:"conflict-warning",marginTop:1,paddingX:1},Ee.createElement(zt,{color:"red",dimColor:!0,italic:!0},"* Conflicting commands will be ignored and defaulted to highest priority"))),v})():Ee.createElement(Pt,{paddingX:1},Ee.createElement(zt,{color:"gray",italic:!0},an[a].desc)))),Ee.createElement(Pt,{paddingX:1,marginTop:0,flexDirection:"row",justifyContent:"space-between"},Ee.createElement(zt,{color:"gray",dimColor:!0,italic:!0},m==="categories"?"\u25B2\u25BC Select Category \u2022 Enter/\u25BA to configure":"\u25B2\u25BC Select Option \u2022 Enter to Toggle \u2022 \u25C4/ESC to go back"),m==="categories"&&Ee.createElement(zt,{color:"gray",dimColor:!0},an[a].desc)))}var an,Aa,Xs,Ma=re(async()=>{await Or();an=[{id:"memory",label:"\u{1F9E0} Memory",desc:"Manage system context & agent's memory"},{id:"security",label:"\u{1F512} Security",desc:"Configure permissions & data safety"},{id:"updater",label:"\u{1F504} Updater",desc:"Manage application updates"},{id:"other",label:"\u{1F4CB} Other",desc:"Miscellaneous preferences"},{id:"exit",label:"\u{1F6AA} Exit Settings",desc:"Return to chat view"}],Aa=e=>{let o=e.autoApproveCommands||"",t=e.autoDisallowCommands||"",n=e.alwaysAskCommands||"",s=e.autoExec===!1&&e.allowExternalAccess===!1&&e.networkAccess===!1&&o===""&&t==="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"&&n==="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"&&e.autoApproveGit===!1,r=e.autoExec===!0&&e.allowExternalAccess===!1&&e.networkAccess!==!1&&o==="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"&&t==="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"&&n==="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"&&e.autoApproveGit===!1,l=e.autoExec===!0&&e.allowExternalAccess===!0&&e.networkAccess!==!1&&o==="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"&&t===""&&n==="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"&&e.autoApproveGit===!0;return s?"Strict":r?"Balanced":l?"Autonomous":e.sandboxPreset||"Custom"},Xs=e=>!e||e.trim()===""?"None":e.length>40?e.substring(0,40)+"...":e});import Po,{useState as Vs,useEffect as Vc}from"react";import{Box as or,Text as cs}from"ink";import qc from"ink-text-input";function qs({initialData:e,onSave:o,onCancel:t}){let[n,s]=Vs(0),[r,l]=Vs(""),[u,f]=Vs(()=>({name:e?.name||"",nickname:e?.nickname||"",instructions:e?.instructions||""})),m=[{key:"name",label:"Enter your Name: "},{key:"nickname",label:"Enter a Nickname (Agent will use this): "},{key:"instructions",label:"System Instructions (Persona overrides): "}];Vc(()=>{let a=m[n].key;l(u[a]||"")},[n,u]);let c=a=>{if(a.trim().toLowerCase()==="/cancel"){t();return}let d=m[n].key,p={...u,[d]:a.trim()};f(p),l(""),n<m.length-1?s(n+1):o(p)};return Po.createElement(or,{borderStyle:"round",borderColor:"gray",padding:0,marginTop:1,flexShrink:0,flexDirection:"column",width:"100%"},Po.createElement(or,{paddingX:1,marginBottom:1},Po.createElement(cs,{color:"magenta",bold:!0},"\u{1F464} DEVELOPER PROFILE CONFIGURATION")),Po.createElement(or,{paddingX:1,flexDirection:"column"},Po.createElement(or,null,Po.createElement(cs,{color:"cyan",bold:!0},m[n].label),Po.createElement(qc,{value:r,onChange:l,onSubmit:c})),Po.createElement(or,{marginTop:1},Po.createElement(cs,{color:"gray",dimColor:!0,italic:!0},"Step ",n+1," of ",m.length))),Po.createElement(or,{paddingX:1,marginTop:1},Po.createElement(cs,{color:"gray",dimColor:!0,italic:!0},"(Enter to submit \u2022 Type /cancel to abort)")))}var va=re(()=>{});import dt,{useState as zs}from"react";import{Box as Ao,Text as ln,useInput as zc}from"ink";import Jc from"ink-text-input";var Qc,Da,Oa=re(()=>{rn();Qc=({question:e,options:o,onResolve:t})=>{let[n,s]=zs(!1),[r,l]=zs(""),[u,f]=zs(0),m=[...o,{id:"CUSTOM",label:"Suggest something else...",description:"Provide a custom response"}];zc((a,d)=>{if(!n&&((d.leftArrow||d.upArrow)&&f(p=>Math.max(0,p-1)),(d.rightArrow||d.downArrow)&&f(p=>Math.min(m.length-1,p+1)),d.return)){let p=m[u];p.id==="CUSTOM"?s(!0):t(p.label)}});let c=Oe(2);return n?dt.createElement(Ao,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},dt.createElement(Ao,{paddingX:1},dt.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} SUGGEST SOMETHING ELSE")),dt.createElement(Ao,{marginTop:1,paddingX:1},dt.createElement(ln,{italic:!0,color:"gray"},"Replying to: ",e)),dt.createElement(Ao,{marginTop:1,paddingX:1,flexDirection:"row"},dt.createElement(ln,{color:"cyan",bold:!0},"\u{1F4A0} "),dt.createElement(Jc,{value:r,onChange:l,onSubmit:()=>t(r)})),dt.createElement(Ao,{marginTop:1,paddingX:1,marginBottom:1},dt.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to send)"))):dt.createElement(Ao,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},dt.createElement(Ao,{paddingX:1,marginBottom:1},dt.createElement(ln,{color:"cyan",bold:!0},"\u{1F4AC} AGENT REQUEST: ACTION REQUIRED")),dt.createElement(Ao,{paddingX:1,marginBottom:1},dt.createElement(ln,{bold:!0,color:"white"},e)),dt.createElement(Ao,{flexDirection:"column",width:"100%"},m.map((a,d)=>{let p=d===u;return dt.createElement(Ao,{key:a.id,flexDirection:"column",width:"100%",backgroundColor:p?"#2a2a2a":void 0,paddingX:1,marginBottom:d===m.length-1?0:1},dt.createElement(ln,{color:p?"cyan":"white",bold:p},p?"\u276F ":" ",a.label),a.description&&dt.createElement(Ao,{marginLeft:4},dt.createElement(ln,{color:"gray",italic:!0,dimColor:!0},a.description)))})),dt.createElement(Ao,{paddingX:1,marginTop:1,marginBottom:1},dt.createElement(ln,{color:"gray",dimColor:!0,italic:!0},"(Use Arrows to navigate, Enter to confirm)")))},Da=Qc});var La,Fa=re(()=>{La=(e=!0,o=!0)=>`
113
113
  Your tool syntax is: '[tool:functions.ToolName(args...)]'
114
114
 
115
115
  -- CHAT MANAGEMENT TOOLS (MUST CALL THESE 2 TOOLS ALWAYS) --
@@ -134,7 +134,7 @@ Explicit Triggers for permanent memory:
134
134
 
135
135
  Usage Rules:
136
136
  - Frequency for 'user' action: Based on explicit triggers.
137
- - IF YOU WANT TO SAVE SOMETHING, BUT SIMILAR MEMORY ALREADY EXISTS, USE THE UPDATE METHOD NOT THE ADD METHOD`:""}`.trim()});var Qs,La=re(()=>{Qs={xHigh:`EFFORT LEVEL: MAX
137
+ - IF YOU WANT TO SAVE SOMETHING, BUT SIMILAR MEMORY ALREADY EXISTS, USE THE UPDATE METHOD NOT THE ADD METHOD`:""}`.trim()});var Js,$a=re(()=>{Js={xHigh:`EFFORT LEVEL: MAX
138
138
  Think in a continuous, relentless analytical monologue within <think>...</think>. Engage in adversarial self interrogation that treats every assumption as hostile until proven:
139
139
  Deconstruct requirements into atomic invariants. Trace every implicit dependency, side effect, and state mutation. Map the entire dependency graph and identify circular dependencies or tight coupling before they manifest
140
140
  Evaluate algorithmic complexity (time/space) for every operation. Consider memory models, cache locality, and allocation patterns. For concurrent systems, reason through race conditions, deadlocks, and memory ordering
@@ -188,26 +188,26 @@ RULES:
188
188
  - Suitable for simple requests/greetings`,Off:`EFFORT LEVEL: INSTANT
189
189
  No thinking. Immediate response
190
190
  RULES:
191
- - Verify ALL imports and system stability, AVOID ANY Syntax errors, re-read TOOL RESULTS/files to verify`}});import Zc from"fs";var Zs,Fa,$a,Pa,_a=re(async()=>{await js();Da();La();Zs=null,Fa=(e="",o="",t=!0,n=!1)=>{if(!t)return"";let s=e?.length>0&&!n?`-- RECENT CONTEXT FROM OTHER CHATS (PRIORITY: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
191
+ - Verify ALL imports and system stability, AVOID ANY Syntax errors, re-read TOOL RESULTS/files to verify`}});import eu from"fs";var Qs,Pa,_a,Na,Ba=re(async()=>{await Ys();Fa();$a();Qs=null,Pa=(e="",o="",t=!0,n=!1)=>{if(!t)return"";let s=e?.length>0&&!n?`-- RECENT CONTEXT FROM OTHER CHATS (PRIORITY: DYNAMIC-LOW, FOCUS: Chat Context > Recent) --
192
192
  ${e}`:"",l=[o?.length>0?`--- SAVED MEMORIES (PRIORITY: MEDIUM, USER PREFERENCES) ---
193
193
  ${o}`:"",s].filter(u=>u.length>0);return l.length>0?`[SYSTEM CONTEXT]
194
194
  ${l.join(`
195
195
 
196
196
  `)}
197
- `:""},$a=(e,o,t,n,s=!0,r=!1,l="Google",u=!1)=>{let f="";if(o!=="GEM"){let w=o;o==="Fast"&&(w="Off"),o==="Low"&&(w="Minimal"),o==="Standard"&&(w="Medium"),(o==="xHigh"||o==="Max")&&(w="xHigh"),f=Qs[w]||Qs.Medium}let m=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",c=e.instructions&&e.instructions?.length>0?`User Instructions: ${e.instructions}
197
+ `:""},_a=(e,o,t,n,s=!0,r=!1,l="Google",u=!1)=>{let f="";if(o!=="GEM"){let T=o;o==="Fast"&&(T="Off"),o==="Low"&&(T="Minimal"),o==="Standard"&&(T="Medium"),(o==="xHigh"||o==="Max")&&(T="xHigh"),f=Js[T]||Js.Medium}let m=process.platform==="win32"?"Windows":process.platform==="darwin"?"macOS":"Linux",c=e.instructions&&e.instructions?.length>0?`User Instructions: ${e.instructions}
198
198
 
199
199
  `:"",a=e.nickname&&e.nickname?.length>0?`User Nickname: ${e.nickname}
200
200
  ${c.length?"":`
201
201
  `}`:"",d=e.name&&e.name?.length>0?`User Name: ${e.name}
202
202
  ${a.length||c.length?"":`
203
- `}`:"",p=process.cwd(),h=(()=>{let w=process.cwd().toLowerCase();if(process.platform==="win32"){let I=process.env.SystemRoot?.toLowerCase()||"c:\\windows",L=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",_=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return w.startsWith(I)||w.startsWith(L)||w.startsWith(_)}else return w==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(L=>w.startsWith(L))})(),S=[{name:"Fluxflow.md",desc:"HIGH PRIORITY. Overrides other files"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(r||Zs===null){let w=S.filter(I=>Zc.existsSync(I.name));Zs=t==="Flux"&&w.length>0?`
203
+ `}`:"",p=process.cwd(),h=(()=>{let T=process.cwd().toLowerCase();if(process.platform==="win32"){let I=process.env.SystemRoot?.toLowerCase()||"c:\\windows",O=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",P=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return T.startsWith(I)||T.startsWith(O)||T.startsWith(P)}else return T==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(O=>T.startsWith(O))})(),E=[{name:"Fluxflow.md",desc:"HIGH PRIORITY. Overrides other files"},{name:"README.md",desc:"Goals"},{name:"Agent.md",desc:"Standards"},{name:"Skills.md",desc:"Workflows"},{name:"design.md",desc:"UI/UX"},{name:"architecture.md",desc:"System Structure"}];if(r||Qs===null){let T=E.filter(I=>eu.existsSync(I.name));Qs=t==="Flux"&&T.length>0?`
204
204
  -- PROJECT CONTEXT (Source of Truth) --
205
- ${w.map(I=>`- ${I.name}: ${I.desc}`).join(`
205
+ ${T.map(I=>`- ${I.name}: ${I.desc}`).join(`
206
206
  `)}
207
207
  Check these first; These Files > Training Data. Safety rules apply
208
- `:""}let T=Zs;return`${d}${a}${c}[SYSTEM]
208
+ `:""}let w=Qs;return`${d}${a}${c}[SYSTEM]
209
209
  Identity: Flux Flow (by Kushal Roy Chowdhury). Conversational, Sassy${t==="Flux"?", Respectful":", Friendly, Humorous, Sarcastic"}, CLI Agent
210
- Mode: ${t}${o!=="Fast"?" (Thinking Mode)":""}. ${t==="Flux"?"Logical, Highly Detailed, Task-Driven. Prioritizes scalable file/folder structures, modular architecture, clean code abstractions, step-by-step execution. Industry standard latest coding practices/libraries, clean code, Double Check Imports, Client-Server Sync":"Concise"}
210
+ Mode: ${t}${o!=="Fast"?" (Thinking)":""}. ${t==="Flux"?"Logical, Highly Detailed, Task-Driven. Prioritizes scalable file/folder structures, modular architecture, clean code abstractions, step-by-step execution. Industry standard latest coding practices/libraries, clean code, Double Check Imports, Client-Server Sync":"Concise"}
211
211
 
212
212
  -- AGENT RULES (PRIORITY: HIGH) --
213
213
  - **MANDATORY: MUST END EVERY RESPONSE WITH [[END]]**
@@ -224,8 +224,8 @@ CRITICAL THINKING POLICY
224
224
  - ALWAYS use <think> ... </think> before responding, even with simple queries/greetings
225
225
  - ${o==="Low"||o==="Medium"||o==="Fast"?"C":"Interrogate approaches adversarially, but c"}ommit once best solution is determined through analysis. Avoid spiraling after reaching decision point
226
226
  `:""}`:""}`:""}
227
- ${Ea(t,m,l.toLowerCase()==="deepseek"?!1:u,l)}
228
- ${T}
227
+ ${Ca(t,m,l.toLowerCase()==="deepseek"?!1:u,l)}
228
+ ${w}
229
229
  -- MEMORY RULES --
230
230
  - Memory: ${s?"Subtly Personalize. Auto Saves":"OFF. Decline Remembering Memories"}
231
231
  - Temporal Awareness: RELATIVE TIME REFERENCE eg. few mins ago
@@ -238,9 +238,8 @@ PROTECTED DIRECTORY: ASK BEFORE MODIFYING`:""}
238
238
 
239
239
  -- FORMATTING --
240
240
  - GFM Supported
241
- - NO EMOJI AT END OF RESPONSE
242
241
  - NO LaTeX${t==="Flux"?"":". Kaomojis"}
243
- [/SYSTEM]`.trim()},Pa=(e="",o=!0,t=!0)=>`${e?`-- CURRENT SAVED USER MEMORIES --
242
+ [/SYSTEM]`.trim()},Na=(e="",o=!0,t=!0)=>`${e?`-- CURRENT SAVED USER MEMORIES --
244
243
  ${e}
245
244
  -------------------------------------------------
246
245
 
@@ -259,58 +258,58 @@ YOU ARE A SILENT BACKGROUND SYSTEM PROCESS. YOU HAVE NO MOUTH. YOUR ONLY OUTPUT
259
258
  YOUR JOB: Analyze the 'User prompt' and 'Agent Raws' to extract facts for long-term memory or handle system tasks.
260
259
  ${o?"If user tell something that is important (like, hobbies, preferences, facts about user, hates, likes, etc) to know user better over time, use long term memory tools.":""}
261
260
 
262
- ${Oa(o,t)}
261
+ ${La(o,t)}
263
262
 
264
263
  Current date and Time: ${new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",hour12:!0})}.
265
- === END SYSTEM PROMPT ===`.trim()});import bo from"fs-extra";import jn from"path";var cn,kt,un=re(()=>{Bt();Lo();bo.ensureDirSync(wn);cn=null,kt={async startTransaction(e,o){cn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:o.trim(),changes:[],reverted:!1}},async recordFileChange(e,o=null){if(!cn||cn.changes.some(l=>l.filePath===e))return;let n=await bo.pathExists(e),s=n&&!o||o?"update":"create";!n&&!o&&(s="create");let r=null;if(n||o){s="update";let l=jn.basename(e);r=`${cn.id}_${l}.bak`;let u=jn.join(wn,cn.chatId);await bo.ensureDir(u);let f=jn.join(u,r),m=o!==null?o:await bo.readFile(e,"utf8"),c=Cr(m);await bo.writeFile(f,c,"utf8")}cn.changes.push({filePath:e,type:s,backupFile:r})},async commitTransaction(){if(!cn)return;let e=xe(nn,[]);if(e.push(cn),e.length>512e3){let o=e.shift();if(o.changes){for(let t of o.changes)if(t.backupFile){let n=jn.join(wn,o.chatId,t.backupFile);await bo.remove(n)}}}ke(nn,e),cn=null},async rollbackToBefore(e){let o=xe(nn,null);if(!o)throw new Error("No transaction ledger found.");let t=o.findIndex(u=>u.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let n=o[t].chatId,s=o[t].prompt,r=o.slice(t).filter(u=>u.chatId===n&&!u.reverted).reverse();for(let u of r){for(let f of[...u.changes].reverse())if(f.type==="create")await bo.pathExists(f.filePath)&&await bo.remove(f.filePath);else if(f.type==="update"){let m=jn.join(wn,u.chatId,f.backupFile);if(await bo.pathExists(m)){let c=await bo.readFile(m,"utf8"),a=Sn(c);await bo.writeFile(f.filePath,a,"utf8")}}u.reverted=!0}for(let u of r)for(let f of u.changes)if(f.backupFile){let m=jn.join(wn,u.chatId,f.backupFile);await bo.remove(m)}let l=o.filter(u=>!r.some(f=>f.id===u.id));return ke(nn,l),{success:!0,chatId:n,targetPrompt:s}},async getChatHistory(e){try{return xe(nn,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{let o=jn.join(wn,e);await bo.remove(o);let t=xe(nn,[]),n=t.length;t=t.filter(s=>s.chatId!==e),t.length!==n&&ke(nn,t)}catch{}}}});import Xo from"fs-extra";import eu from"path";import{nanoid as tu}from"nanoid";var Na,ei,_o,ms,Ba,ti,oi,Ua,ou,nu,Ra,Wa,$r=re(()=>{Lo();Bt();un();Na=Promise.resolve(),ei=e=>{let o=Na.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Na=o.catch(()=>{}),o},_o=async()=>{if(await Xo.pathExists(Rn))try{return xe(Rn,{})}catch{return{}}return{}},ms=async(e,o,t)=>ei(async()=>{let n=await _o(),s=n[e],r=(t||[]).filter(u=>!u.isUpdateNotification&&!u.isMeta),l=o||(s?s.name:`Session ${e.slice(-6)}`);n[e]={name:l,messages:r,updatedAt:Date.now()},ke(Rn,n)}),Ba=async(e,o)=>ei(async()=>{let t=await _o();t[e]?(t[e].name=o,t[e].updatedAt=Date.now()):t[e]={name:o,messages:[],updatedAt:Date.now()},ke(Rn,t)}),ti=async e=>ei(async()=>{let o=await _o();delete o[e],ke(Rn,o);let t=xe(Eo,{});t[e]&&(delete t[e],ke(Eo,t));let n=xe(Go,{});return n[e]&&(delete n[e],ke(Go,n)),await kt.deleteChatBackups(e),o}),oi=()=>`flow-${tu(6)}`,Ua=async e=>{if(!e||e==="Never")return;let o=parseInt(e);if(isNaN(o))return;let t=await _o(),n=Date.now(),s=o*24*60*60*1e3,r=0;for(let l in t){let u=t[l];u.updatedAt&&n-u.updatedAt>s&&(await ti(l),r++)}return r},ou=e=>{let o=e.replace(/[\[\]]/g,"").trim(),t=new Date(o);if(!isNaN(t.getTime()))return t.getTime();let n=o.split(/,\s*|\s+/);if(n.length===0)return null;let s=n[0],r=n[1]||"",l=n[2]||"",u=s.split(/[-/.]/).map(Number);if(u.length!==3)return null;let f,m,c;if(u[0]>1e3)f=u[0],m=u[1],c=u[2];else if(u[2]>1e3)f=u[2],u[0]>12?(c=u[0],m=u[1]):u[1]>12?(c=u[1],m=u[0]):(m=u[0],c=u[1]);else return null;let a=0,d=0,p=0;if(r){let S=r.split(":").map(Number);a=S[0]||0,d=S[1]||0,p=S[2]||0,l.toLowerCase()==="pm"&&a<12?a+=12:l.toLowerCase()==="am"&&a===12&&(a=0)}let h=new Date(f,m-1,c,a,d,p);return isNaN(h.getTime())?null:h.getTime()},nu=async e=>{try{if(!await Xo.pathExists(e))return;let o=await Xo.readFile(e,"utf8");if(!o.trim())return;let t=o.split(`
264
+ === END SYSTEM PROMPT ===`.trim()});import So from"fs-extra";import Yn from"path";var cn,kt,un=re(()=>{Yt();Lo();So.ensureDirSync(hn);cn=null,kt={async startTransaction(e,o){cn={id:`tx_prompt_${Date.now()}`,chatId:e,timestamp:new Date().toISOString(),prompt:o.trim(),changes:[],reverted:!1}},async recordFileChange(e,o=null){if(!cn||cn.changes.some(l=>l.filePath===e))return;let n=await So.pathExists(e),s=n&&!o||o?"update":"create";!n&&!o&&(s="create");let r=null;if(n||o){s="update";let l=Yn.basename(e);r=`${cn.id}_${l}.bak`;let u=Yn.join(hn,cn.chatId);await So.ensureDir(u);let f=Yn.join(u,r),m=o!==null?o:await So.readFile(e,"utf8"),c=Cr(m);await So.writeFile(f,c,"utf8")}cn.changes.push({filePath:e,type:s,backupFile:r})},async commitTransaction(){if(!cn)return;let e=Te(on,[]);if(e.push(cn),e.length>512e3){let o=e.shift();if(o.changes){for(let t of o.changes)if(t.backupFile){let n=Yn.join(hn,o.chatId,t.backupFile);await So.remove(n)}}}De(on,e),cn=null},async rollbackToBefore(e){let o=Te(on,null);if(!o)throw new Error("No transaction ledger found.");let t=o.findIndex(u=>u.id===e);if(t===-1)throw new Error(`Transaction [${e}] not found.`);let n=o[t].chatId,s=o[t].prompt,r=o.slice(t).filter(u=>u.chatId===n&&!u.reverted).reverse();for(let u of r){for(let f of[...u.changes].reverse())if(f.type==="create")await So.pathExists(f.filePath)&&await So.remove(f.filePath);else if(f.type==="update"){let m=Yn.join(hn,u.chatId,f.backupFile);if(await So.pathExists(m)){let c=await So.readFile(m,"utf8"),a=xn(c);await So.writeFile(f.filePath,a,"utf8")}}u.reverted=!0}for(let u of r)for(let f of u.changes)if(f.backupFile){let m=Yn.join(hn,u.chatId,f.backupFile);await So.remove(m)}let l=o.filter(u=>!r.some(f=>f.id===u.id));return De(on,l),{success:!0,chatId:n,targetPrompt:s}},async getChatHistory(e){try{return Te(on,[]).filter(t=>t.chatId===e&&!t.reverted)}catch{return[]}},async deleteChatBackups(e){try{let o=Yn.join(hn,e);await So.remove(o);let t=Te(on,[]),n=t.length;t=t.filter(s=>s.chatId!==e),t.length!==n&&De(on,t)}catch{}}}});import Go from"fs-extra";import tu from"path";import{nanoid as ou}from"nanoid";var Ua,Zs,_o,us,Ra,ei,ti,Wa,nu,ru,Ya,ja,$r=re(()=>{Lo();Yt();un();Ua=Promise.resolve(),Zs=e=>{let o=Ua.then(async()=>{try{return await e()}catch(t){throw console.error("Lock Operation Failed:",t),t}});return Ua=o.catch(()=>{}),o},_o=async()=>{if(await Go.pathExists(Un))try{return Te(Un,{})}catch{return{}}return{}},us=async(e,o,t)=>Zs(async()=>{let n=await _o(),s=n[e],r=(t||[]).filter(u=>!u.isUpdateNotification&&!u.isMeta),l=o||(s?s.name:`Session ${e.slice(-6)}`);n[e]={name:l,messages:r,updatedAt:Date.now()},De(Un,n)}),Ra=async(e,o)=>Zs(async()=>{let t=await _o();t[e]?(t[e].name=o,t[e].updatedAt=Date.now()):t[e]={name:o,messages:[],updatedAt:Date.now()},De(Un,t)}),ei=async e=>Zs(async()=>{let o=await _o();delete o[e],De(Un,o);let t=Te(To,{});t[e]&&(delete t[e],De(To,t));let n=Te(Yo,{});return n[e]&&(delete n[e],De(Yo,n)),await kt.deleteChatBackups(e),o}),ti=()=>`flow-${ou(6)}`,Wa=async e=>{if(!e||e==="Never")return;let o=parseInt(e);if(isNaN(o))return;let t=await _o(),n=Date.now(),s=o*24*60*60*1e3,r=0;for(let l in t){let u=t[l];u.updatedAt&&n-u.updatedAt>s&&(await ei(l),r++)}return r},nu=e=>{let o=e.replace(/[\[\]]/g,"").trim(),t=new Date(o);if(!isNaN(t.getTime()))return t.getTime();let n=o.split(/,\s*|\s+/);if(n.length===0)return null;let s=n[0],r=n[1]||"",l=n[2]||"",u=s.split(/[-/.]/).map(Number);if(u.length!==3)return null;let f,m,c;if(u[0]>1e3)f=u[0],m=u[1],c=u[2];else if(u[2]>1e3)f=u[2],u[0]>12?(c=u[0],m=u[1]):u[1]>12?(c=u[1],m=u[0]):(m=u[0],c=u[1]);else return null;let a=0,d=0,p=0;if(r){let E=r.split(":").map(Number);a=E[0]||0,d=E[1]||0,p=E[2]||0,l.toLowerCase()==="pm"&&a<12?a+=12:l.toLowerCase()==="am"&&a===12&&(a=0)}let h=new Date(f,m-1,c,a,d,p);return isNaN(h.getTime())?null:h.getTime()},ru=async e=>{try{if(!await Go.pathExists(e))return;let o=await Go.readFile(e,"utf8");if(!o.trim())return;let t=o.split(`
266
265
  `),n=[],s=null,r=/^\s*(?:DEBUG|ERROR|SEARCH|PUPPETEER)\b/i;for(let a of t)r.test(a)?(s&&n.push(s),s={header:a,body:[]}):s?s.body.push(a):n.push({header:a,body:[]});s&&n.push(s);let l=10080*60*1e3,u=Date.now(),f=[],m=/(\d{1,4}[-/.]\d{1,4}[-/.]\d{1,4}(?:,\s*|\s+)?(?:\d{1,2}:\d{2}:\d{2}(?:\s*[aApP][mM])?)?)/;for(let a of n){let d=a.header+(a.body.length>0?`
267
266
  `+a.body.join(`
268
- `):""),p=d.match(m);if(p){let h=ou(p[1]);if(h&&u-h>l)continue}f.push(d)}let c=f.join(`
269
- `).trim();c?await Xo.writeFile(e,c+`
270
- `,"utf8"):await Xo.writeFile(e,"","utf8")}catch{}},Ra=async e=>{try{if(!await Xo.pathExists(e))return;let o=async t=>{let n=await Xo.readdir(t);for(let s of n){let r=eu.join(t,s);(await Xo.stat(r)).isDirectory()?(await o(r),(await Xo.readdir(r)).length===0&&await Xo.remove(r)):s.endsWith(".log")&&await nu(r)}};await o(e)}catch{}},Wa=(e,o=4)=>{if(e.length<=1)return e;let t=e[0],n=e.slice(1),s=o*2,r=n.slice(s);return[t,...r]}});import ze from"fs-extra";import Ko from"path";import ni from"os";var ru,dn,su,Tt,vn,Ya,fs,ri,ja,si,ii,Ga,Ha,An,qo,Co,ai,li,Xa,Ka,ps,qa,hs=re(()=>{Bt();Lo();ru=()=>{if(process.platform==="win32"){let o=process.env.LOCALAPPDATA||Ko.join(ni.homedir(),"AppData","Local");return Ko.join(o,"FxFl","backups","backup.json")}if(process.platform==="darwin")return Ko.join(ni.homedir(),"Library","Application Support","FxFl","backups","backup.json");let e=process.env.XDG_DATA_HOME||Ko.join(ni.homedir(),".local","share");return Ko.join(e,"fxfl","backups","backup.json")},dn=ru(),su=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),Tt=null,vn=null,Ya=0,fs=!1,ri={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},ja=async()=>{let e=new Date().toISOString().split("T")[0],o=Ht+".tmp",t=null,n=null;try{if(await ze.exists(o)){let r=(await ze.readFile(o,"utf8")).trim(),l=null;if(r.startsWith("{")||r.startsWith("[")?l=JSON.parse(r):l=JSON.parse(Sn(r)),l&&l.date&&l.stats){t=l;try{await ze.rename(o,Ht)}catch{}}else try{await ze.remove(o)}catch{}}}catch{try{await ze.remove(o)}catch{}}if(!t)try{if(await ze.exists(Ht)){let r=(await ze.readFile(Ht,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?t=JSON.parse(r):t=JSON.parse(Sn(r))}}catch{}try{if(await ze.exists(dn)){let r=(await ze.readFile(dn,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?n=JSON.parse(r):n=JSON.parse(Sn(r))}}catch{}let s=null;if(t&&n)if(t.saveId!==n.saveId){s=t;try{await ze.ensureDir(Ko.dirname(dn)),await ze.copy(Ht,dn)}catch{}}else s=t;else if(t&&!n){s=t;try{await ze.ensureDir(Ko.dirname(dn)),await ze.copy(Ht,dn)}catch{}}else if(!t&&n){s=n;try{await ze.ensureDir(Ko.dirname(Ht)),await ze.copy(dn,Ht)}catch{}}if(s&&s.date===e&&s.stats){let r={...ri,...s.stats};return Array.isArray(r.imageCalls)||(r.imageCalls=[]),{...s,stats:r}}return{date:e,stats:{...ri}}},si=async()=>{if(!(!fs||!Tt))try{await ze.ensureDir(Ko.dirname(Ht));let e=null;try{if(await ze.exists(Ht)){let s=(await ze.readFile(Ht,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(Sn(s))}}catch{}if(e&&e.date===Tt.date&&e.stats){for(let s in Tt.stats)if(e.stats[s]!==void 0)if(Array.isArray(Tt.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],l=Tt.stats[s],u=new Map;for(let f of[...r,...l])f&&f.timestamp&&u.set(f.timestamp,f);Tt.stats[s]=Array.from(u.values())}else typeof Tt.stats[s]=="number"&&(Tt.stats[s]=Math.max(Tt.stats[s],Number(e.stats[s])||0))}Tt.saveId=su();let o=Ht+".tmp",t=Cr(JSON.stringify(Tt,null,2));await ze.writeFile(o,t,"utf8");let n=await ze.open(o,"r+");await ze.fsync(n),await ze.close(n),await ze.rename(o,Ht);try{await ze.ensureDir(Ko.dirname(dn)),await ze.copy(Ht,dn)}catch{}fs=!1,Ya=Date.now()}catch{}},ii=()=>{if(fs=!0,vn)return;let e=Date.now(),o=Math.max(0,1500-(e-Ya));vn=setTimeout(async()=>{await si(),vn=null},o),vn.unref&&vn.unref()},Ga=async()=>{Tt=await ja()},Ha=async()=>{vn&&(clearTimeout(vn),vn=null),await si()},An=async()=>{let e=new Date().toISOString().split("T")[0];return Tt?Tt.date!==e&&(Tt={date:e,stats:{...ri}},fs=!0,await si()):Tt=await ja(),Tt&&Tt.stats&&!Array.isArray(Tt.stats.imageCalls)&&(Tt.stats.imageCalls=[]),Tt.stats},qo=async e=>{let o=await An();o[e]!==void 0&&(o[e]++,ii())},Co=async(e,o)=>{let t=await An();t[e]!==void 0&&(t[e]+=Math.floor(o),ii())},ai=async(e,o)=>{let t=await An(),n=o.apiTier||"Free",s=o.quotas||{};if(n==="Free"){if(e==="agent"||e==="background")return t.agent+t.background<999999;if(e==="search")return!0}if(n==="Paid"||n==="Custom"){if(e==="agent")return t.agent<(s.agentLimit||999999);if(e==="background")return t.background<(s.backgroundLimit||999999);if(e==="search")return t.search<(s.searchLimit||100)}return!0},li=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),n=[];for(let s of t){if(n.length>0){let r=n[n.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}n.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return n},Xa=(e,o)=>{if(!e||e.length===0)return .025;let n=li(e);if(n.length===0)return .025;let s=[];for(let a of n){let d=.025;if(s.length>0){let h=s[s.length-1],S=!1;if(s.length>=2){let T=s[s.length-2];h.ratio>=.8&&T.ratio>=.8&&(S=!0)}if(S)d=.015;else{let T=h.limit,w=h.ratio;w>=.8?d=T===.015?.015:T:w<.4?d=Math.min(.025,T+.005):w>=.4&&w<.6?d=Math.min(.025,T+.004):d=Math.min(.025,T+.002)}}let p=d>0?a.spent/d:0;s.push({limit:d,spent:a.spent,ratio:p})}let r=n[n.length-1];if(o<r.end)return s[s.length-1].limit;let l=s[s.length-1].limit,u=l,f=s[s.length-1].ratio,m=r.end,c=0;for(let a=s.length-1;a>=0&&s[a].ratio>=.8;a--)c++;for(;m<=o;){let a=.025;c>=2?a=.015:f>=.8?a=u===.015?.015:u:f<.4?a=Math.min(.025,u+.005):f>=.4&&f<.6?a=Math.min(.025,u+.004):a=Math.min(.025,u+.002),u=a,f=0,c=0,m+=36e5,l=a}return l},Ka=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(o.keyType!=="Default")return!0;let n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[o.quality]||.002,s=await An();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),l=li(s.imageCalls),u=0;if(l.length>0){let m=l[l.length-1];r>=m.start&&r<m.end&&(u=m.spent)}let f=Xa(s.imageCalls,r);return u+n<=f},ps=async()=>{let e=await An();e.imageCalls||(e.imageCalls=[]);let o=Date.now(),t=li(e.imageCalls),n=[],s=0,r=0;if(t.length>0){let m=t[t.length-1];o>=m.start&&o<m.end&&(n=m.calls,s=m.spent,r=Math.max(0,Math.ceil((m.end-o)/(60*1e3))))}let l=Xa(e.imageCalls,o),u=Math.max(0,l-s),f=s;return{totalSpent:s,remaining:u,activeCallsCount:n.length,nextResetMin:r,reclaimCost:f,limit:l}},qa=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"},n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[o.quality]||.002,s=await An();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:n}),ii()}});import iu from"puppeteer";var ci,Va=re(()=>{Xt();Bt();ci=async e=>{let{query:o,limit:t=10}=ne(e);if(!o)return'ERROR: Missing "query" argument for web_search.';let n=3,s=null;for(let r=1;r<=n;r++){let l=null;try{l=await iu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(d=>setTimeout(d,f));let m=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(o)}`;await u.goto(m,{waitUntil:"networkidle2",timeout:18e4});let c=await u.$$eval(".result",(d,p)=>d.slice(0,p).map((h,S)=>{let T=h.querySelector(".result__a"),w=h.querySelector(".result__snippet"),I=T?T.href:"";I.includes("uddg=")&&(I=decodeURIComponent(I.split("uddg=")[1].split("&")[0]));let L=T?T.innerText.trim():"No Title",_=w?w.innerText.trim():"No Snippet";return`${S+1}. ${L}
267
+ `):""),p=d.match(m);if(p){let h=nu(p[1]);if(h&&u-h>l)continue}f.push(d)}let c=f.join(`
268
+ `).trim();c?await Go.writeFile(e,c+`
269
+ `,"utf8"):await Go.writeFile(e,"","utf8")}catch{}},Ya=async e=>{try{if(!await Go.pathExists(e))return;let o=async t=>{let n=await Go.readdir(t);for(let s of n){let r=tu.join(t,s);(await Go.stat(r)).isDirectory()?(await o(r),(await Go.readdir(r)).length===0&&await Go.remove(r)):s.endsWith(".log")&&await ru(r)}};await o(e)}catch{}},ja=(e,o=4)=>{if(e.length<=1)return e;let t=e[0],n=e.slice(1),s=o*2,r=n.slice(s);return[t,...r]}});import Ve from"fs-extra";import Ho from"path";import oi from"os";var su,dn,iu,St,bn,Ga,ds,ni,Ha,ri,si,Xa,Ka,Cn,Xo,Eo,ii,ai,Va,qa,ms,za,fs=re(()=>{Yt();Lo();su=()=>{if(process.platform==="win32"){let o=process.env.LOCALAPPDATA||Ho.join(oi.homedir(),"AppData","Local");return Ho.join(o,"FxFl","backups","backup.json")}if(process.platform==="darwin")return Ho.join(oi.homedir(),"Library","Application Support","FxFl","backups","backup.json");let e=process.env.XDG_DATA_HOME||Ho.join(oi.homedir(),".local","share");return Ho.join(e,"fxfl","backups","backup.json")},dn=su(),iu=()=>Math.random().toString(36).substring(2)+Date.now().toString(36),St=null,bn=null,Ga=0,ds=!1,ni={agent:0,background:0,search:0,toolSuccess:0,toolFailure:0,toolDenied:0,duration:0,tokens:0,cachedTokens:0,candidateTokens:0,linesAdded:0,linesRemoved:0,imageCalls:[]},Ha=async()=>{let e=new Date().toISOString().split("T")[0],o=Vt+".tmp",t=null,n=null;try{if(await Ve.exists(o)){let r=(await Ve.readFile(o,"utf8")).trim(),l=null;if(r.startsWith("{")||r.startsWith("[")?l=JSON.parse(r):l=JSON.parse(xn(r)),l&&l.date&&l.stats){t=l;try{await Ve.rename(o,Vt)}catch{}}else try{await Ve.remove(o)}catch{}}}catch{try{await Ve.remove(o)}catch{}}if(!t)try{if(await Ve.exists(Vt)){let r=(await Ve.readFile(Vt,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?t=JSON.parse(r):t=JSON.parse(xn(r))}}catch{}try{if(await Ve.exists(dn)){let r=(await Ve.readFile(dn,"utf8")).trim();r.startsWith("{")||r.startsWith("[")?n=JSON.parse(r):n=JSON.parse(xn(r))}}catch{}let s=null;if(t&&n)if(t.saveId!==n.saveId){s=t;try{await Ve.ensureDir(Ho.dirname(dn)),await Ve.copy(Vt,dn)}catch{}}else s=t;else if(t&&!n){s=t;try{await Ve.ensureDir(Ho.dirname(dn)),await Ve.copy(Vt,dn)}catch{}}else if(!t&&n){s=n;try{await Ve.ensureDir(Ho.dirname(Vt)),await Ve.copy(dn,Vt)}catch{}}if(s&&s.date===e&&s.stats){let r={...ni,...s.stats};return Array.isArray(r.imageCalls)||(r.imageCalls=[]),{...s,stats:r}}return{date:e,stats:{...ni}}},ri=async()=>{if(!(!ds||!St))try{await Ve.ensureDir(Ho.dirname(Vt));let e=null;try{if(await Ve.exists(Vt)){let s=(await Ve.readFile(Vt,"utf8")).trim();s.startsWith("{")||s.startsWith("[")?e=JSON.parse(s):e=JSON.parse(xn(s))}}catch{}if(e&&e.date===St.date&&e.stats){for(let s in St.stats)if(e.stats[s]!==void 0)if(Array.isArray(St.stats[s])){let r=Array.isArray(e.stats[s])?e.stats[s]:[],l=St.stats[s],u=new Map;for(let f of[...r,...l])f&&f.timestamp&&u.set(f.timestamp,f);St.stats[s]=Array.from(u.values())}else typeof St.stats[s]=="number"&&(St.stats[s]=Math.max(St.stats[s],Number(e.stats[s])||0))}St.saveId=iu();let o=Vt+".tmp",t=Cr(JSON.stringify(St,null,2));await Ve.writeFile(o,t,"utf8");let n=await Ve.open(o,"r+");await Ve.fsync(n),await Ve.close(n),await Ve.rename(o,Vt);try{await Ve.ensureDir(Ho.dirname(dn)),await Ve.copy(Vt,dn)}catch{}ds=!1,Ga=Date.now()}catch{}},si=()=>{if(ds=!0,bn)return;let e=Date.now(),o=Math.max(0,1500-(e-Ga));bn=setTimeout(async()=>{await ri(),bn=null},o),bn.unref&&bn.unref()},Xa=async()=>{St=await Ha()},Ka=async()=>{bn&&(clearTimeout(bn),bn=null),await ri()},Cn=async()=>{let e=new Date().toISOString().split("T")[0];return St?St.date!==e&&(St={date:e,stats:{...ni}},ds=!0,await ri()):St=await Ha(),St&&St.stats&&!Array.isArray(St.stats.imageCalls)&&(St.stats.imageCalls=[]),St.stats},Xo=async e=>{let o=await Cn();o[e]!==void 0&&(o[e]++,si())},Eo=async(e,o)=>{let t=await Cn();t[e]!==void 0&&(t[e]+=Math.floor(o),si())},ii=async(e,o)=>{let t=await Cn(),n=o.apiTier||"Free",s=o.quotas||{};if(n==="Free"){if(e==="agent"||e==="background")return t.agent+t.background<999999;if(e==="search")return!0}if(n==="Paid"||n==="Custom"){if(e==="agent")return t.agent<(s.agentLimit||999999);if(e==="background")return t.background<(s.backgroundLimit||999999);if(e==="search")return t.search<(s.searchLimit||100)}return!0},ai=e=>{if(!e||e.length===0)return[];let t=[...e].sort((s,r)=>s.timestamp-r.timestamp),n=[];for(let s of t){if(n.length>0){let r=n[n.length-1];if(s.timestamp>=r.start&&s.timestamp<r.end){r.calls.push(s),r.spent+=s.cost;continue}}n.push({start:s.timestamp,end:s.timestamp+36e5,calls:[s],spent:s.cost})}return n},Va=(e,o)=>{if(!e||e.length===0)return .025;let n=ai(e);if(n.length===0)return .025;let s=[];for(let a of n){let d=.025;if(s.length>0){let h=s[s.length-1],E=!1;if(s.length>=2){let w=s[s.length-2];h.ratio>=.8&&w.ratio>=.8&&(E=!0)}if(E)d=.015;else{let w=h.limit,T=h.ratio;T>=.8?d=w===.015?.015:w:T<.4?d=Math.min(.025,w+.005):T>=.4&&T<.6?d=Math.min(.025,w+.004):d=Math.min(.025,w+.002)}}let p=d>0?a.spent/d:0;s.push({limit:d,spent:a.spent,ratio:p})}let r=n[n.length-1];if(o<r.end)return s[s.length-1].limit;let l=s[s.length-1].limit,u=l,f=s[s.length-1].ratio,m=r.end,c=0;for(let a=s.length-1;a>=0&&s[a].ratio>=.8;a--)c++;for(;m<=o;){let a=.025;c>=2?a=.015:f>=.8?a=u===.015?.015:u:f<.4?a=Math.min(.025,u+.005):f>=.4&&f<.6?a=Math.min(.025,u+.004):a=Math.min(.025,u+.002),u=a,f=0,c=0,m+=36e5,l=a}return l},qa=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"};if(o.keyType!=="Default")return!0;let n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.15}[o.quality]||.002,s=await Cn();s.imageCalls||(s.imageCalls=[]);let r=Date.now(),l=ai(s.imageCalls),u=0;if(l.length>0){let m=l[l.length-1];r>=m.start&&r<m.end&&(u=m.spent)}let f=Va(s.imageCalls,r);return u+n<=f},ms=async()=>{let e=await Cn();e.imageCalls||(e.imageCalls=[]);let o=Date.now(),t=ai(e.imageCalls),n=[],s=0,r=0;if(t.length>0){let m=t[t.length-1];o>=m.start&&o<m.end&&(n=m.calls,s=m.spent,r=Math.max(0,Math.ceil((m.end-o)/(60*1e3))))}let l=Va(e.imageCalls,o),u=Math.max(0,l-s),f=s;return{totalSpent:s,remaining:u,activeCallsCount:n.length,nextResetMin:r,reclaimCost:f,limit:l}},za=async e=>{let o=e.imageSettings||{keyType:"Default",quality:"Low-High"},n={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[o.quality]||.002,s=await Cn();s.imageCalls||(s.imageCalls=[]),s.imageCalls.push({timestamp:Date.now(),cost:n}),si()}});import au from"puppeteer";var li,Ja=re(()=>{qt();Yt();li=async e=>{let{query:o,limit:t=10}=ne(e);if(!o)return'ERROR: Missing "query" argument for web_search.';let n=3,s=null;for(let r=1;r<=n;r++){let l=null;try{l=await au.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(d=>setTimeout(d,f));let m=`https://html.duckduckgo.com/html/?q=${encodeURIComponent(o)}`;await u.goto(m,{waitUntil:"networkidle2",timeout:18e4});let c=await u.$$eval(".result",(d,p)=>d.slice(0,p).map((h,E)=>{let w=h.querySelector(".result__a"),T=h.querySelector(".result__snippet"),I=w?w.href:"";I.includes("uddg=")&&(I=decodeURIComponent(I.split("uddg=")[1].split("&")[0]));let O=w?w.innerText.trim():"No Title",P=T?T.innerText.trim():"No Snippet";return`${E+1}. ${O}
271
270
  Source: ${I}
272
- Snippet: ${_}`}),t);if(c.length===0){if((await u.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await l.close(),`No results found for query: [${o}].`}let a=c.join(`
271
+ Snippet: ${P}`}),t);if(c.length===0){if((await u.evaluate(()=>document.body.innerText)).includes("anomaly"))throw new Error("ANOMALY_DETECTED");return await l.close(),`No results found for query: [${o}].`}let a=c.join(`
273
272
 
274
273
  `);return await l.close(),`Search results for [${o}]:
275
274
 
276
- ${a}`}catch(u){if(s=u,l&&await l.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Search failed after ${n+1} attempts. Last error: ${s.message}`}});import au from"puppeteer";var ui,za=re(()=>{Bt();ui=async e=>{let o=e.match(/url\s*=\s*["'](.*)["']/),t=o?o[1]:e,n=3,s=null;for(let r=1;r<=n;r++){let l=null;try{l=await au.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(a=>setTimeout(a,f)),await u.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(a=>setTimeout(a,5e3));let m=await u.evaluate(()=>{document.querySelectorAll("script, style, nav, footer, header, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(T=>T.remove());let d=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),p;for(;p=d.nextNode();)p.remove();document.querySelectorAll("*").forEach(T=>{let w=T.attributes;for(let I=w.length-1;I>=0;I--){let L=w[I].name;L!=="href"&&L!=="src"&&T.removeAttribute(L)}(T.tagName==="SPAN"||T.tagName==="DIV"||T.tagName==="SECTION")&&T.attributes.length===0&&(T.tagName==="SPAN"||T.tagName==="DIV"&&T.childNodes.length===1&&T.childNodes[0].nodeType===Node.TEXT_NODE)&&T.replaceWith(...T.childNodes)});let S=()=>{let T=!1;document.querySelectorAll("*:not(br)").forEach(w=>{w.childNodes.length===0&&!w.innerText.trim()&&(w.remove(),T=!0)}),T&&S()};return S(),document.body.innerHTML});if(!m)throw new Error("EMPTY_RENDER_RESULT");let c=m.replace(/\s+/g," ").replace(/>\s+</g,"><").trim().substring(0,3e4);return await l.close(),`CLEANED HTML FROM [${t}]:
275
+ ${a}`}catch(u){if(s=u,l&&await l.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Search failed after ${n+1} attempts. Last error: ${s.message}`}});import lu from"puppeteer";var ci,Qa=re(()=>{Yt();ci=async e=>{let o=e.match(/url\s*=\s*["'](.*)["']/),t=o?o[1]:e,n=3,s=null;for(let r=1;r<=n;r++){let l=null;try{l=await lu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage();await u.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.7778.97 Safari/537.36"),await u.setViewport({width:1366,height:768});let f=r===1?Math.random()*1e3+500:Math.random()*2e3+1e3;await new Promise(a=>setTimeout(a,f)),await u.goto(t,{waitUntil:"networkidle2",timeout:18e4}),await new Promise(a=>setTimeout(a,5e3));let m=await u.evaluate(()=>{document.querySelectorAll("script, style, nav, footer, header, noscript, svg, canvas, iframe, ad, .ads, link, meta, img").forEach(w=>w.remove());let d=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT),p;for(;p=d.nextNode();)p.remove();document.querySelectorAll("*").forEach(w=>{let T=w.attributes;for(let I=T.length-1;I>=0;I--){let O=T[I].name;O!=="href"&&O!=="src"&&w.removeAttribute(O)}(w.tagName==="SPAN"||w.tagName==="DIV"||w.tagName==="SECTION")&&w.attributes.length===0&&(w.tagName==="SPAN"||w.tagName==="DIV"&&w.childNodes.length===1&&w.childNodes[0].nodeType===Node.TEXT_NODE)&&w.replaceWith(...w.childNodes)});let E=()=>{let w=!1;document.querySelectorAll("*:not(br)").forEach(T=>{T.childNodes.length===0&&!T.innerText.trim()&&(T.remove(),w=!0)}),w&&E()};return E(),document.body.innerHTML});if(!m)throw new Error("EMPTY_RENDER_RESULT");let c=m.replace(/\s+/g," ").replace(/>\s+</g,"><").trim().substring(0,3e4);return await l.close(),`CLEANED HTML FROM [${t}]:
277
276
 
278
277
  ${c}${m.length>3e4?`
279
278
 
280
- [TRUNCATED AT 30K CHARS]`:""}`}catch(u){if(s=u,l&&await l.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Scrape failed after ${n+1} attempts. Last error: ${s.message}`}});var lu,di,Ja=re(()=>{Lo();Bt();lu=4*(1024*2),di=async(e,o={})=>{let t=c=>{let a=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),d=e.match(a);if(d)return d[2].trim();let p=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),h=e.match(p);return h?h[1].trim():null},n=t("action"),s=t("method"),r=t("content"),l=t("content-new"),u=t("content-old"),f=t("id"),m=t("chat-id")||o.chatId||o.sessionId||"default-session";if(n==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=xe(Eo,{});c[m]||(c[m]=[]),c[m].push(r),ke(Eo,c);let a=c[m].reduce((d,p)=>d+p.length,0);return`SUCCESS: Temporary context saved for session [${m}]. (Size: ${a} chars)`}if(n==="user"){let c=xe(Nt,[]).map(a=>(a.score===void 0&&(a.score=.5),a));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let a=new Date,d=`${a.getDate()}/${a.getMonth()+1}/${a.getFullYear()}`,p=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${d}]`,h=lu,S=c.reduce((L,_)=>L+(_.memory?.length||0),0);for(;c.length>0&&S+p.length>h;){let L=c.shift();S-=L.memory?.length||0}let T=t("score"),w=T?parseFloat(T):.5,I={id:`mem-${Date.now().toString(36)}`,memory:p,score:Math.min(2,isNaN(w)?.5:w)};return c.push(I),ke(Nt,c),`SUCCESS: Memory added with ID [${I.id}] and score [${I.score}]. (Vault Size: ${S+p.length} chars)`}if(s==="update"){let a=f||u,d=l||r;if(!a||!d)return"ERROR: Missing 'id' or content for update.";let p=c.findIndex(w=>w.id===a);if(p===-1)return`ERROR: Memory ID [${a}] not found.`;let h=new Date,S=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,T=d.includes("[Saved on:")?d:`${d.trim()} [Saved on: ${S}]`;return c[p].memory=T,ke(Nt,c),`SUCCESS: Memory [${a}] updated.`}if(s==="delete"){let a=f||r;if(!a)return"ERROR: Missing 'id' for deletion.";let d=c.length,p=c.filter(h=>h.id!==a);return p.length===d?`ERROR: Memory ID [${a}] not found.`:(ke(Nt,p),`SUCCESS: Memory [${a}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${n}] for memory tool.`}});var mi,Qa=re(()=>{$r();Xt();mi=async(e,o={})=>{let t=ne(e).title,n=o.chatId||o.sessionId;if(!n)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Ba(n,t),`SUCCESS: Chat title updated to [${t}] for session [${n}].`}catch(s){return`ERROR: Failed to update chat title: ${s.message}`}}});import gs from"fs";import Za from"path";var fi,el=re(()=>{Xt();fi=async(e,o={})=>{let{path:t,StartLine:n,EndLine:s,start_line:r,end_line:l,startLine:u,endLine:f}=ne(e),m=parseInt(n||r||u),c=parseInt(s||l||f),a=m||1,d=c||(m?m+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let p=Za.resolve(process.cwd(),t);try{if(!gs.existsSync(p))return`ERROR: File [${t}] does not exist.`;if(gs.statSync(p).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let S=Za.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(S))return`ERROR: Unable to read. Type ${S.slice(1).toUpperCase()} not supported`;let w={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(w[S]){if(!(o.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let Z=gs.readFileSync(p).toString("base64"),B=w[S];return{text:`[BINARY FILE]: ${t} (${B}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:Z,mimeType:B}}}}let I=gs.readFileSync(p,"utf8");I.startsWith("\uFEFF")&&(I=I.slice(1)),I=I.replace(/\r\n/g,`
279
+ [TRUNCATED AT 30K CHARS]`:""}`}catch(u){if(s=u,l&&await l.close(),r<n){let f=Math.pow(2,r)*1e3;await new Promise(m=>setTimeout(m,f))}}}return`ERROR: Scrape failed after ${n+1} attempts. Last error: ${s.message}`}});var cu,ui,Za=re(()=>{Lo();Yt();cu=4*(1024*2),ui=async(e,o={})=>{let t=c=>{let a=new RegExp(`${c}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),d=e.match(a);if(d)return d[2].trim();let p=new RegExp(`${c}\\s*[:=]\\s*([^,\\s)]+)`,"s"),h=e.match(p);return h?h[1].trim():null},n=t("action"),s=t("method"),r=t("content"),l=t("content-new"),u=t("content-old"),f=t("id"),m=t("chat-id")||o.chatId||o.sessionId||"default-session";if(n==="temp"){if(!r)return"ERROR: Missing 'content' for temp memory.";let c=Te(To,{});c[m]||(c[m]=[]),c[m].push(r),De(To,c);let a=c[m].reduce((d,p)=>d+p.length,0);return`SUCCESS: Temporary context saved for session [${m}]. (Size: ${a} chars)`}if(n==="user"){let c=Te(Wt,[]).map(a=>(a.score===void 0&&(a.score=.5),a));if(s==="add"){if(!r)return"ERROR: Missing 'content' for memory addition.";let a=new Date,d=`${a.getDate()}/${a.getMonth()+1}/${a.getFullYear()}`,p=r.includes("[Saved on:")?r:`${r.trim()} [Saved on: ${d}]`,h=cu,E=c.reduce((O,P)=>O+(P.memory?.length||0),0);for(;c.length>0&&E+p.length>h;){let O=c.shift();E-=O.memory?.length||0}let w=t("score"),T=w?parseFloat(w):.5,I={id:`mem-${Date.now().toString(36)}`,memory:p,score:Math.min(2,isNaN(T)?.5:T)};return c.push(I),De(Wt,c),`SUCCESS: Memory added with ID [${I.id}] and score [${I.score}]. (Vault Size: ${E+p.length} chars)`}if(s==="update"){let a=f||u,d=l||r;if(!a||!d)return"ERROR: Missing 'id' or content for update.";let p=c.findIndex(T=>T.id===a);if(p===-1)return`ERROR: Memory ID [${a}] not found.`;let h=new Date,E=`${h.getDate()}/${h.getMonth()+1}/${h.getFullYear()}`,w=d.includes("[Saved on:")?d:`${d.trim()} [Saved on: ${E}]`;return c[p].memory=w,De(Wt,c),`SUCCESS: Memory [${a}] updated.`}if(s==="delete"){let a=f||r;if(!a)return"ERROR: Missing 'id' for deletion.";let d=c.length,p=c.filter(h=>h.id!==a);return p.length===d?`ERROR: Memory ID [${a}] not found.`:(De(Wt,p),`SUCCESS: Memory [${a}] deleted.`)}return`ERROR: Invalid method [${s}] for user memory. Use 'add', 'update', or 'delete'.`}return`ERROR: Unknown action [${n}] for memory tool.`}});var di,el=re(()=>{$r();qt();di=async(e,o={})=>{let t=ne(e).title,n=o.chatId||o.sessionId;if(!n)return"ERROR: No active chatId found in tool context.";if(!t)return"ERROR: Missing 'title' argument.";try{return await Ra(n,t),`SUCCESS: Chat title updated to [${t}] for session [${n}].`}catch(s){return`ERROR: Failed to update chat title: ${s.message}`}}});import ps from"fs";import tl from"path";var mi,ol=re(()=>{qt();mi=async(e,o={})=>{let{path:t,StartLine:n,EndLine:s,start_line:r,end_line:l,startLine:u,endLine:f}=ne(e),m=parseInt(n||r||u),c=parseInt(s||l||f),a=m||1,d=c||(m?m+800:800);if(!t)return'ERROR: Missing "path" argument for view_file.';let p=tl.resolve(process.cwd(),t);try{if(!ps.existsSync(p))return`ERROR: File [${t}] does not exist.`;if(ps.statSync(p).isDirectory())return`ERROR: Path [${t}] is a directory. Use list_files instead.`;let E=tl.extname(t).toLowerCase();if([".mp4",".mkv",".avi",".mov",".webm",".flv",".wmv",".mpeg",".mpg"].includes(E))return`ERROR: Unable to read. Type ${E.slice(1).toUpperCase()} not supported`;let T={".pdf":"application/pdf",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};if(T[E]){if(!(o.isMultiModal!==!1))return`ERROR: Multimodality is not supported for the current model. Unable to load [${t}].`;let Z=ps.readFileSync(p).toString("base64"),N=T[E];return{text:`[BINARY FILE]: ${t} (${N}) - Loaded as multimodal part.`,binaryPart:{inlineData:{data:Z,mimeType:N}}}}let I=ps.readFileSync(p,"utf8");I.startsWith("\uFEFF")&&(I=I.slice(1)),I=I.replace(/\r\n/g,`
281
280
  `).replace(/\r/g,`
282
- `);let L=I.split(`
283
- `),_=L.length,R=Math.max(0,a-1),v=Math.min(_,d),b=L.slice(R,v),A=`File: [${t}] (Showing lines ${R+1}-${v} of ${_}).`,F=b.map((Q,j)=>`${String(R+j+1).padStart(4)}: ${Q}`).join(`
284
- `);return`${A}
281
+ `);let O=I.split(`
282
+ `),P=O.length,U=Math.max(0,a-1),A=Math.min(P,d),S=O.slice(U,A),v=`File: [${t}] (Showing lines ${U+1}-${A} of ${P}).`,F=S.map((V,Y)=>`${String(U+Y+1).padStart(4)}: ${V}`).join(`
283
+ `);return`${v}
285
284
 
286
- ${F}`}catch(h){return`ERROR: Failed to read file [${t}]: ${h.message}`}}});import ir from"fs";import tl from"path";var pi,ol=re(()=>{Xt();un();pi=async(e,o={})=>{let{path:t,content:n}=ne(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(n===void 0)return'ERROR: Missing "content" argument for write_file.';n=n.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
285
+ ${F}`}catch(h){return`ERROR: Failed to read file [${t}]: ${h.message}`}}});import nr from"fs";import nl from"path";var fi,rl=re(()=>{qt();un();fi=async(e,o={})=>{let{path:t,content:n}=ne(e);if(!t)return'ERROR: Missing "path" argument for write_file.';if(n===void 0)return'ERROR: Missing "content" argument for write_file.';n=n.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
287
286
  `).replace(/\r/g,`
288
- `);let s=tl.resolve(process.cwd(),t),r=tl.dirname(s);try{await kt.recordFileChange(s);let l="";if(ir.existsSync(s))try{l=`Old File contents:
289
- ${ir.readFileSync(s,"utf8").split(/\r?\n/).map((I,L)=>`${L+1} | ${I}`).join(`
287
+ `);let s=nl.resolve(process.cwd(),t),r=nl.dirname(s);try{await kt.recordFileChange(s);let l="";if(nr.existsSync(s))try{l=`Old File contents:
288
+ ${nr.readFileSync(s,"utf8").split(/\r?\n/).map((I,O)=>`${O+1} | ${I}`).join(`
290
289
  `)}
291
290
 
292
291
  `}catch{l=`[Note: Could not read existing file for reversal reference]
293
292
 
294
- `}ir.existsSync(r)||ir.mkdirSync(r,{recursive:!0});let f=(T=>T.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
293
+ `}nr.existsSync(r)||nr.mkdirSync(r,{recursive:!0});let f=(w=>w.replace(/^```[\w]*\n?/,"").replace(/```\s*$/,"").replace(/\r\n/g,`
295
294
  `).replace(/\r/g,`
296
- `))(n),m=f.split(/\r?\n/).length,c=Buffer.byteLength(f,"utf8");ir.writeFileSync(s,f,"utf8");let a=ir.readFileSync(s,"utf8"),d=Buffer.byteLength(a,"utf8"),p=a.split(/\r?\n/),h=p.length;if(d===0&&c>0)return a=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk despite success report!`;let S="";if(h<=200)S=p.join(`
297
- `);else{let T=p.slice(0,100).join(`
298
- `),w=p.slice(-100).join(`
299
- `);S=`${T}
295
+ `))(n),m=f.split(/\r?\n/).length,c=Buffer.byteLength(f,"utf8");nr.writeFileSync(s,f,"utf8");let a=nr.readFileSync(s,"utf8"),d=Buffer.byteLength(a,"utf8"),p=a.split(/\r?\n/),h=p.length;if(d===0&&c>0)return a=null,`ERROR: CRITICAL FAILURE: Verification failed. File [${t}] is empty on disk despite success report!`;let E="";if(h<=200)E=p.join(`
296
+ `);else{let w=p.slice(0,100).join(`
297
+ `),T=p.slice(-100).join(`
298
+ `);E=`${w}
300
299
 
301
300
  ... [${h-200} lines truncated] ...
302
301
 
303
- ${w}`}return a=null,`SUCCESS: File [${t}] saved.
302
+ ${T}`}return a=null,`SUCCESS: File [${t}] saved.
304
303
 
305
304
  - Stats: [${h} lines, ${(d/1024).toFixed(1)} KB]
306
305
  ${l}- Content Preview:
307
- ${S}
306
+ ${E}
308
307
 
309
- Check if Starting and Ending matches your write.`}catch(l){return`ERROR: Failed to write file [${t}]: ${l.message}`}}});import hi from"fs";import cu from"path";var gi,nl=re(()=>{Xt();un();Wn();gi=async(e,o={})=>{let t=ne(e),n=t.path;if(!n)return'ERROR: Missing "path" argument for update_file.';let{patchPairs:s,error:r}=rs(t);if(r)return`ERROR: ${r}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use replaceContent1, newContent1, etc.";let l=cu.resolve(process.cwd(),n);try{if(!hi.existsSync(l))return`ERROR: File [${n}] does not exist. Use write_file instead.`;let u=o.forcedContent||hi.readFileSync(l,"utf8");u.startsWith("\uFEFF")&&(u=u.slice(1));let f=u.replace(/\r\n/g,`
308
+ Check if Starting and Ending matches your write.`}catch(l){return`ERROR: Failed to write file [${t}]: ${l.message}`}}});import pi from"fs";import uu from"path";var hi,sl=re(()=>{qt();un();Rn();hi=async(e,o={})=>{let t=ne(e),n=t.path;if(!n)return'ERROR: Missing "path" argument for update_file.';let{patchPairs:s,error:r}=os(t);if(r)return`ERROR: ${r}`;if(s.length===0)return"ERROR: No valid replacement pairs found. Use replaceContent1, newContent1, etc.";let l=uu.resolve(process.cwd(),n);try{if(!pi.existsSync(l))return`ERROR: File [${n}] does not exist. Use write_file instead.`;let u=o.forcedContent||pi.readFileSync(l,"utf8");u.startsWith("\uFEFF")&&(u=u.slice(1));let f=u.replace(/\r\n/g,`
310
309
  `).replace(/\r/g,`
311
- `),{content:m,results:c}=ss(f,s),a=c.filter(h=>!h.success),d=c.filter(h=>h.success);if(d.length===0)return`ERROR: Patch Failed to apply to [${n}].
310
+ `),{content:m,results:c}=ns(f,s),a=c.filter(h=>!h.success),d=c.filter(h=>h.success);if(d.length===0)return`ERROR: Patch Failed to apply to [${n}].
312
311
  ${a.map(h=>` \u2022 ${h.error}`).join(`
313
- `)}`;await kt.recordFileChange(l,f),hi.writeFileSync(l,m,"utf8");let p=is(f,m,c,12);return a.length>0?`SUCCESS: File [${n}] updated with some blocks failed. [${d.length}/${s.length}] blocks applied.
312
+ `)}`;await kt.recordFileChange(l,f),pi.writeFileSync(l,m,"utf8");let p=rs(f,m,c,12);return a.length>0?`SUCCESS: File [${n}] updated with some blocks failed. [${d.length}/${s.length}] blocks applied.
314
313
 
315
314
  Failures:
316
315
  ${a.map(h=>` \u2022 ${h.error}`).join(`
@@ -318,14 +317,14 @@ ${a.map(h=>` \u2022 ${h.error}`).join(`
318
317
 
319
318
  ${p}`:`SUCCESS: File [${n}] updated. [${c.length}/${s.length}] blocks applied.
320
319
 
321
- ${p}`}catch(u){return`ERROR: Failed to update file [${n}]: ${u.message}`}}});import xs from"fs";import rl from"path";var xi,sl=re(()=>{Xt();xi=async e=>{let{path:o="."}=ne(e),t=rl.resolve(process.cwd(),o);try{if(!xs.existsSync(t))return`ERROR: Path [${o}] does not exist.`;if(!xs.statSync(t).isDirectory())return`ERROR: Path [${o}] is a file, not a directory. Use view_file instead.`;let s=xs.readdirSync(t),r=s.length,l=100,u=s.slice(0,l),f=[];for(let d of u){let p=rl.join(t,d),h="\u{1F4C4}",S={name:d,type:"unknown",size:"N/A",mtime:"N/A"};try{let T=xs.statSync(p);S={name:d,type:T.isDirectory()?"directory":"file",size:(T.size/1024).toFixed(1)+" KB",mtime:T.mtime.toLocaleString()}}catch{S.type="inaccessible"}f.push(S)}let m=f.map(d=>{let p=d.type==="directory"?"\u{1F4C1}":d.type==="file"?"\u{1F4C4}":"\u2753";return d.type==="directory"?`${p} ${d.name} - [DIR] - [Modified: ${d.mtime}]`:`${p} ${d.name} - [Size: ${d.size}] - [Modified: ${d.mtime}]`}).join(`
320
+ ${p}`}catch(u){return`ERROR: Failed to update file [${n}]: ${u.message}`}}});import hs from"fs";import il from"path";var gi,al=re(()=>{qt();gi=async e=>{let{path:o="."}=ne(e),t=il.resolve(process.cwd(),o);try{if(!hs.existsSync(t))return`ERROR: Path [${o}] does not exist.`;if(!hs.statSync(t).isDirectory())return`ERROR: Path [${o}] is a file, not a directory. Use view_file instead.`;let s=hs.readdirSync(t),r=s.length,l=100,u=s.slice(0,l),f=[];for(let d of u){let p=il.join(t,d),h="\u{1F4C4}",E={name:d,type:"unknown",size:"N/A",mtime:"N/A"};try{let w=hs.statSync(p);E={name:d,type:w.isDirectory()?"directory":"file",size:(w.size/1024).toFixed(1)+" KB",mtime:w.mtime.toLocaleString()}}catch{E.type="inaccessible"}f.push(E)}let m=f.map(d=>{let p=d.type==="directory"?"\u{1F4C1}":d.type==="file"?"\u{1F4C4}":"\u2753";return d.type==="directory"?`${p} ${d.name} - [DIR] - [Modified: ${d.mtime}]`:`${p} ${d.name} - [Size: ${d.size}] - [Modified: ${d.mtime}]`}).join(`
322
321
  `),c=`
323
322
 
324
323
  (Total items in folder: ${r})`;r>l&&(c=`
325
324
 
326
325
  \u26A0\uFE0F TRUNCATED: Showing first ${l} of ${r} items.`);let a=`Detailed folder stats for [${o}]:
327
326
 
328
- ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){return`ERROR: Failed to read folder [${o}]: ${n.message}`}}});var yi,il=re(()=>{Xt();yi=async(e,o)=>{let t=ne(e),{question:n}=t;if(!n)return'ERROR: Missing "question" argument for ask.';if(!o.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let l=t[r];if(typeof l=="string"&&l.includes("::")){let[u,f]=l.split("::");s.push({id:r,label:u.trim(),description:f.trim()})}else s.push({id:r,label:String(l).trim(),description:""})}});try{return`USER CHOOSE: ${await o.onAskUser(n,s)}`}catch(r){return`ERROR: Failed to get user input: ${r.message}`}}});import uu from"puppeteer";import ar from"path";import Gn from"fs-extra";import{PDFDocument as du}from"pdf-lib";var wi,al=re(()=>{Xt();un();wi=async e=>{let{path:o,content:t,orientation:n="portrait",margin:s="0px"}=ne(e);if(!o)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=ar.resolve(process.cwd(),o),l=null;try{await Gn.ensureDir(ar.dirname(r)),await kt.recordFileChange(r),l=await uu.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage(),f=t,m={},c=async v=>{if(!v||v.startsWith("http://")||v.startsWith("https://")||v.startsWith("data:"))return null;try{let b=ar.resolve(process.cwd(),v);if(await Gn.pathExists(b)){let A=ar.extname(b).toLowerCase().replace(".","")||"png",F=A==="jpg"?"jpeg":A==="svg"?"svg+xml":A,Q=await Gn.readFile(b,"base64");return`data:image/${F};base64,${Q}`}}catch{}return null},a=/<link[^>]+href=["']([^"']+)["']/gi,d={},p;for(;(p=a.exec(t))!==null;){let v=p[1],b=p[0];if(v&&b.toLowerCase().includes("stylesheet")&&!v.startsWith("http://")&&!v.startsWith("https://")&&!v.startsWith("data:"))try{let A=ar.resolve(process.cwd(),v);if(await Gn.pathExists(A)){let F=await Gn.readFile(A,"utf-8");d[b]=`<style>${F}</style>`}}catch{}}for(let[v,b]of Object.entries(d))f=f.split(v).join(b);let h=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=h.exec(f))!==null;){let v=p[1];if(v&&!m[v]){let b=await c(v);b&&(m[v]=b)}}let S=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=S.exec(f))!==null;){let v=p[1].trim();if(v&&!m[v]){let b=await c(v);b&&(m[v]=b)}}for(let[v,b]of Object.entries(m)){let A=v.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),F=new RegExp(`(src=["'])(${A})(["'])`,"gi");f=f.replace(F,`$1${b}$3`);let Q=new RegExp(`url\\(\\s*(['"]?)(${A})\\1\\s*\\)`,"gi");f=f.replace(Q,`url($1${b}$1)`)}let T=`
327
+ ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){return`ERROR: Failed to read folder [${o}]: ${n.message}`}}});var xi,ll=re(()=>{qt();xi=async(e,o)=>{let t=ne(e),{question:n}=t;if(!n)return'ERROR: Missing "question" argument for ask.';if(!o.onAskUser)return"ERROR: onAskUser callback not provided in tool context.";let s=[];Object.keys(t).forEach(r=>{if(r.startsWith("option")){let l=t[r];if(typeof l=="string"&&l.includes("::")){let[u,f]=l.split("::");s.push({id:r,label:u.trim(),description:f.trim()})}else s.push({id:r,label:String(l).trim(),description:""})}});try{return`USER CHOOSE: ${await o.onAskUser(n,s)}`}catch(r){return`ERROR: Failed to get user input: ${r.message}`}}});import du from"puppeteer";import rr from"path";import jn from"fs-extra";import{PDFDocument as mu}from"pdf-lib";var yi,cl=re(()=>{qt();un();yi=async e=>{let{path:o,content:t,orientation:n="portrait",margin:s="0px"}=ne(e);if(!o)return'ERROR: Missing "path" argument for write_pdf.';if(!t)return'ERROR: Missing "content" (HTML/CSS) for write_pdf.';let r=rr.resolve(process.cwd(),o),l=null;try{await jn.ensureDir(rr.dirname(r)),await kt.recordFileChange(r),l=await du.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-gpu","--disable-dev-shm-usage"]});let u=await l.newPage(),f=t,m={},c=async A=>{if(!A||A.startsWith("http://")||A.startsWith("https://")||A.startsWith("data:"))return null;try{let S=rr.resolve(process.cwd(),A);if(await jn.pathExists(S)){let v=rr.extname(S).toLowerCase().replace(".","")||"png",F=v==="jpg"?"jpeg":v==="svg"?"svg+xml":v,V=await jn.readFile(S,"base64");return`data:image/${F};base64,${V}`}}catch{}return null},a=/<link[^>]+href=["']([^"']+)["']/gi,d={},p;for(;(p=a.exec(t))!==null;){let A=p[1],S=p[0];if(A&&S.toLowerCase().includes("stylesheet")&&!A.startsWith("http://")&&!A.startsWith("https://")&&!A.startsWith("data:"))try{let v=rr.resolve(process.cwd(),A);if(await jn.pathExists(v)){let F=await jn.readFile(v,"utf-8");d[S]=`<style>${F}</style>`}}catch{}}for(let[A,S]of Object.entries(d))f=f.split(A).join(S);let h=/<img[^>]+src=["']([^"']+)["']/gi;for(;(p=h.exec(f))!==null;){let A=p[1];if(A&&!m[A]){let S=await c(A);S&&(m[A]=S)}}let E=/url\(\s*['"]?([^'")]+?)['"]?\s*\)/gi;for(;(p=E.exec(f))!==null;){let A=p[1].trim();if(A&&!m[A]){let S=await c(A);S&&(m[A]=S)}}for(let[A,S]of Object.entries(m)){let v=A.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),F=new RegExp(`(src=["'])(${v})(["'])`,"gi");f=f.replace(F,`$1${S}$3`);let V=new RegExp(`url\\(\\s*(['"]?)(${v})\\1\\s*\\)`,"gi");f=f.replace(V,`url($1${S}$1)`)}let w=`
329
328
  <style>
330
329
  @page {
331
330
  margin: ${s};
@@ -355,7 +354,7 @@ ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){return`ERROR: Faile
355
354
  </style>
356
355
  <div class="watermark">Generated by FluxFlow CLI (AI)</div>
357
356
  ${f}
358
- `;await u.setContent(T,{waitUntil:"networkidle0",timeout:18e4});let w=await u.pdf({format:"A4",landscape:String(n).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),I=await du.load(w),L=ar.basename(o);I.setTitle(`FluxFlow_${L}`),I.setAuthor("FluxFlow CLI"),I.setSubject("Generated with Agentic AI System"),I.setKeywords(["FluxFlow","AI","Agentic","Automated"]),I.setCreator("FluxFlow PDF Engine"),I.setProducer("FluxFlow (Generative AI)");let _=await I.save();await Gn.writeFile(r,_);let R=await Gn.stat(r);return`SUCCESS: PDF generated successfully at [${o}] (${(R.size/1024).toFixed(2)} KB).`}catch(u){return`ERROR: Failed to generate PDF [${o}]: ${u.message}`}finally{l&&await l.close()}}});import ll from"fs-extra";import Ti from"path";import mu from"html-to-docx";var Si,cl=re(()=>{Xt();un();Si=async e=>{let{path:o,content:t}=ne(e);if(!o)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let n=Ti.resolve(process.cwd(),o);try{await ll.ensureDir(Ti.dirname(n)),await kt.recordFileChange(n);let s=Ti.basename(o),r=t.includes("<html")?t:`
357
+ `;await u.setContent(w,{waitUntil:"networkidle0",timeout:18e4});let T=await u.pdf({format:"A4",landscape:String(n).toLowerCase()==="landscape",margin:{top:s,right:s,bottom:s,left:s},printBackground:!0}),I=await mu.load(T),O=rr.basename(o);I.setTitle(`FluxFlow_${O}`),I.setAuthor("FluxFlow CLI"),I.setSubject("Generated with Agentic AI System"),I.setKeywords(["FluxFlow","AI","Agentic","Automated"]),I.setCreator("FluxFlow PDF Engine"),I.setProducer("FluxFlow (Generative AI)");let P=await I.save();await jn.writeFile(r,P);let U=await jn.stat(r);return`SUCCESS: PDF generated successfully at [${o}] (${(U.size/1024).toFixed(2)} KB).`}catch(u){return`ERROR: Failed to generate PDF [${o}]: ${u.message}`}finally{l&&await l.close()}}});import ul from"fs-extra";import wi from"path";import fu from"html-to-docx";var Ti,dl=re(()=>{qt();un();Ti=async e=>{let{path:o,content:t}=ne(e);if(!o)return'ERROR: Missing "path" argument for write_docx.';if(!t)return'ERROR: Missing "content" (HTML) for write_docx.';let n=wi.resolve(process.cwd(),o);try{await ul.ensureDir(wi.dirname(n)),await kt.recordFileChange(n);let s=wi.basename(o),r=t.includes("<html")?t:`
359
358
  <!DOCTYPE html>
360
359
  <html lang="en">
361
360
  <head>
@@ -366,34 +365,35 @@ ${m}${c}`;return s.length=0,u.length=0,f.length=0,a}catch(n){return`ERROR: Faile
366
365
  ${t}
367
366
  </body>
368
367
  </html>
369
- `,l=await mu(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await ll.writeFile(n,l),`SUCCESS: Word document [${o}] generated successfully.
370
- - Size: ${(l.length/1024).toFixed(1)} KB`}catch(s){return`ERROR: Failed to generate DOCX [${o}]: ${s.message}`}}});import Ei from"fs/promises";import Pr from"path";async function ul(e,o,t=e,n=1){if(n>12)return[];let s=[],r;try{r=await Ei.readdir(e,{withFileTypes:!0})}catch{return[]}for(let l of r){let u=Pr.join(e,l.name),f=Pr.relative(t,u),m=f.split(Pr.sep).map(a=>a.toLowerCase());if(!o.some(a=>m.includes(a.toLowerCase())))if(l.isDirectory()){let a=await ul(u,o,t,n+1);s=s.concat(a)}else l.isFile()&&s.push({fullPath:u,relativePath:f})}return s}var bi,dl=re(()=>{Xt();bi=async e=>{let{keyword:o,file:t}=ne(e);if(!o)return'ERROR: Missing "keyword" argument.';let n=["node_modules",".git","dist",".next",".gemini",".exe",".dll",".png",".jpg",".jpeg",".gif",".zip",".tgz"],s=150;try{let r=[],l=process.cwd();if(t){let a=Pr.resolve(l,t);try{(await Ei.stat(a)).isFile()&&r.push({fullPath:a,relativePath:Pr.relative(l,a)})}catch{return`ERROR: File not found: ${t}`}}else r=await ul(l,n);let u=r.map(async a=>{try{let d=await Ei.readFile(a.fullPath,"utf-8");if(d.includes("\0"))return[];let p=d.split(/\r?\n/),h=[];for(let S=0;S<p.length;S++)if(p[S].includes(o)){let T=a.relativePath.replace(/\\/g,"/");h.push(`${T} \u2192 ${S+1}`)}return h}catch{return[]}}),m=(await Promise.all(u)).flat().slice(0,s);if(typeof global.gc=="function"&&global.gc(),m.length===0)return`Found 0 matches for keyword: "${o}"${t?` in file: ${t}`:". Try to specify files"}`;let c=`Found ${m.length} matches:
368
+ `,l=await fu(r,null,{title:`FluxFlow_${s}`,creator:"FluxFlow CLI",description:"Generated by Agentic AI System",table:{row:{cantSplit:!0}},footer:!0,pageNumber:!0});return await ul.writeFile(n,l),`SUCCESS: Word document [${o}] generated successfully.
369
+ - Size: ${(l.length/1024).toFixed(1)} KB`}catch(s){return`ERROR: Failed to generate DOCX [${o}]: ${s.message}`}}});import Si from"fs/promises";import Pr from"path";async function ml(e,o,t=e,n=1){if(n>12)return[];let s=[],r;try{r=await Si.readdir(e,{withFileTypes:!0})}catch{return[]}for(let l of r){let u=Pr.join(e,l.name),f=Pr.relative(t,u),m=f.split(Pr.sep).map(a=>a.toLowerCase());if(!o.some(a=>m.includes(a.toLowerCase())))if(l.isDirectory()){let a=await ml(u,o,t,n+1);s=s.concat(a)}else l.isFile()&&s.push({fullPath:u,relativePath:f})}return s}var Ei,fl=re(()=>{qt();Ei=async e=>{let{keyword:o,file:t}=ne(e);if(!o)return'ERROR: Missing "keyword" argument.';let n=["node_modules",".git","dist",".next",".gemini",".exe",".dll",".png",".jpg",".jpeg",".gif",".zip",".tgz"],s=150;try{let r=[],l=process.cwd();if(t){let a=Pr.resolve(l,t);try{(await Si.stat(a)).isFile()&&r.push({fullPath:a,relativePath:Pr.relative(l,a)})}catch{return`ERROR: File not found: ${t}`}}else r=await ml(l,n);let u=r.map(async a=>{try{let d=await Si.readFile(a.fullPath,"utf-8");if(d.includes("\0"))return[];let p=d.split(/\r?\n/),h=[];for(let E=0;E<p.length;E++)if(p[E].includes(o)){let w=a.relativePath.replace(/\\/g,"/");h.push(`${w} \u2192 ${E+1}`)}return h}catch{return[]}}),m=(await Promise.all(u)).flat().slice(0,s);if(typeof global.gc=="function"&&global.gc(),m.length===0)return`Found 0 matches for keyword: "${o}"${t?` in file: ${t}`:". Try to specify files"}`;let c=`Found ${m.length} matches:
371
370
 
372
371
  `;return c+=m.join(`
373
- `),c}catch(r){return`ERROR: ${r.message}`}}});import ml from"fs-extra";import Ci from"path";var fu,ki,fl=re(()=>{Xt();os();hs();un();fu=(e,o={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],n=[];for(let l=0;l<256;l++){let u=l;for(let f=0;f<8;f++)u&1?u=3988292384^u>>>1:u=u>>>1;n[l]=u}let s=l=>{let u=4294967295;for(let f=0;f<l.length;f++)u=n[(u^l[f])&255]^u>>>8;return(u^4294967295)>>>0},r=(l,u)=>{let f=Buffer.from(l,"ascii"),m=Buffer.from(u,"utf-8"),c=f.length+1+m.length,a=Buffer.alloc(8+c+4);a.writeUInt32BE(c,0),a.write("tEXt",4,"ascii"),f.copy(a,8),a[8+f.length]=0,m.copy(a,8+f.length+1);let d=s(a.subarray(4,8+c));return a.writeUInt32BE(d,8+c),a};for(let[l,u]of Object.entries(o))u!=null&&t.push(r(l,String(u)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let u=e.subarray(0,33),f=e.subarray(33);return Buffer.concat([u,...t,f])}return e}catch{return e}},ki=async(e,o={})=>{let t=ne(e),n=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!n)return'ERROR: Missing "prompt" argument for generate_image.';let l=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],u=n.toLowerCase();if(l.some(m=>u.includes(m)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let m=await or();if(!await Ka(m))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await ps()).nextResetMin||60}m).`;let a=m.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},d=a.keyType==="Custom"&&a.apiKey?a.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[a.quality]||"zimage",S=1024,T=1024;if(r){let z=r.replace(/\s+/g,"");z==="16:9"?(S=1024,T=576):z==="9:16"?(S=576,T=1024):z==="4:3"?(S=1024,T=768):z==="3:4"?(S=768,T=1024):z==="1:1"&&(S=1024,T=1024)}let w=Math.floor(Math.random()*1e7),L=`https://gen.pollinations.ai/image/${encodeURIComponent(n)}?model=${h}&width=${S}&height=${T}&seed=${w}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,_=await fetch(L,{method:"GET",headers:{Authorization:`Bearer ${d}`}});if(!_.ok){let z=_.status,mt="";try{mt=await _.text()}catch{}return z===402||mt.includes("Insufficient balance")||mt.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${z}]: ${mt||"Unknown API Error"}`}if((_.headers.get("content-type")||"").includes("application/json")){let z=await _.json();return z.status===402||z.error&&z.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${z.error?.message||JSON.stringify(z)}`}let v=await _.arrayBuffer(),b=Buffer.from(v),A={Title:n,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:n,Model:`Fluxflow:${h}`,Ratio:r||"1:1",Seed:String(w)};b=fu(b,A);let F=Ci.resolve(process.cwd(),s);await ml.ensureDir(Ci.dirname(F)),await kt.recordFileChange(F),await ml.writeFile(F,b),await qa(m);let Q=Ci.extname(s).toLowerCase(),Z={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[Q]||"image/png";return o.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:b.toString("base64"),mimeType:Z}}}:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}].`}catch(m){return`ERROR: Failed during image generation: ${m.message}`}}});var _r,pl=re(()=>{Lo();Bt();_r=async(e,o={})=>{let t=r=>{let l=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);return u?u[2].trim():null},n=t("id"),s=t("summary");if(!n||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=xe(Eo,{}),l=xe(Go,{});return l[n]=s,delete r[n],ke(Go,l),ke(Eo,r),`SUCCESS: Saved summary and purged raw memories for chat [${n}].`}catch(r){return`ERROR: Failed to save summary for chat [${n}]: ${r.message}`}}});var lr,hl=re(()=>{Lo();Bt();lr=async(e,o={})=>{let n=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),l=e.match(r);return l?l[2].trim():null})("id");if(!n)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=xe(Nt,[]),r=!1,l=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===n?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&l.push(c);if(ke(Nt,l),!r)return`WARNING: Memory ID [${n}] not found. Other memories decayed by -0.01.`;let u=l.find(c=>c.id===n),f=u?u.score.toFixed(2):"deleted (score <= 0)",m=s.length-l.length;return`SUCCESS: Adjusted memory scores. Target [${n}] is now ${f}.${m>0?` Purged ${m} decayed memories.`:""}`}catch(s){return`ERROR: Failed to adjust memory score for [${n}]: ${s.message}`}}});import Hn from"fs-extra";import Ii from"path";import pu from"https";async function Mi(e,o=null){let t=o||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,n=Ii.join(Tn,e);return await Hn.ensureDir(Tn),new Promise((s,r)=>{let l={headers:{"User-Agent":"FluxFlow-Agent"}};pu.get(t,l,u=>{if([301,302,307,308].includes(u.statusCode)&&u.headers.location){let m=u.headers.location;if(!m.startsWith("http")){let c=new URL(t);m=`${c.protocol}//${c.host}${m}`}Mi(e,m).then(s).catch(r);return}if(u.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${u.statusCode}`));return}let f=Hn.createWriteStream(n);u.pipe(f),f.on("finish",()=>{f.close(),s()})}).on("error",u=>{Hn.existsSync(n)&&Hn.unlink(n,()=>{}),r(u)})})}function xl(e){let o=Ii.join(Tn,e);return Hn.existsSync(o)}async function yl(e){let o=Ii.join(Tn,e);Hn.existsSync(o)&&await Hn.unlink(o)}var gl,vi=re(()=>{Bt();gl={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"}});import Ai from"fs-extra";import Xn from"path";import{createRequire as hu}from"module";function bl(e){if(e.type==="element"||e.type==="script_element"||e.type==="style_element"){let t=e.childForFieldName("start_tag")||e.children.find(s=>s.type==="start_tag");if(t){let s=t.childForFieldName("name")||t.children.find(r=>r.type==="tag_name");return s?s.text:null}let n=e.children.find(s=>s.type==="tag_name");return n?n.text:null}if(e.type==="jsx_element"||e.type==="jsx_self_closing_element"){let n=(e.childForFieldName("opening_element")||e).childForFieldName("name");return n?n.text:null}if(e.type==="import_declaration"||e.type==="import_from_statement"||e.type==="import_statement"||e.type==="preproc_include")return e.text.split(`
374
- `)[0].trim();if(e.type==="function_definition"||e.type==="function_declaration"){let t=e.childForFieldName("declarator");if(t){let n=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(n)return n.text}}let o=e.childForFieldName("name")||e.children.find(t=>t.type==="identifier"||t.type==="variable_declarator"||t.type==="type_identifier"||t.type==="field_identifier");if(o){if(o.type==="variable_declarator"){let t=o.childForFieldName("name")||o.children.find(n=>n.type==="identifier");return t?t.text:null}return o.text}if(e.type==="lexical_declaration"||e.type==="variable_declaration"){let t=e.children.find(n=>n.type==="variable_declarator");if(t)return bl(t)}if(e.type==="method_definition"||e.type==="function_declaration"){let t=e.childForFieldName("name")||e.children.find(n=>n.type==="identifier");if(t)return t.text}return null}function gu(e){let o=[];function t(n){for(let s of n.children)El.has(s.type)?o.push(s):t(s)}return t(e),o}function Cl(e,o=0,t=!0,n=""){if(o>6)return"";let r=e.type,l=El.has(r)||o===0,u="",f=n;if(l){let c=e.startPosition.row+1,a=e.endPosition.row+1,d=bl(e),p=d?`${r} [${d}]`:r;o===0?u+=`\u{1F4C1} ROOT (Lines: ${c}-${a})
375
- `:(u+=`${n}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${p} (Lines: ${c}-${a})
376
- `,f+=t?" ":"\u2502 ")}let m=gu(e);return m.forEach((c,a)=>{let d=a===m.length-1;u+=Cl(c,o+1,d,l?f:n)}),u}var Sl,wl,Tl,El,Oi,kl=re(()=>{vi();Bt();Xt();Sl=hu(import.meta.url),wl=Sl("web-tree-sitter"),Tl=!1,El=new Set(["class_declaration","function_declaration","method_definition","arrow_function","if_statement","for_statement","while_statement","do_statement","switch_statement","try_statement","variable_declaration","lexical_declaration","export_statement","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]);Oi=async e=>{let o;try{o=ne(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!o)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=Xn.isAbsolute(o)?o:Xn.resolve(process.cwd(),o);if(!Ai.existsSync(t))return`ERROR: File not found: ${o}`;let n=Xn.extname(t).slice(1).toLowerCase(),s=gl[n];if(!s)return`ERROR: Unsupported file extension: .${n}`;let r=Xn.resolve(Tn,s);if(!Ai.existsSync(r))return`ERROR: Parser for .${n} not found. Please download it in Settings > Other.`;try{let l=wl.Parser;if(!Tl){let d;try{d=Xn.join(Xn.dirname(Sl.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{d=Xn.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await l.init({locateFile:p=>p==="tree-sitter.wasm"||p.endsWith("tree-sitter.wasm")?d:p}),Tl=!0}let u=new l,f=await wl.Language.load(r);u.setLanguage(f);let m=await Ai.readFile(t,"utf8"),c=u.parse(m),a=Cl(c.rootNode);return`\u{1F4C4} File Map for: ${o}
372
+ `),c}catch(r){return`ERROR: ${r.message}`}}});import pl from"fs-extra";import bi from"path";var pu,Ci,hl=re(()=>{qt();es();fs();un();pu=(e,o={})=>{try{if(e.length<8||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return e;let t=[],n=[];for(let l=0;l<256;l++){let u=l;for(let f=0;f<8;f++)u&1?u=3988292384^u>>>1:u=u>>>1;n[l]=u}let s=l=>{let u=4294967295;for(let f=0;f<l.length;f++)u=n[(u^l[f])&255]^u>>>8;return(u^4294967295)>>>0},r=(l,u)=>{let f=Buffer.from(l,"ascii"),m=Buffer.from(u,"utf-8"),c=f.length+1+m.length,a=Buffer.alloc(8+c+4);a.writeUInt32BE(c,0),a.write("tEXt",4,"ascii"),f.copy(a,8),a[8+f.length]=0,m.copy(a,8+f.length+1);let d=s(a.subarray(4,8+c));return a.writeUInt32BE(d,8+c),a};for(let[l,u]of Object.entries(o))u!=null&&t.push(r(l,String(u)));if(t.length===0)return e;if(e.subarray(12,16).toString("ascii")==="IHDR"){let u=e.subarray(0,33),f=e.subarray(33);return Buffer.concat([u,...t,f])}return e}catch{return e}},Ci=async(e,o={})=>{let t=ne(e),n=t.prompt||t.text,s=t.path||t.outputPath||t.output||"generated_image.png",r=t.ratio;if(!n)return'ERROR: Missing "prompt" argument for generate_image.';let l=["nsfw","naked","nudity","nude","porn","sex","xxx","erotic","gore","bloody","violence","abuse","suicide","murder","hentai","pedophile","rape"],u=n.toLowerCase();if(l.some(m=>u.includes(m)))return"ERROR: Prompt blocked by system safety filter (inappropriate or unsafe content detected).";try{let m=await Zn();if(!await qa(m))return`ERROR: Insufficient Quota for selected quality. Either tell user reduce quality or wait for next refresh cycle (${(await ms()).nextResetMin||60}m).`;let a=m.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""},d=a.keyType==="Custom"&&a.apiKey?a.apiKey:FALLBACK_IMAGE_KEY,h={Low:"flux","Low-High":"zimage",Medium:"gptimage","Medium-High":"gptimage",High:"qwen-image",Ultra:"gptimage-large",Premium:"nanobanana-pro"}[a.quality]||"zimage",E=1024,w=1024;if(r){let J=r.replace(/\s+/g,"");J==="16:9"?(E=1024,w=576):J==="9:16"?(E=576,w=1024):J==="4:3"?(E=1024,w=768):J==="3:4"?(E=768,w=1024):J==="1:1"&&(E=1024,w=1024)}let T=Math.floor(Math.random()*1e7),O=`https://gen.pollinations.ai/image/${encodeURIComponent(n)}?model=${h}&width=${E}&height=${w}&seed=${T}&enhance=true&reasoning=high&quality=high&negative=${encodeURIComponent("deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated hands and fingers, blurry, low quality, low resolution, extra fingers, censored, watermarks, signatures")}`,P=await fetch(O,{method:"GET",headers:{Authorization:`Bearer ${d}`}});if(!P.ok){let J=P.status,ft="";try{ft=await P.text()}catch{}return J===402||ft.includes("Insufficient balance")||ft.includes("PAYMENT_REQUIRED")?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed with status [${J}]: ${ft||"Unknown API Error"}`}if((P.headers.get("content-type")||"").includes("application/json")){let J=await P.json();return J.status===402||J.error&&J.error.code==="PAYMENT_REQUIRED"?"ERROR: Image Generation Currently unavailable. Try again later.":`ERROR: Image Generation failed: ${J.error?.message||JSON.stringify(J)}`}let A=await P.arrayBuffer(),S=Buffer.from(A),v={Title:n,Description:"Generated via FluxFlow CLI",Software:"FluxFlow CLI",Author:"FluxFlow","Creation Time":new Date().toISOString(),Prompt:n,Model:`Fluxflow:${h}`,Ratio:r||"1:1",Seed:String(T)};S=pu(S,v);let F=bi.resolve(process.cwd(),s);await pl.ensureDir(bi.dirname(F)),await kt.recordFileChange(F),await pl.writeFile(F,S),await za(m);let V=bi.extname(s).toLowerCase(),Z={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".webp":"image/webp"}[V]||"image/png";return o.isMultiModal!==!1?{text:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}]. Output attached to multimodal part`,binaryPart:{inlineData:{data:S.toString("base64"),mimeType:Z}}}:`SUCCESS: Image successfully generated from prompt [${n}] and saved to [${s}].`}catch(m){return`ERROR: Failed during image generation: ${m.message}`}}});var _r,gl=re(()=>{Lo();Yt();_r=async(e,o={})=>{let t=r=>{let l=new RegExp(`${r}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),u=e.match(l);return u?u[2].trim():null},n=t("id"),s=t("summary");if(!n||!s)return"ERROR: Missing 'id' or 'summary' for saveSummary tool.";try{let r=Te(To,{}),l=Te(Yo,{});return l[n]=s,delete r[n],De(Yo,l),De(To,r),`SUCCESS: Saved summary and purged raw memories for chat [${n}].`}catch(r){return`ERROR: Failed to save summary for chat [${n}]: ${r.message}`}}});var sr,xl=re(()=>{Lo();Yt();sr=async(e,o={})=>{let n=(s=>{let r=new RegExp(`${s}\\s*[:=]\\s*(["'])(.*?)\\1(?=\\s*[,)]|\\s+\\w+\\s*[:=]|$)`,"s"),l=e.match(r);return l?l[2].trim():null})("id");if(!n)return"ERROR: Missing 'id' parameter for addMemScore tool.";try{let s=Te(Wt,[]),r=!1,l=[];for(let c of s)c.score===void 0&&(c.score=.5),c.id===n?(c.score=Math.min(2,c.score+.2),r=!0):(c.score*=.98,c.score<.05&&(c.score=0)),c.score=Math.round(c.score*1e5)/1e5,c.score>0&&l.push(c);if(De(Wt,l),!r)return`WARNING: Memory ID [${n}] not found. Other memories decayed by -0.01.`;let u=l.find(c=>c.id===n),f=u?u.score.toFixed(2):"deleted (score <= 0)",m=s.length-l.length;return`SUCCESS: Adjusted memory scores. Target [${n}] is now ${f}.${m>0?` Purged ${m} decayed memories.`:""}`}catch(s){return`ERROR: Failed to adjust memory score for [${n}]: ${s.message}`}}});import Gn from"fs-extra";import ki from"path";import hu from"https";async function Ii(e,o=null){let t=o||`https://unpkg.com/tree-sitter-wasms@0.1.13/out/${e}`,n=ki.join(gn,e);return await Gn.ensureDir(gn),new Promise((s,r)=>{let l={headers:{"User-Agent":"FluxFlow-Agent"}};hu.get(t,l,u=>{if([301,302,307,308].includes(u.statusCode)&&u.headers.location){let m=u.headers.location;if(!m.startsWith("http")){let c=new URL(t);m=`${c.protocol}//${c.host}${m}`}Ii(e,m).then(s).catch(r);return}if(u.statusCode!==200){r(new Error(`Failed to download ${e}: HTTP ${u.statusCode}`));return}let f=Gn.createWriteStream(n);u.pipe(f),f.on("finish",()=>{f.close(),s()})}).on("error",u=>{Gn.existsSync(n)&&Gn.unlink(n,()=>{}),r(u)})})}function wl(e){let o=ki.join(gn,e);return Gn.existsSync(o)}async function Tl(e){let o=ki.join(gn,e);Gn.existsSync(o)&&await Gn.unlink(o)}var yl,Ai=re(()=>{Yt();yl={js:"tree-sitter-javascript.wasm",jsx:"tree-sitter-javascript.wasm",ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",py:"tree-sitter-python.wasm",c:"tree-sitter-c.wasm",cpp:"tree-sitter-cpp.wasm",java:"tree-sitter-java.wasm",html:"tree-sitter-html.wasm"}});import Mi from"fs-extra";import Hn from"path";import{createRequire as gu}from"module";function kl(e){if(e.type==="element"||e.type==="script_element"||e.type==="style_element"){let t=e.childForFieldName("start_tag")||e.children.find(s=>s.type==="start_tag");if(t){let s=t.childForFieldName("name")||t.children.find(r=>r.type==="tag_name");return s?s.text:null}let n=e.children.find(s=>s.type==="tag_name");return n?n.text:null}if(e.type==="jsx_element"||e.type==="jsx_self_closing_element"){let n=(e.childForFieldName("opening_element")||e).childForFieldName("name");return n?n.text:null}if(e.type==="import_declaration"||e.type==="import_from_statement"||e.type==="import_statement"||e.type==="preproc_include")return e.text.split(`
373
+ `)[0].trim();if(e.type==="function_definition"||e.type==="function_declaration"){let t=e.childForFieldName("declarator");if(t){let n=t.descendantsOfType("identifier")[0]||t.descendantsOfType("field_identifier")[0];if(n)return n.text}}let o=e.childForFieldName("name")||e.children.find(t=>t.type==="identifier"||t.type==="variable_declarator"||t.type==="type_identifier"||t.type==="field_identifier");if(o){if(o.type==="variable_declarator"){let t=o.childForFieldName("name")||o.children.find(n=>n.type==="identifier");return t?t.text:null}return o.text}if(e.type==="lexical_declaration"||e.type==="variable_declaration"){let t=e.children.find(n=>n.type==="variable_declarator");if(t)return kl(t)}if(e.type==="method_definition"||e.type==="function_declaration"){let t=e.childForFieldName("name")||e.children.find(n=>n.type==="identifier");if(t)return t.text}return null}function xu(e){let o=[];function t(n){for(let s of n.children)Cl.has(s.type)?o.push(s):t(s)}return t(e),o}function yu(e){return e.replace(/_([a-z])/g,o=>o[1].toUpperCase())}function Il(e,o=0,t=!0,n=""){if(o>6)return"";let r=e.type,l=Cl.has(r)||o===0,u="",f=n;if(l){let c=e.startPosition.row+1,a=e.endPosition.row+1,d=kl(e),p=yu(r),h=d?`${p} [${d}]`:p;o===0?u+=`\u{1F4C1} ROOT (Lines: ${c}-${a})
374
+ `:(u+=`${n}${t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${h} (Lines: ${c}-${a})
375
+ `,f+=t?" ":"\u2502 ")}let m=xu(e);return m.forEach((c,a)=>{let d=a===m.length-1;u+=Il(c,o+1,d,l?f:n)}),u}var bl,Sl,El,Cl,vi,Al=re(()=>{Ai();Yt();qt();bl=gu(import.meta.url),Sl=bl("web-tree-sitter"),El=!1,Cl=new Set(["class_declaration","function_declaration","method_definition","arrow_function","if_statement","for_statement","while_statement","do_statement","switch_statement","try_statement","variable_declaration","lexical_declaration","export_statement","interface_declaration","type_alias_declaration","enum_declaration","import_declaration","jsx_element","jsx_self_closing_element","class_definition","function_definition","decorated_definition","import_from_statement","import_statement","preproc_include","method_declaration","constructor_declaration","class_specifier","struct_specifier","enum_specifier","field_declaration","element","script_element","style_element"]);vi=async e=>{let o;try{o=ne(e).path}catch{return`ERROR: Failed to parse arguments: ${e}`}if(!o)return'ERROR: No file path provided. Use [tool:functions.FileMap(path="...")]';let t=Hn.isAbsolute(o)?o:Hn.resolve(process.cwd(),o);if(!Mi.existsSync(t))return`ERROR: File not found: ${o}`;let n=Hn.extname(t).slice(1).toLowerCase(),s=yl[n];if(!s)return`ERROR: Unsupported file extension: .${n}`;let r=Hn.resolve(gn,s);if(!Mi.existsSync(r))return`ERROR: Parser for .${n} not found. Please download it in Settings > Other.`;try{let l=Sl.Parser;if(!El){let d;try{d=Hn.join(Hn.dirname(bl.resolve("web-tree-sitter")),"tree-sitter.wasm")}catch{d=Hn.join(process.cwd(),"node_modules","web-tree-sitter","tree-sitter.wasm")}await l.init({locateFile:p=>p==="tree-sitter.wasm"||p.endsWith("tree-sitter.wasm")?d:p}),El=!0}let u=new l,f=await Sl.Language.load(r);u.setLanguage(f);let m=await Mi.readFile(t,"utf8"),c=u.parse(m),a=Il(c.rootNode);return`\u{1F4C4} File Map for: ${o}
377
376
  ${a}`}catch(l){let u=l instanceof Error?l.message:typeof l=="object"?JSON.stringify(l):String(l),f=l instanceof Error?`
378
- Stack: ${l.stack}`:"";return`ERROR: Failed to map file: ${u}${f}`}}});var xu,ys,Il=re(async()=>{Va();za();Ja();Qa();el();ol();nl();await Dr();sl();il();al();cl();dl();fl();pl();hl();kl();xu={web_search:ci,web_scrape:ui,memory:di,chat:mi,view_file:fi,write_file:pi,update_file:gi,exec_command:Xs,read_folder:xi,write_pdf:wi,write_docx:Si,search_keyword:bi,generate_image:ki,saveSummary:_r,addMemScore:lr,file_map:Oi,ask:yi,Ask:yi,WebSearch:ci,WebScrape:ui,ReadFile:fi,ReadFolder:xi,WriteFile:pi,PatchFile:gi,WritePDF:wi,WriteDoc:Si,Run:Xs,SearchKeyword:bi,Memory:di,Chat:mi,GenerateImage:ki,saveSumary:_r,SaveSummary:_r,SaveSumary:_r,add_mem_score:lr,AddMemScore:lr,addMemoryScore:lr,AddMemoryScore:lr,FileMap:Oi},ys=async(e,o,t={})=>{if(t.mode&&t.mode.toLowerCase()==="flow"){let s=e.toLowerCase();if(!(s.startsWith("web")||s.startsWith("ask")))return`ERROR: Tool [${e}] is restricted in Flow mode.`}let n=xu[e];if(!n)return`ERROR: Tool [${e}] not found in registry.`;try{return await n(o,t)}catch(s){return`ERROR: Execution failed for [${e}]: ${s.message}`}}});import{WebSocket as ws}from"ws";var po,cr,yu,Di,ur,Li,Ml,Fi,$i,vl,Ts,Vo,Ss,Nr,Al,Pi,Ol,_i=re(()=>{po=null,cr=!1,yu="ws://localhost:56832",Di=[],ur=null,Li=null,Ml="2.0.0",Fi=e=>{Ml=e,vl()},$i=e=>{Li=e},vl=()=>{if(po||cr)return;cr=!0;let e=new ws(yu);e.on("open",()=>{for(po=e,cr=!1,po.send(JSON.stringify({command:"version",version:Ml,pid:process.pid,ppid:process.ppid}));Di.length>0;)po.send(JSON.stringify(Di.shift()))}),e.on("message",o=>{try{let t=JSON.parse(o.toString());t.command==="contextResponse"&&ur?(ur(t.data),ur=null):t.command==="securityResponse"&&Li&&Li(t.result)}catch{}}),e.on("error",()=>{cr=!1,po=null}),e.on("close",()=>{cr=!1,po=null})},Ts=e=>{po&&po.readyState===ws.OPEN?po.send(JSON.stringify(e)):(Di.push(e),cr||vl())},Vo=()=>po!==null&&po.readyState===ws.OPEN,Ss=e=>{Ts({command:"status",status:e})},Nr=()=>new Promise(e=>{if(!po||po.readyState!==ws.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}ur=e,po.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{ur===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),ur=null)},1e3)}),Al=e=>{Ts({command:"open",filePath:e})},Pi=(e,o,t)=>{Ts({command:"showDiff",filePath:e,originalContent:o,modifiedContent:t})},Ol=(e,o)=>{Ts({command:"closeDiff",filePath:e,result:o})}});import{GoogleGenAI as wu,ThinkingLevel as No,HarmBlockThreshold as On,HarmCategory as Dn}from"@google/genai";import Ee from"path";import dt from"fs";var mr,Bi,dr,Tu,Ni,Su,Fl,Ri,Wi,$l,Dl,Eu,Pl,bu,_l,Cu,Ll,Yi,Br,Ui,ku,Nl,Bl=re(async()=>{await _a();$r();hs();await Il();Lo();Xt();rn();Wn();Bt();un();_i();mr=null,Bi={},dr=!1,Tu=["google/gemma-4-31b-it:free","moonshotai/kimi-k2.6:free","google/gemini-3.5-flash","qwen/qwen3.7-plus","minimax/minimax-m3","anthropic/claude-sonnet-4.5","anthropic/claude-opus-4.6","anthropic/claude-opus-4.8","openai/gpt-5.2-codex","openai/gpt-5.2-pro","openai/gpt-5.5-pro","moonshotai/kimi-k2.6","gemma-4-31b-it","gemini-2.5-flash","gemini-3-flash-preview","gemini-3.5-flash","gemini-3.1-flash-lite","gemini-3.1-pro-preview"],Ni=e=>{if(!e)return!1;let o=e.toLowerCase();return o.startsWith("gemini-")||o.startsWith("gemma-")?!0:Tu.some(t=>t.toLowerCase()===o)},Su=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Fl=async(e,o,t=5,n=1e3)=>{for(let s=0;s<t;s++){try{let r=await fetch(e,o);if(r.ok||r.status!==429&&r.status<500)return r}catch(r){if(s===t-1)throw r}await new Promise(r=>setTimeout(r,n*Math.pow(2,s)))}return fetch(e,o)},Ri=async function*(e,o,t,n,s,r,l){let u=[];n&&u.push({role:"system",content:n});for(let w of t){let I=w.role==="user"?"user":"assistant",L=[];if(Array.isArray(w.parts)){for(let _ of w.parts)if(_.text)L.push({type:"text",text:_.text});else if(_.inlineData&&l){let R=_.inlineData.mimeType,v=_.inlineData.data;R.startsWith("image/")&&L.push({type:"image_url",image_url:{url:`data:${R};base64,${v}`}})}}else{let _=w.text||"";_&&L.push({type:"text",text:_})}u.push({role:I,content:L.length===1&&L[0].type==="text"?L[0].text:L})}let f={model:o,messages:u,stream:!0,stream_options:{include_usage:!0},temperature:r==="Flux"?1:1.4};if(s!=="Fast"){let w={Low:"high",Medium:"high",High:"high",Standard:"high",xHigh:"max"};f.reasoning_effort=w[s]||"high",f.extra_body={thinking:{type:"enabled"}}}else f.extra_body={thinking:{type:"disabled"}};let m=await Fl("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(f)});if(!m.ok){let w=await m.json().catch(()=>({}));throw new Error(`DeepSeek Error (${m.status}): ${w.error?.message||m.statusText}`)}let c=m.body.getReader(),a=new TextDecoder,d="",p=[],h=null,S=Date.now(),T=!1;for(;;){let{done:w,value:I}=await c.read();if(w){T&&(p.length>0||h)&&(yield{candidates:p.length>0?[{content:{parts:p}}]:[],usageMetadata:h});break}d+=a.decode(I,{stream:!0});let L=d.split(`
379
- `);d=L.pop();for(let _ of L){let R=_.trim();if(!(!R||!R.startsWith("data: "))){if(R==="data: [DONE]")break;try{let v=JSON.parse(R.substring(6)),b=v.choices?.[0]?.delta,A=v.usage;if(A&&(h={totalTokenCount:A.total_tokens||A.prompt_tokens+A.completion_tokens,promptTokenCount:A.prompt_tokens||0,candidatesTokenCount:A.completion_tokens||0,cachedContentTokenCount:A.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:A.completion_tokens_details?.reasoning_tokens||0},T=!0),b){let F=b.reasoning_content||null;F&&(p.push({text:F,thought:!0}),T=!0),b.content&&(p.push({text:b.content}),T=!0)}}catch{}}}Date.now()-S>=150&&T&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:h},p=[],S=Date.now(),T=!1)}},Wi=async function*(e,o,t,n,s,r,l){let u=[];n&&u.push({role:"system",content:n});for(let L of t){let _=L.role==="user"?"user":"assistant",R=[];if(Array.isArray(L.parts)){for(let v of L.parts)if(v.text)R.push({type:"text",text:v.text});else if(v.inlineData&&l){let b=v.inlineData.mimeType,A=v.inlineData.data;b.startsWith("image/")?R.push({type:"image_url",image_url:{url:`data:${b};base64,${A}`}}):R.push({type:"file",file:{filename:v.filename||"file",file_data:`data:${b};base64,${A}`}})}}else{let v=L.text||"";v&&R.push({type:"text",text:v})}u.push({role:_,content:R.length===1&&R[0].type==="text"?R[0].text:R})}let f={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m={model:o,messages:u,stream:!0,temperature:r==="Flux"?1:1.4},c=f[s];c&&s!=="Fast"&&(m.reasoning_effort=c);let a=await Fl("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true"},body:JSON.stringify(m)});if(!a.ok){let L=await a.json().catch(()=>({}));throw new Error(`OpenRouter Error (${a.status}): ${L.error?.message||a.statusText}`)}let d=a.body.getReader(),p=new TextDecoder,h="",S=[],T=null,w=Date.now(),I=!1;for(;;){let{done:L,value:_}=await d.read();if(L){I&&(S.length>0||T)&&(yield{candidates:S.length>0?[{content:{parts:S}}]:[],usageMetadata:T});break}h+=p.decode(_,{stream:!0});let R=h.split(`
380
- `);h=R.pop();for(let v of R){let b=v.trim();if(!(!b||!b.startsWith("data: "))){if(b==="data: [DONE]")break;try{let A=JSON.parse(b.substring(6)),F=A.choices?.[0]?.delta,Q=A.usage;if(Q&&(T={totalTokenCount:Q.total_tokens||Q.prompt_tokens+Q.completion_tokens,promptTokenCount:Q.prompt_tokens||0,candidatesTokenCount:Q.completion_tokens||0,cachedContentTokenCount:Q.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:Q.completion_tokens_details?.reasoning_tokens||0},I=!0),F){let j=F.reasoning||(F.reasoning_details?F.reasoning_details.map(Z=>Z.text).join(""):null);j&&(S.push({text:j,thought:!0}),I=!0),F.content&&(S.push({text:F.content}),I=!0)}}catch{}}}Date.now()-w>=150&&I&&(yield{candidates:S.length>0?[{content:{parts:[...S]}}]:[],usageMetadata:T},S=[],w=Date.now(),I=!1)}},$l=()=>{dr=!0},Dl={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating"},Eu=(e,o)=>{try{let t=ne(o),n=t.path||t.targetFile||t.TargetFile||t.directory;return n?Ee.basename(n.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},Pl=async(e,o,t,n,s={})=>{process.stdout.isTTY&&(process.stdout.write("\x1B]0;Finalizing...\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Finalizing...\x07"));let r=4*(1024*2),l=4*(1024*8),{onStatus:u,onMemoryUpdated:f,onBackgroundIncrement:m}=s,{profile:c,thinkingLevel:a,mode:d,janitorModel:p,chatId:h,systemSettings:S,sessionStats:T,aiProvider:w="Google",apiKey:I}=e,L=S?.memory!==!1,R=xe(Nt,[]).map(ue=>`- [${ue.id}]: ${ue.memory}`).join(`
381
- `),v=n.slice(0,-1).filter(ue=>ue.text&&!ue.text.includes("[TOOL RESULT]")&&!ue.text.includes("OBSERVATION:")&&!ue.text.startsWith("[TERMINAL_RECORD]")&&!ue.isTerminalRecord&&!ue.isMeta&&!ue.isLogo&&!String(ue.id).startsWith("welcome")&&!String(ue.id).startsWith("logo")).slice(-14).map(ue=>{let tt=Su(ue.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(je,ye)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${ye.replace(/:\d{2}/g,"")}`).replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
377
+ Stack: ${l.stack}`:"";return`ERROR: Failed to map file: ${u}${f}`}}});var wu,gs,Ml=re(async()=>{Ja();Qa();Za();el();ol();rl();sl();await Or();al();ll();cl();dl();fl();hl();gl();xl();Al();wu={web_search:li,web_scrape:ci,memory:ui,chat:di,view_file:mi,write_file:fi,update_file:hi,exec_command:Hs,read_folder:gi,write_pdf:yi,write_docx:Ti,search_keyword:Ei,generate_image:Ci,saveSummary:_r,addMemScore:sr,file_map:vi,ask:xi,Ask:xi,WebSearch:li,WebScrape:ci,ReadFile:mi,ReadFolder:gi,WriteFile:fi,PatchFile:hi,WritePDF:yi,WriteDoc:Ti,Run:Hs,SearchKeyword:Ei,Memory:ui,Chat:di,GenerateImage:Ci,saveSumary:_r,SaveSummary:_r,SaveSumary:_r,add_mem_score:sr,AddMemScore:sr,addMemoryScore:sr,AddMemoryScore:sr,FileMap:vi},gs=async(e,o,t={})=>{if(t.mode&&t.mode.toLowerCase()==="flow"){let s=e.toLowerCase();if(!(s.startsWith("web")||s.startsWith("ask")))return`ERROR: Tool [${e}] is restricted in Flow mode.`}let n=wu[e];if(!n)return`ERROR: Tool [${e}] not found in registry.`;try{return await n(o,t)}catch(s){return`ERROR: Execution failed for [${e}]: ${s.message}`}}});import{WebSocket as xs}from"ws";var po,ir,Tu,Di,ar,Oi,vl,Li,Fi,Dl,ys,Ko,ws,Nr,Ol,$i,Ll,Pi=re(()=>{po=null,ir=!1,Tu="ws://localhost:56832",Di=[],ar=null,Oi=null,vl="2.0.0",Li=e=>{vl=e,Dl()},Fi=e=>{Oi=e},Dl=()=>{if(po||ir)return;ir=!0;let e=new xs(Tu);e.on("open",()=>{for(po=e,ir=!1,po.send(JSON.stringify({command:"version",version:vl,pid:process.pid,ppid:process.ppid}));Di.length>0;)po.send(JSON.stringify(Di.shift()))}),e.on("message",o=>{try{let t=JSON.parse(o.toString());t.command==="contextResponse"&&ar?(ar(t.data),ar=null):t.command==="securityResponse"&&Oi&&Oi(t.result)}catch{}}),e.on("error",()=>{ir=!1,po=null}),e.on("close",()=>{ir=!1,po=null})},ys=e=>{po&&po.readyState===xs.OPEN?po.send(JSON.stringify(e)):(Di.push(e),ir||Dl())},Ko=()=>po!==null&&po.readyState===xs.OPEN,ws=e=>{ys({command:"status",status:e})},Nr=()=>new Promise(e=>{if(!po||po.readyState!==xs.OPEN){e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]});return}ar=e,po.send(JSON.stringify({command:"requestContext"})),setTimeout(()=>{ar===e&&(e({cursor_line:0,selected:0,manual_edits:"",file_focused:"none",opened_editors:[]}),ar=null)},1e3)}),Ol=e=>{ys({command:"open",filePath:e})},$i=(e,o,t)=>{ys({command:"showDiff",filePath:e,originalContent:o,modifiedContent:t})},Ll=(e,o)=>{ys({command:"closeDiff",filePath:e,result:o})}});import{GoogleGenAI as Su,ThinkingLevel as No,HarmBlockThreshold as kn,HarmCategory as In}from"@google/genai";import ke from"path";import mt from"fs";var cr,Ni,lr,Eu,_i,bu,Ui,Ri,Wi,Yi,Pl,Fl,Cu,_l,ku,Nl,Iu,$l,ji,Br,Bi,Au,Bl,Ul=re(async()=>{await Ba();$r();fs();await Ml();Lo();qt();rn();Rn();Yt();un();Pi();cr=null,Ni={},lr=!1,Eu=["google/gemma-4-31b-it:free","moonshotai/kimi-k2.6:free","google/gemini-3.5-flash","qwen/qwen3.7-plus","minimax/minimax-m3","anthropic/claude-sonnet-4.5","anthropic/claude-opus-4.6","anthropic/claude-opus-4.8","openai/gpt-5.2-codex","openai/gpt-5.2-pro","openai/gpt-5.5-pro","moonshotai/kimi-k2.6","moonshotai/kimi-k2.6","gemma-4-31b-it","gemini-2.5-flash","gemini-3-flash-preview","gemini-3.5-flash","gemini-3.1-flash-lite","gemini-3.1-pro-preview"],_i=e=>{if(!e)return!1;let o=e.toLowerCase();return o.startsWith("gemini-")||o.startsWith("gemma-")?!0:Eu.some(t=>t.toLowerCase()===o)},bu=e=>typeof e!="string"?e:e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,""),Ui=async(e,o,t=5,n=1e3)=>{for(let s=0;s<t;s++){try{let r=await fetch(e,o);if(r.ok||r.status!==429&&r.status<500)return r}catch(r){if(s===t-1)throw r}await new Promise(r=>setTimeout(r,n*Math.pow(2,s)))}return fetch(e,o)},Ri=async function*(e,o,t,n,s,r,l){let u=[];n&&u.push({role:"system",content:n});for(let T of t){let I=T.role==="user"?"user":"assistant",O=[];if(Array.isArray(T.parts)){for(let P of T.parts)if(P.text)O.push({type:"text",text:P.text});else if(P.inlineData&&l){let U=P.inlineData.mimeType,A=P.inlineData.data;U.startsWith("image/")&&O.push({type:"image_url",image_url:{url:`data:${U};base64,${A}`}})}}else{let P=T.text||"";P&&O.push({type:"text",text:P})}u.push({role:I,content:O.length===1&&O[0].type==="text"?O[0].text:O})}let f={model:o,messages:u,stream:!0,stream_options:{include_usage:!0},temperature:r==="Flux"?1:1.4};if(s!=="Fast"){let T={Low:"high",Medium:"high",High:"high",Standard:"high",xHigh:"max"};f.reasoning_effort=T[s]||"high",f.extra_body={thinking:{type:"enabled"}}}else f.extra_body={thinking:{type:"disabled"}};let m=await Ui("https://api.deepseek.com/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(f)});if(!m.ok){let T=await m.json().catch(()=>({}));throw new Error(`DeepSeek Error (${m.status}): ${T.error?.message||m.statusText}`)}let c=m.body.getReader(),a=new TextDecoder,d="",p=[],h=null,E=Date.now(),w=!1;for(;;){let{done:T,value:I}=await c.read();if(T){w&&(p.length>0||h)&&(yield{candidates:p.length>0?[{content:{parts:p}}]:[],usageMetadata:h});break}d+=a.decode(I,{stream:!0});let O=d.split(`
378
+ `);d=O.pop();for(let P of O){let U=P.trim();if(!(!U||!U.startsWith("data: "))){if(U==="data: [DONE]")break;try{let A=JSON.parse(U.substring(6)),S=A.choices?.[0]?.delta,v=A.usage;if(v&&(h={totalTokenCount:v.total_tokens||v.prompt_tokens+v.completion_tokens,promptTokenCount:v.prompt_tokens||0,candidatesTokenCount:v.completion_tokens||0,cachedContentTokenCount:v.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:v.completion_tokens_details?.reasoning_tokens||0},w=!0),S){let F=S.reasoning_content||null;F&&(p.push({text:F,thought:!0}),w=!0),S.content&&(p.push({text:S.content}),w=!0)}}catch{}}}Date.now()-E>=150&&w&&(yield{candidates:p.length>0?[{content:{parts:[...p]}}]:[],usageMetadata:h},p=[],E=Date.now(),w=!1)}},Wi=async function*(e,o,t,n,s,r,l=!1){let u=[];n&&u.push({role:"system",content:n}),t.forEach(P=>{let U=P.role==="model"?"assistant":"user",A=[];Array.isArray(P.parts)&&P.parts.forEach(S=>{if(S.text)A.push({type:"text",text:S.text});else if(S.inlineData&&l){let v=S.inlineData.mimeType,F=S.inlineData.data;v.startsWith("image/")&&A.push({type:"image_url",image_url:{url:`data:${v};base64,${F}`}})}}),u.push({role:U,content:A.length===1&&A[0].type==="text"?A[0].text:A})});let m={Low:512,Medium:4096,High:8192,xHigh:16384}[s]||0,c=s!=="Fast"&&m>0,a={model:o,messages:u,temperature:r==="Flux"?.7:1,top_p:c?.95:.7,max_tokens:16384,stream:!0,stream_options:{include_usage:!0}};c&&!r.includes("deepseek")&&(a.reasoning_budget=o.includes("gemma-4")?16384:m,o.includes("minimax")||(a.chat_template_kwargs={enable_thinking:!0})),o.includes("deepseek")&&c&&(a.chat_template_kwargs={enable_thinking:!0,reasoning_effort:"high"});let d=await Ui("https://integrate.api.nvidia.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)});if(!d.ok){let P=await d.json(),U=new Error(`NVIDIA API Error: ${P.error?.message||d.statusText}`);throw U.status=d.status,U}let p=d.body.getReader(),h=new TextDecoder,E="",w=[],T=null,I=Date.now(),O=!1;for(;;){let{done:P,value:U}=await p.read();if(P){O&&(w.length>0||T)&&(yield{candidates:w.length>0?[{content:{parts:w}}]:[],usageMetadata:T});break}E+=h.decode(U,{stream:!0});let A=E.split(`
379
+ `);E=A.pop();for(let S of A){let v=S.trim();if(!(!v||v==="data: [DONE]")&&v.startsWith("data: "))try{let F=JSON.parse(v.substring(6)),V=F.usage;V&&(T={totalTokenCount:V.total_tokens||V.prompt_tokens+V.completion_tokens,promptTokenCount:V.prompt_tokens||0,candidatesTokenCount:V.completion_tokens||0,thoughtsTokenCount:(V.completion_tokens_details?.reasoning_tokens||0)+(V.completion_tokens_details?.thoughts_tokens||0)},O=!0);let Y=F.choices?.[0]?.delta?.reasoning||F.choices?.[0]?.delta?.reasoning_content||"",Z=F.choices?.[0]?.delta?.content||"";Y&&(w.push({text:Y,thought:!0}),O=!0),Z&&(w.push({text:Z}),O=!0)}catch{}}Date.now()-I>=350&&O&&(yield{candidates:w.length>0?[{content:{parts:[...w]}}]:[],usageMetadata:T},w=[],I=Date.now(),O=!1)}},Yi=async function*(e,o,t,n,s,r,l){let u=[];n&&u.push({role:"system",content:n});for(let O of t){let P=O.role==="user"?"user":"assistant",U=[];if(Array.isArray(O.parts)){for(let A of O.parts)if(A.text)U.push({type:"text",text:A.text});else if(A.inlineData&&l){let S=A.inlineData.mimeType,v=A.inlineData.data;S.startsWith("image/")?U.push({type:"image_url",image_url:{url:`data:${S};base64,${v}`}}):U.push({type:"file",file:{filename:A.filename||"file",file_data:`data:${S};base64,${v}`}})}}else{let A=O.text||"";A&&U.push({type:"text",text:A})}u.push({role:P,content:U.length===1&&U[0].type==="text"?U[0].text:U})}let f={Low:"low",Medium:"medium",Standard:"medium",High:"high",xHigh:"high"},m={model:o,messages:u,stream:!0,temperature:r==="Flux"?1:1.4},c=f[s];c&&s!=="Fast"&&(m.reasoning_effort=c);let a=await Ui("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-Title":"FluxFlow CLI","X-Cache":"true"},body:JSON.stringify(m)});if(!a.ok){let O=await a.json().catch(()=>({}));throw new Error(`OpenRouter Error (${a.status}): ${O.error?.message||a.statusText}`)}let d=a.body.getReader(),p=new TextDecoder,h="",E=[],w=null,T=Date.now(),I=!1;for(;;){let{done:O,value:P}=await d.read();if(O){I&&(E.length>0||w)&&(yield{candidates:E.length>0?[{content:{parts:E}}]:[],usageMetadata:w});break}h+=p.decode(P,{stream:!0});let U=h.split(`
380
+ `);h=U.pop();for(let A of U){let S=A.trim();if(!(!S||!S.startsWith("data: "))){if(S==="data: [DONE]")break;try{let v=JSON.parse(S.substring(6)),F=v.choices?.[0]?.delta,V=v.usage;if(V&&(w={totalTokenCount:V.total_tokens||V.prompt_tokens+V.completion_tokens,promptTokenCount:V.prompt_tokens||0,candidatesTokenCount:V.completion_tokens||0,cachedContentTokenCount:V.prompt_tokens_details?.cached_tokens||0,thoughtsTokenCount:V.completion_tokens_details?.reasoning_tokens||0},I=!0),F){let Y=F.reasoning||(F.reasoning_details?F.reasoning_details.map(Z=>Z.text).join(""):null);Y&&(E.push({text:Y,thought:!0}),I=!0),F.content&&(E.push({text:F.content}),I=!0)}}catch{}}}Date.now()-T>=150&&I&&(yield{candidates:E.length>0?[{content:{parts:[...E]}}]:[],usageMetadata:w},E=[],T=Date.now(),I=!1)}},Pl=()=>{lr=!0},Fl={write_file:"Writing",update_file:"Editing",read_folder:"Reading",view_file:"Reading",exec_command:"Executing Command",web_search:"Searching",web_scrape:"Reading",memory:"Updating Memory",search_keyword:"Searching",file_map:"Generating Map",ask:"User Input",write_pdf:"Creating",write_docx:"Creating",generate_image:"Generating"},Cu=(e,o)=>{try{let t=ne(o),n=t.path||t.targetFile||t.TargetFile||t.directory;return n?ke.basename(n.replace(/["']/g,"").replace(/\\/g,"/")):null}catch{return null}},_l=async(e,o,t,n,s={})=>{process.stdout.isTTY&&(process.stdout.write("\x1B]0;Finalizing...\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Finalizing...\x07"));let r=4*(1024*2),l=4*(1024*8),{onStatus:u,onMemoryUpdated:f,onBackgroundIncrement:m}=s,{profile:c,thinkingLevel:a,mode:d,janitorModel:p,chatId:h,systemSettings:E,sessionStats:w,aiProvider:T="Google",apiKey:I}=e,O=E?.memory!==!1,U=Te(Wt,[]).map(me=>`- [${me.id}]: ${me.memory}`).join(`
381
+ `),A=n.slice(0,-1).filter(me=>me.text&&!me.text.includes("[TOOL RESULT]")&&!me.text.includes("OBSERVATION:")&&!me.text.startsWith("[TERMINAL_RECORD]")&&!me.isTerminalRecord&&!me.isMeta&&!me.isLogo&&!String(me.id).startsWith("welcome")&&!String(me.id).startsWith("logo")).slice(-14).map(me=>{let Ze=bu(me.text).replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[METADATA \(PRIORITY: DYNAMIC\)\] Time: ([^|\n]+)/g,(Ge,Se)=>`[METADATA (PRIORITY: DYNAMIC)] Time: ${Se.replace(/:\d{2}/g,"")}`).replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").replace(/\r?\n\r?\n/g,`
382
382
  `).replace(/\n\n/g,`
383
- `).replace(/\\n\\n/g,"").trim(),Ye=ue.role==="user"?r:l,_e=tt.substring(0,Ye);tt.length>Ye&&(_e+=`
384
- ... (truncated) ...`);let Me=ue.role==="user"?_e.startsWith("[USER]")?"":"[USER]: ":_e.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:ue.role==="user"?"user":"model",parts:[{text:`${Me}${_e}`}]}}),b=n.filter(ue=>ue.role==="user").length===1,A=o.includes("[TITLE-UPDATE]"),F=Math.random()<.8,Q=b||A||F,j=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),Z=Pa(R,L,Q),B=`${j.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").substring(0,l)}`;B.length>l&&(B+=`
385
- ... (truncated) ...`);let z=o.replace(/\[Prompted on:.*?\]/g,"").trim();B=B.replace(/\r?\n\r?\n/g,`
383
+ `).replace(/\\n\\n/g,"").trim(),je=me.role==="user"?r:l,Be=Ze.substring(0,je);Ze.length>je&&(Be+=`
384
+ ... (truncated) ...`);let Le=me.role==="user"?Be.startsWith("[USER]")?"":"[USER]: ":Be.startsWith("[AGENT]")?"":"[AGENT]: ";return{role:me.role==="user"?"user":"model",parts:[{text:`${Le}${Be}`}]}}),S=n.filter(me=>me.role==="user").length===1,v=o.includes("[TITLE-UPDATE]"),F=Math.random()<.8,V=S||v||F,Y=t.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim(),Z=Na(U,O,V),N=`${Y.replace(/\[tool:functions\..*?\]/g,"").replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").replace(/\[Prompted on:.*?\]/g,"").replace(/\[turn: continue\]/g,"").replace(/\[turn: finish\]/g,"").replace(/\[\[END\]\]/g,"").replace(/\[TOOL RESULTS\]/g,"").replace(/\[tool results\]/g,"").substring(0,l)}`;N.length>l&&(N+=`
385
+ ... (truncated) ...`);let J=o.replace(/\[Prompted on:.*?\]/g,"").trim();N=N.replace(/\r?\n\r?\n/g,`
386
386
  `).replace(/\n\n/g,`
387
- `).replace(/\\n\\n/g,"").trim();let mt=`[USER]: ${z.substring(0,r)}
388
- ${z.length>r?`... (truncated) ...
387
+ `).replace(/\\n\\n/g,"").trim();let ft=`[USER]: ${J.substring(0,r)}
388
+ ${J.length>r?`... (truncated) ...
389
389
 
390
390
  `:""}
391
- [AGENT (current turn)]: ${B}`;v.push({role:"user",parts:[{text:mt}]});let ce="",Le=0,Je=L?12:-1;for(;Le<=Je;){process.stdout.isTTY&&(process.stdout.write(`\x1B]0;Retrying Finalizing... (${Le+1})...\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=Retrying Finalizing... (${Le+1})...\x07`));try{if(!await ai("background",e))return;let ue="",tt=null;try{let Me=new Promise((Wt,be)=>setTimeout(()=>be(new Error("JANITOR_TIMEOUT")),6e4)),je=(async()=>{if(w==="OpenRouter"){let rt=Wi(I,"google/gemma-4-26b-a4b-it:free",v,Z,"Fast",d)[Symbol.asyncIterator](),Ao=await rt.next();return{iterator:rt,firstResult:Ao}}else if(w==="DeepSeek"){let be=Ri(I,"deepseek-chat",v,Z,"Fast",d,!1)[Symbol.asyncIterator](),rt=await be.next();return{iterator:be,firstResult:rt}}else{let be=(await mr.models.generateContentStream({model:p||"gemma-4-26b-a4b-it",contents:v,config:{systemInstruction:Z,maxOutputTokens:512,temperature:.3,safetySettings:[{category:Dn.HARM_CATEGORY_HARASSMENT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_HATE_SPEECH,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:On.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:No.MINIMAL}}}))[Symbol.asyncIterator](),rt=await be.next();return{iterator:be,firstResult:rt}}})(),{iterator:ye,firstResult:ft}=await Promise.race([je,Me]),{value:pt,done:lo}=ft;if(!lo&&pt){let Wt=pt.candidates?.[0]?.content?.parts,be=Wt?.[1]?.text||Wt?.[0]?.text||(typeof pt.text=="function"?pt.text():"");be&&(ue+=be),tt=pt.usageMetadata;for await(let rt of{[Symbol.asyncIterator]:()=>ye}){let Ao=rt.candidates?.[0]?.content?.parts,co=Ao?.[1]?.text||Ao?.[0]?.text||(typeof rt.text=="function"?rt.text():"");co&&(ue+=co),tt=rt.usageMetadata}}}catch(Me){throw Me}if(ue)ce=ue,tt&&await Co("tokens",tt.totalTokenCount||0);else throw new Error("No synthesis generated by Janitor.");m&&(m(),await qo("background"));let Ye=Yi(ce),_e=!1;for(let Me of Ye){let je=Me.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(je)&&(_e=!0);let ye={chatId:h,sessionId:h,history:n},ft=await ys(je,Me.args,ye);je.toLowerCase()==="memory"&&(Me.args.includes("action='user'")||Me.args.includes('action="user"'))&&!ft.startsWith("ERROR")&&(f&&f(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(lo=>setTimeout(lo,3e3)))}if(!_e)try{let Me=xe(Nt,[]);if(Me.length>0){let je=[];for(let ye of Me)ye.score===void 0&&(ye.score=.5),ye.score*=.9995,ye.score<.05&&(ye.score=0),ye.score=Math.round(ye.score*1e5)/1e5,ye.score>0&&je.push(ye);ke(Nt,je)}}catch{}break}catch(ue){Le++;let tt=new Date().toLocaleString();process.stdout.isTTY&&process.stdout.write("\x1B]0;Finalizing Error\x07"),await new Promise(Me=>setTimeout(Me,1e3));let Ye=Ee.join(Io,"janitor");if(dt.existsSync(Ye)||dt.mkdirSync(Ye,{recursive:!0}),dt.appendFileSync(Ee.join(Ye,"error.log"),`ERROR [Attempt ${Le}/${Je+1}] [${tt}]: ${String(ue)}
391
+ [AGENT (current turn)]: ${N}`;A.push({role:"user",parts:[{text:ft}]});let de="",$e=0,qe=O?12:-1;for(;$e<=qe;){process.stdout.isTTY&&(process.stdout.write(`\x1B]0;Retrying Finalizing... (${$e+1})...\x07`),process.stdout.write(`\x1B]633;P;TerminalTitle=Retrying Finalizing... (${$e+1})...\x07`));try{if(!await ii("background",e))return;let me="",Ze=null;try{let Le=new Promise((Nt,be)=>setTimeout(()=>be(new Error("JANITOR_TIMEOUT")),6e4)),Ge=(async()=>{if(T==="OpenRouter"){let ze=Yi(I,"google/gemma-4-26b-a4b-it:free",A,Z,"Fast",d)[Symbol.asyncIterator](),Mo=await ze.next();return{iterator:ze,firstResult:Mo}}else if(T==="DeepSeek"){let be=Ri(I,"deepseek-chat",A,Z,"Fast",d,!1)[Symbol.asyncIterator](),ze=await be.next();return{iterator:be,firstResult:ze}}else if(T==="NVIDIA"){let be=Wi(I,"deepseek-ai/deepseek-v4-flash",A,Z,"Fast",d,!1)[Symbol.asyncIterator](),ze=await be.next();return{iterator:be,firstResult:ze}}else{let be=(await cr.models.generateContentStream({model:p||"gemma-4-26b-a4b-it",contents:A,config:{systemInstruction:Z,maxOutputTokens:512,temperature:.3,safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:kn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:kn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:kn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:kn.BLOCK_NONE}],thinkingConfig:{includeThoughts:!1,thinkingLevel:No.MINIMAL}}}))[Symbol.asyncIterator](),ze=await be.next();return{iterator:be,firstResult:ze}}})(),{iterator:Se,firstResult:pt}=await Promise.race([Ge,Le]),{value:ht,done:lo}=pt;if(!lo&&ht){let Nt=ht.candidates?.[0]?.content?.parts,be=Nt?.[1]?.text||Nt?.[0]?.text||(typeof ht.text=="function"?ht.text():"");be&&(me+=be),Ze=ht.usageMetadata;for await(let ze of{[Symbol.asyncIterator]:()=>Se}){let Mo=ze.candidates?.[0]?.content?.parts,co=Mo?.[1]?.text||Mo?.[0]?.text||(typeof ze.text=="function"?ze.text():"");co&&(me+=co),Ze=ze.usageMetadata}}}catch(Le){throw Le}if(me)de=me,Ze&&await Eo("tokens",Ze.totalTokenCount||0);else throw new Error("No synthesis generated by Janitor.");m&&(m(),await Xo("background"));let je=ji(de),Be=!1;for(let Le of je){let Ge=Le.toolName;["addMemScore","add_mem_score","AddMemScore","addMemoryScore","AddMemoryScore"].includes(Ge)&&(Be=!0);let Se={chatId:h,sessionId:h,history:n},pt=await gs(Ge,Le.args,Se);Ge.toLowerCase()==="memory"&&(Le.args.includes("action='user'")||Le.args.includes('action="user"'))&&!pt.startsWith("ERROR")&&(f&&f(),process.stdout.isTTY&&(process.stdout.write("\x1B]0;Memory Updated\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=Memory Updated\x07")),await new Promise(lo=>setTimeout(lo,3e3)))}if(!Be)try{let Le=Te(Wt,[]);if(Le.length>0){let Ge=[];for(let Se of Le)Se.score===void 0&&(Se.score=.5),Se.score*=.9995,Se.score<.05&&(Se.score=0),Se.score=Math.round(Se.score*1e5)/1e5,Se.score>0&&Ge.push(Se);De(Wt,Ge)}}catch{}break}catch(me){$e++;let Ze=new Date().toLocaleString();process.stdout.isTTY&&process.stdout.write("\x1B]0;Finalizing Error\x07"),await new Promise(Le=>setTimeout(Le,1e3));let je=ke.join(ko,"janitor");if(mt.existsSync(je)||mt.mkdirSync(je,{recursive:!0}),mt.appendFileSync(ke.join(je,"error.log"),`ERROR [Attempt ${$e}/${qe+1}] [${Ze}]: ${String(me)}
392
392
 
393
- `),Le>Je)break;let _e=Math.min(1e3*Math.pow(2,Le-1),8e3);await new Promise(Me=>setTimeout(Me,_e))}}if(Le){let ue=Ee.join(Io,"janitor");dt.appendFileSync(Ee.join(ue,"error.log"),`-----------------------------------------------------------------------------
393
+ `),$e>qe)break;let Be=Math.min(1e3*Math.pow(2,$e-1),8e3);await new Promise(Le=>setTimeout(Le,Be))}}if($e){let me=ke.join(ko,"janitor");mt.appendFileSync(ke.join(me,"error.log"),`-----------------------------------------------------------------------------
394
394
 
395
395
 
396
- `),Le>=Je&&(process.stdout.isTTY&&process.stdout.write(`\x1B]0;${L?"Finalizing Error":"Finalizing Skipped"}\x07`),await new Promise(tt=>setTimeout(tt,3e3)))}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07"))},bu=e=>{let o=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,t;for(;(t=o.exec(e))!==null;){let n=t.index+t[0].length-1,s=0,r=null,l=!1,u=!1;for(let f=n;f<e.length;f++){let m=e[f];if(!r&&(m==='"'||m==="'"||m==="`")?(r=m,l=!1):r&&m===r&&!l&&(r=null),!r&&(m==="("?s++:m===")"&&s--,s===0)){let c=f+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){u=!0,o.lastIndex=c+1;break}}m==="\\"?l=!l:l=!1}if(!u)return{inside:!0,toolName:t[1],startIndex:t.index,args:e.substring(t.index+t[0].length)}}return{inside:!1}},_l=(e,o=!0)=>{let t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n="",s=0,r;for(;(r=t.exec(e))!==null;){let l=e.substring(s,r.index);n+=o?l.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):l;let u=r.index+r[0].length-1,f=0,m=null,c=-1;for(let a=u;a<e.length;a++){let d=e[a];if(m){if(d===m){let p=0;for(let h=a-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(m=null)}}else if(d==='"'||d==="'"||d==="`")m=d;else if(d==="(")f++;else if(d===")"&&(f--,f===0)){let p=a+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){c=p;break}}}if(c!==-1)n+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{n+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(n+=o?e.substring(s).replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):e.substring(s)),n},Cu=(e,o,t)=>{let n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s="",r=0,l;for(;(l=n.exec(e))!==null;){let u=e.substring(r,l.index);s+=u.replace(o,t);let f=l.index+l[0].length-1,m=0,c=null,a=-1;for(let d=f;d<e.length;d++){let p=e[d];if(c){if(p===c){let h=0;for(let S=d-1;S>=0&&e[S]==="\\";S--)h++;h%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")m++;else if(p===")"&&(m--,m===0)){let h=d+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){a=h;break}}}if(a!==-1)s+=e.substring(l.index,a+1),r=a+1,n.lastIndex=r;else{s+=e.substring(l.index),r=e.length;break}}return r<e.length&&(s+=e.substring(r).replace(o,t)),s},Ll=e=>_l(e,!0),Yi=e=>{if(!e)return[];let o=e.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),t=[],n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s;for(;(s=n.exec(o))!==null;){let r=s[1],l=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=l;a<o.length;a++){let d=o[a];if(f){if(d===f){let p=0;for(let h=a-1;h>=0&&o[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let p=a+1;for(;p<o.length&&/\s/.test(o[p]);)p++;if(p<o.length&&o[p]==="]"){m=p;break}}}if(m!==-1){let a=o.substring(l+1,c),d=o.substring(s.index,m+1);t.push({fullMatch:d,toolName:r.trim(),args:a.trim()}),n.lastIndex=m+1}}return t},Br=(e,o={})=>e?(Bi=o,mr=new wu({apiKey:e}),mr):null,Ui=async(e,o,t,n,s="Fast")=>{let{aiProvider:r="Google",apiKey:l,mode:u}=e,f="",m=null,c;r==="OpenRouter"?c=Wi(l,o,t,n,s,u,!1):r==="DeepSeek"?c=Ri(l,o,t,n,s,u,!1):c=await mr.models.generateContentStream({model:o,contents:t,config:{systemInstruction:n,maxOutputTokens:2048,temperature:.3,thinkingConfig:{includeThoughts:!1,thinkingLevel:No.MINIMAL}}});for await(let a of c){if(a.candidates?.[0]?.content?.parts)for(let d of a.candidates[0].content.parts)d.text&&!d.thought&&(f+=d.text);a.usageMetadata&&(m=a.usageMetadata)}return{text:f,usageMetadata:m}},ku=async(e,o)=>{try{let{aiProvider:t="Google"}=o,n=xe(Eo,{});if(Object.values(n).flat().length<=2)return;let r=Object.keys(n).filter(d=>d!==e&&Array.isArray(n[d])&&n[d].length>2);if(r.length===0)return;let l=`You are a silent background process for the FluxFlow CLI Agent.
396
+ `),$e>=qe&&(process.stdout.isTTY&&process.stdout.write(`\x1B]0;${O?"Finalizing Error":"Finalizing Skipped"}\x07`),await new Promise(Ze=>setTimeout(Ze,3e3)))}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07"))},ku=e=>{let o=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,t;for(;(t=o.exec(e))!==null;){let n=t.index+t[0].length-1,s=0,r=null,l=!1,u=!1;for(let f=n;f<e.length;f++){let m=e[f];if(!r&&(m==='"'||m==="'"||m==="`")?(r=m,l=!1):r&&m===r&&!l&&(r=null),!r&&(m==="("?s++:m===")"&&s--,s===0)){let c=f+1;for(;c<e.length&&/\s/.test(e[c]);)c++;if(c<e.length&&e[c]==="]"){u=!0,o.lastIndex=c+1;break}}m==="\\"?l=!l:l=!1}if(!u)return{inside:!0,toolName:t[1],startIndex:t.index,args:e.substring(t.index+t[0].length)}}return{inside:!1}},Nl=(e,o=!0)=>{let t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n="",s=0,r;for(;(r=t.exec(e))!==null;){let l=e.substring(s,r.index);n+=o?l.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):l;let u=r.index+r[0].length-1,f=0,m=null,c=-1;for(let a=u;a<e.length;a++){let d=e[a];if(m){if(d===m){let p=0;for(let h=a-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(m=null)}}else if(d==='"'||d==="'"||d==="`")m=d;else if(d==="(")f++;else if(d===")"&&(f--,f===0)){let p=a+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){c=p;break}}}if(c!==-1)n+="[tool:functions."+r[1]+"()]",s=c+1,t.lastIndex=s;else{n+="[tool:functions."+r[1]+"(",s=e.length;break}}return s<e.length&&(n+=o?e.substring(s).replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\]|$)/gi,""):e.substring(s)),n},Iu=(e,o,t)=>{let n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s="",r=0,l;for(;(l=n.exec(e))!==null;){let u=e.substring(r,l.index);s+=u.replace(o,t);let f=l.index+l[0].length-1,m=0,c=null,a=-1;for(let d=f;d<e.length;d++){let p=e[d];if(c){if(p===c){let h=0;for(let E=d-1;E>=0&&e[E]==="\\";E--)h++;h%2===0&&(c=null)}}else if(p==='"'||p==="'"||p==="`")c=p;else if(p==="(")m++;else if(p===")"&&(m--,m===0)){let h=d+1;for(;h<e.length&&/\s/.test(e[h]);)h++;if(h<e.length&&e[h]==="]"){a=h;break}}}if(a!==-1)s+=e.substring(l.index,a+1),r=a+1,n.lastIndex=r;else{s+=e.substring(l.index),r=e.length;break}}return r<e.length&&(s+=e.substring(r).replace(o,t)),s},$l=e=>Nl(e,!0),ji=e=>{if(!e)return[];let o=e.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),t=[],n=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,s;for(;(s=n.exec(o))!==null;){let r=s[1],l=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=l;a<o.length;a++){let d=o[a];if(f){if(d===f){let p=0;for(let h=a-1;h>=0&&o[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let p=a+1;for(;p<o.length&&/\s/.test(o[p]);)p++;if(p<o.length&&o[p]==="]"){m=p;break}}}if(m!==-1){let a=o.substring(l+1,c),d=o.substring(s.index,m+1);t.push({fullMatch:d,toolName:r.trim(),args:a.trim()}),n.lastIndex=m+1}}return t},Br=(e,o={})=>e?(Ni=o,cr=new Su({apiKey:e}),cr):null,Bi=async(e,o,t,n,s="Fast")=>{let{aiProvider:r="Google",apiKey:l,mode:u}=e,f="",m=null,c;r==="OpenRouter"?c=Yi(l,o,t,n,s,u,!1):r==="DeepSeek"?c=Ri(l,o,t,n,s,u,!1):r==="NVIDIA"?c=Wi(l,o,t,n,s,u,!1):c=await cr.models.generateContentStream({model:o,contents:t,config:{systemInstruction:n,maxOutputTokens:2048,temperature:.3,thinkingConfig:{includeThoughts:!1,thinkingLevel:No.MINIMAL}}});for await(let a of c){if(a.candidates?.[0]?.content?.parts)for(let d of a.candidates[0].content.parts)d.text&&!d.thought&&(f+=d.text);a.usageMetadata&&(m=a.usageMetadata)}return{text:f,usageMetadata:m}},Au=async(e,o)=>{try{let{aiProvider:t="Google"}=o,n=Te(To,{});if(Object.values(n).flat().length<=2)return;let r=Object.keys(n).filter(d=>d!==e&&Array.isArray(n[d])&&n[d].length>2);if(r.length===0)return;let l=`You are a silent background process for the FluxFlow CLI Agent.
397
397
  Your task is to summarize or merge temporary context memories from one or more past conversation sessions.
398
398
  For each Chat ID provided, you must output a tool call to save the consolidated summary.
399
399
 
@@ -408,158 +408,158 @@ Guidelines:
408
408
 
409
409
  Chats to process:
410
410
 
411
- `,u=xe(Go,{});for(let d of r){let h=n[d].map(T=>`- ${T}`).join(`
412
- `),S=u[d];l+=`[Chat ID: ${d}]
413
- `,S?(l+=`- Existing Summary: "${S}"
411
+ `,u=Te(Yo,{});for(let d of r){let h=n[d].map(w=>`- ${w}`).join(`
412
+ `),E=u[d];l+=`[Chat ID: ${d}]
413
+ `,E?(l+=`- Existing Summary: "${E}"
414
414
  `,l+=`-- New Memories to integrate:
415
415
  ${h}
416
416
 
417
417
  `):l+=`-- Individual Memories:
418
418
  ${h}
419
419
 
420
- `}let f=0,m=5,c=!1,a="gemma-4-26b-a4b-it";for(t==="OpenRouter"&&(a="google/gemma-4-26b-a4b-it:free"),t==="DeepSeek"&&(a="deepseek-v4-flash");f<=m&&!c;){f++;try{let d=await Ui(o,a,l,null,"Fast"),p=d.text||"",h=Yi(p);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let S of h){let T=S.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(T)&&await ys(T,S.args,{chatId:e})}d.usageMetadata&&await Co("tokens",d.usageMetadata.totalTokenCount||0),c=!0}catch(d){if(f>=m)throw new Error(`Failed after ${m} attempts. Last error: ${d.message}`)}}}catch(t){let n=Ee.join(Io,"janitor");dt.existsSync(n)||dt.mkdirSync(n,{recursive:!0}),dt.appendFileSync(Ee.join(n,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${t.message}
421
- `)}},Nl=async function*(e,o,t,n,s){let{profile:r,thinkingLevel:l,mode:u,janitorModel:f,chatId:m,systemSettings:c,sessionStats:a,aiProvider:d="Google",apiTier:p}=t,h=Ni(e);if(!mr&&d==="Google")throw new Error("AI not initialized");let S=c?.memory!==!1,T=o[o.length-1].text,w=Ee.join(ro,"chat-summaries.json"),I=!1,L=o.filter(b=>b.role==="user").length===1,_=T.includes("[TITLE-UPDATE]"),R=L||_,v=T.replace(/\[TITLE-UPDATE\]/g,"").trim();v=v.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),await kt.startTransaction(m,v);try{let b=[...o.slice(0,-1)],A=252e3,F=254e3;if((d==="DeepSeek"||d==="Google"&&p==="Paid")&&(A=396e3,F=4e5),c?.compression===0&&(a?.tokens||0)>A){yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."};let te=St=>St.filter(gt=>(gt.role==="user"||gt.role==="agent"||gt.role==="system")&&!String(gt.id).startsWith("welcome")&&!gt.isMeta).map(gt=>`[${gt.text?.startsWith("[TOOL RESULT]")?"TOOL":gt.role==="agent"?"AGENT":"USER"}]: ${gt.text}`).join(`
420
+ `}let f=0,m=5,c=!1,a="gemma-4-26b-a4b-it";for(t==="OpenRouter"&&(a="google/gemma-4-26b-a4b-it:free"),t==="DeepSeek"&&(a="deepseek-v4-flash");f<=m&&!c;){f++;try{let d=await Bi(o,a,l,null,"Fast"),p=d.text||"",h=ji(p);if(h.length===0)throw new Error("No tool calls detected in synthesis response");for(let E of h){let w=E.toolName;["saveSummary","saveSumary","SaveSummary","SaveSumary"].includes(w)&&await gs(w,E.args,{chatId:e})}d.usageMetadata&&await Eo("tokens",d.usageMetadata.totalTokenCount||0),c=!0}catch(d){if(f>=m)throw new Error(`Failed after ${m} attempts. Last error: ${d.message}`)}}}catch(t){let n=ke.join(ko,"janitor");mt.existsSync(n)||mt.mkdirSync(n,{recursive:!0}),mt.appendFileSync(ke.join(n,"error.log"),`[${new Date().toLocaleString()}] Past memory batch consolidation error: ${t.message}
421
+ `)}},Bl=async function*(e,o,t,n,s){let{profile:r,thinkingLevel:l,mode:u,janitorModel:f,chatId:m,systemSettings:c,sessionStats:a,aiProvider:d="Google",apiTier:p}=t,h=_i(e);if(!cr&&d==="Google")throw new Error("AI not initialized");let E=c?.memory!==!1,w=o[o.length-1].text,T=ke.join(ro,"chat-summaries.json"),I=!1,O=o.filter(S=>S.role==="user").length===1,P=w.includes("[TITLE-UPDATE]"),U=O||P,A=w.replace(/\[TITLE-UPDATE\]/g,"").trim();A=A.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),await kt.startTransaction(m,A);try{let S=[...o.slice(0,-1)],v=252e3,F=254e3;if((d==="DeepSeek"||d==="NVIDIA"||d==="Google"&&p==="Paid")&&(v=396e3,F=4e5),c?.compression===0&&(a?.tokens||0)>v){yield{type:"status_history",content:"Context Limit Reached. Condensing session history..."};let ee=Et=>Et.filter(xt=>(xt.role==="user"||xt.role==="agent"||xt.role==="system")&&!String(xt.id).startsWith("welcome")&&!xt.isMeta).map(xt=>`[${xt.text?.startsWith("[TOOL RESULT]")?"TOOL":xt.role==="agent"?"AGENT":"USER"}]: ${xt.text}`).join(`
422
422
 
423
- `),ve=async(St,gt)=>{let Ne="You are an expert context condenser. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details. Under no circumstances exceed MAX 2000 words.",ae=gt?`Here is the previous summary:
424
- ${gt}
423
+ `),ve=async(Et,xt)=>{let Ue="You are an expert context condenser. Summarize the provided chat history (which may include previous summaries, user instructions, agent outputs, and tool results) into a detailed, coherent, and highly technical summary of 1000 to 1500 words. Focus on preserving the architectural decisions made, current system state, task progress, and critical code details. Under no circumstances exceed MAX 2000 words.",ae=xt?`Here is the previous summary:
424
+ ${xt}
425
425
 
426
426
  Here is the new conversation history:
427
- ${St}
427
+ ${Et}
428
428
 
429
429
  Provide a new consolidated summary of the entire session.`:`Here is the conversation history:
430
- ${St}
431
-
432
- Provide a consolidated summary of the entire session.`,jt="gemma-4-26b-a4b-it";d==="OpenRouter"&&(jt="google/gemma-4-26b-a4b-it:free"),d==="DeepSeek"&&(jt="deepseek-v4-flash");let at=0,go=!1,xt=null;for(;at<=3&&!go;){at++;try{xt=await Ui(t,jt,ae,Ne,"Fast"),go=!0}catch{if(at>3){if(d==="Google")try{return(await Ui(t,"gemini-3.1-flash-lite",ae,Ne,"Fast")).text||""}catch{return""}return""}}}return xt&&xt.text||""},st=te(b),de=xe(w,{}),he=de[m]||{summary:"",historyLength:0};typeof he=="string"&&(he={summary:he,historyLength:0});let fe=b.filter(St=>(St.role==="user"||St.role==="agent"||St.role==="system")&&!String(St.id).startsWith("welcome")&&!St.isMeta).length;he.historyLength&&fe<he.historyLength&&(he.summary="",he.historyLength=0,de[m]=he,ke(w,de));let it=he.summary||"",Bo=await ve(st,it);Bo&&(he.summary=Bo,de[m]=he,ke(w,de),b=[],I=!0)}L&&S&&(yield{type:"status",content:"Condensing past chat memories..."},await ku(m,t));let Q=xe(Eo,{}),j=xe(Go,{}),Z=Object.entries(Q).filter(([te])=>te!==m).flatMap(([te,ve])=>ve),z=[...Object.entries(j).filter(([te])=>te!==m).slice(-20).map(([te,ve])=>`[Chat Summary]: ${ve}`),...Z].map(te=>`- ${te}`).join(`
433
- `),ce=xe(Nt,[]).map(te=>`- ${te.memory}`).join(`
434
- `),Le=(a?.tokens||0)>=24e3,Je=Fa(z,ce,S,Le),ue=new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!0}),tt=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache"],Ye=te=>{try{return dt.readdirSync(te,{withFileTypes:!0})}catch{return[]}},_e=(te,ve={value:0},st=1)=>{if(ve.value>6200||st>7)return ve.value;let de=Ye(te);for(let he of de){if(ve.value>6200)break;tt.includes(he.name)||he.isDirectory()&&(ve.value++,_e(Ee.join(te,he.name),ve,st+1))}return ve.value},Me=(te,ve,st="",de=1)=>{let he=Ye(te),fe=Ee.sep;if(he.length>100)return`${st}\u2514\u2500\u2500 ${Ee.basename(te)}${fe} ...100+ files...
435
- `;let it="",Bo=tt,St=he.filter(ae=>!Bo.includes(ae.name)),gt=he.filter(ae=>Bo.includes(ae.name)).map(ae=>ae.name).sort();St.sort((ae,jt)=>ae.isDirectory()&&!jt.isDirectory()?-1:!ae.isDirectory()&&jt.isDirectory()?1:ae.name.localeCompare(jt.name));let Ne=[...St.map(ae=>({name:ae.name,isDir:ae.isDirectory()})),...gt.map(ae=>({name:ae,isDir:!0,isCollapsed:!0}))];return Ne.forEach((ae,jt)=>{let at=jt===Ne.length-1,go=Ee.join(te,ae.name),xt=at?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",pn=st+(at?" ":"\u2502 ");if(ae.isCollapsed){it+=`${st}${xt}${ae.name}${fe}...
436
- `;return}ae.isDir?de>ve?it+=`${st}${xt}${ae.name}${fe} ...depth exceeded...
437
- `:Ye(go).length>80?it+=`${st}${xt}${ae.name}${fe} ...80+ files...
438
- `:(it+=`${st}${xt}${ae.name}${fe}
439
- `,it+=Me(go,ve,pn,de+1)):it+=`${st}${xt}${ae.name}
440
- `}),it};yield{type:"status",content:"Gathering Context..."},await new Promise(te=>setTimeout(te,500));let je=_e(process.cwd()),ye=12;je>4096?ye=1:je>3072?ye=2:je>2048?ye=3:je>1024?ye=4:je>512?ye=6:je>256?ye=7:je>128?ye=8:je>64?ye=9:je>32&&(ye=10);let ft=xe(Vr,{}),pt=ft[m],lo=pt?pt!==process.cwd():!1;ft[m]=process.cwd(),ke(Vr,ft);let Wt=xe(w,{}),be=Wt[m]||{summary:"",historyLength:0};typeof be=="string"&&(be={summary:be,historyLength:0});let rt=o.filter(te=>(te.role==="user"||te.role==="agent"||te.role==="system")&&!String(te.id).startsWith("welcome")&&!te.isMeta).length;be.historyLength&&rt<be.historyLength&&(be.summary="",be.historyLength=0,Wt[m]=be,ke(w,Wt));let Ao=typeof be=="object"?be.summary||"":be||"",co=Ao?`
430
+ ${Et}
431
+
432
+ Provide a consolidated summary of the entire session.`,Bt="gemma-4-26b-a4b-it";d==="OpenRouter"&&(Bt="google/gemma-4-26b-a4b-it:free"),d==="DeepSeek"&&(Bt="deepseek-v4-flash"),d==="NVIDIA"&&(Bt="nvidia/llama-3.1-405b-instruct");let st=0,go=!1,yt=null;for(;st<=3&&!go;){st++;try{yt=await Bi(t,Bt,ae,Ue,"Fast"),go=!0}catch{if(st>3){if(d==="Google")try{return(await Bi(t,"gemini-3.1-flash-lite",ae,Ue,"Fast")).text||""}catch{return""}return""}}}return yt&&yt.text||""},nt=ee(S),fe=Te(T,{}),ge=fe[m]||{summary:"",historyLength:0};typeof ge=="string"&&(ge={summary:ge,historyLength:0});let he=S.filter(Et=>(Et.role==="user"||Et.role==="agent"||Et.role==="system")&&!String(Et.id).startsWith("welcome")&&!Et.isMeta).length;ge.historyLength&&he<ge.historyLength&&(ge.summary="",ge.historyLength=0,fe[m]=ge,De(T,fe));let rt=ge.summary||"",Bo=await ve(nt,rt);Bo&&(ge.summary=Bo,fe[m]=ge,De(T,fe),S=[],I=!0)}O&&E&&(yield{type:"status",content:"Condensing past chat memories..."},await Au(m,t));let V=Te(To,{}),Y=Te(Yo,{}),Z=Object.entries(V).filter(([ee])=>ee!==m).flatMap(([ee,ve])=>ve),J=[...Object.entries(Y).filter(([ee])=>ee!==m).slice(-20).map(([ee,ve])=>`[Chat Summary]: ${ve}`),...Z].map(ee=>`- ${ee}`).join(`
433
+ `),de=Te(Wt,[]).map(ee=>`- ${ee.memory}`).join(`
434
+ `),$e=(a?.tokens||0)>=24e3,qe=Pa(J,de,E,$e),me=new Date().toLocaleString([],{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!0}),Ze=[".git","node_modules",".gemini","dist","build",".next","out",".cache","bin","obj","vendor","venv",".idea",".gradle",".terraform","target","coverage",".vscode",".svn",".hg",".fslckout",".github",".gitlab",".circleci",".gitea",".gitee",".lerna",".changeset",".nx",".npm",".yarn",".pnpm-store",".expo",".nuxt",".svelte-kit",".docusaurus",".turbo",".vercel","bower_components",".netlify",".vuepress",".quasar",".output",".angular","jspm_packages",".parcel-cache",".rollup.cache",".rspack",".vitepress","__pycache__",".pytest_cache",".mypy_cache",".tox",".poetry","env","vhdl",".ipynb_checkpoints",".jupyter",".conda",".pdm-build",".bundle",".yardoc",".metadata","App_Data","ClientBin",".cargo",".rustc_info",".go","Godeps","_vendor",".rake_tasks","CMakefiles",".wakatime",".dart_tool",".fvm",".cocoapods","Pods",".pub-cache",".symlinks","DerivedData",".xcworkspace",".serverless",".aws",".gcloud",".azure",".kube",".vagrant",".docker","postgres-data","redis-data","mongo-data",".Spotlight-V100",".Trashes","$RECYCLE.BIN","System Volume Information",".DocumentRevisions-V100",".fseventsd","AppData","Application Data","Local","LocalLow","Roaming","$WinREAgent","$WINDOWS.~BT","$WINDOWS.~WS","scw","System32","SysWOW64",".AppleDouble",".AppleDB",".AppleDesktop","_CodeSignature",".cmio",".LSOverride",".localized",".TemporaryItems",".Trash",".Trash-0",".Trash-1000",".gvfs",".local",".config",".dbus",".fontconfig",".snap",".var",".lost+found","lost+found",".thumb",".thumbnails","EFI","boot","grub","logs","log",".nyc_output",".sonar",".ruff_cache"],je=ee=>{try{return mt.readdirSync(ee,{withFileTypes:!0})}catch{return[]}},Be=(ee,ve={value:0},nt=1)=>{if(ve.value>6200||nt>7)return ve.value;let fe=je(ee);for(let ge of fe){if(ve.value>6200)break;Ze.includes(ge.name)||ge.isDirectory()&&(ve.value++,Be(ke.join(ee,ge.name),ve,nt+1))}return ve.value},Le=(ee,ve,nt="",fe=1)=>{let ge=je(ee),he=ke.sep;if(ge.length>100)return`${nt}\u2514\u2500\u2500 ${ke.basename(ee)}${he} ...100+ files...
435
+ `;let rt="",Bo=Ze,Et=ge.filter(ae=>!Bo.includes(ae.name)),xt=ge.filter(ae=>Bo.includes(ae.name)).map(ae=>ae.name).sort();Et.sort((ae,Bt)=>ae.isDirectory()&&!Bt.isDirectory()?-1:!ae.isDirectory()&&Bt.isDirectory()?1:ae.name.localeCompare(Bt.name));let Ue=[...Et.map(ae=>({name:ae.name,isDir:ae.isDirectory()})),...xt.map(ae=>({name:ae,isDir:!0,isCollapsed:!0}))];return Ue.forEach((ae,Bt)=>{let st=Bt===Ue.length-1,go=ke.join(ee,ae.name),yt=st?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",pn=nt+(st?" ":"\u2502 ");if(ae.isCollapsed){rt+=`${nt}${yt}${ae.name}${he}...
436
+ `;return}ae.isDir?fe>ve?rt+=`${nt}${yt}${ae.name}${he} ...depth exceeded...
437
+ `:je(go).length>80?rt+=`${nt}${yt}${ae.name}${he} ...80+ files...
438
+ `:(rt+=`${nt}${yt}${ae.name}${he}
439
+ `,rt+=Le(go,ve,pn,fe+1)):rt+=`${nt}${yt}${ae.name}
440
+ `}),rt};yield{type:"status",content:"Gathering Context..."},await new Promise(ee=>setTimeout(ee,500));let Ge=Be(process.cwd()),Se=12;Ge>4096?Se=1:Ge>3072?Se=2:Ge>2048?Se=3:Ge>1024?Se=4:Ge>512?Se=6:Ge>256?Se=7:Ge>128?Se=8:Ge>64?Se=9:Ge>32&&(Se=10);let pt=Te(Kr,{}),ht=pt[m],lo=ht?ht!==process.cwd():!1;pt[m]=process.cwd(),De(Kr,pt);let Nt=Te(T,{}),be=Nt[m]||{summary:"",historyLength:0};typeof be=="string"&&(be={summary:be,historyLength:0});let ze=o.filter(ee=>(ee.role==="user"||ee.role==="agent"||ee.role==="system")&&!String(ee.id).startsWith("welcome")&&!ee.isMeta).length;be.historyLength&&ze<be.historyLength&&(be.summary="",be.historyLength=0,Nt[m]=be,De(T,Nt));let Mo=typeof be=="object"?be.summary||"":be||"",co=Mo?`
441
441
  **CONTEXT SUMMARY OF PREVIOUS TURNS (PRIORITY: HIGH)**
442
- ${Ao}`:"",Vt=process.cwd()+`
443
- `+Me(process.cwd(),ye),H=await Nr(),Ge="";if(Vo())if(Ge=`[IDE CONTEXT]
444
- `,H.file_focused!=="none"){let te=Ee.relative(process.cwd(),H.file_focused),ve=(H.opened_editors||[]).map(de=>{let he=Ee.relative(process.cwd(),de);return he.startsWith("..")?`[External] ${Ee.basename(de)}`:he});if(Ge+=`Focused File: ${te}
445
- Cursor Line: ${H.cursor_line}
446
- `,H.selected&&(Ge+=`Current Selection: "${H.selected}"
447
- `),H.manual_edits){let de=H.manual_edits,he=4*512,fe=50,it=de.split(`
448
- `);it.length>fe&&(de=it.slice(0,fe).join(`
442
+ ${Mo}`:"",Qt=process.cwd()+`
443
+ `+Le(process.cwd(),Se),X=await Nr(),He="";if(Ko())if(He=`[IDE CONTEXT]
444
+ `,X.file_focused!=="none"){let ee=ke.relative(process.cwd(),X.file_focused),ve=(X.opened_editors||[]).map(fe=>{let ge=ke.relative(process.cwd(),fe);return ge.startsWith("..")?`[External] ${ke.basename(fe)}`:ge});if(He+=`Focused File: ${ee}
445
+ Cursor Line: ${X.cursor_line}
446
+ `,X.selected&&(He+=`Current Selection: "${X.selected}"
447
+ `),X.manual_edits){let fe=X.manual_edits,ge=4*512,he=50,rt=fe.split(`
448
+ `);rt.length>he&&(fe=rt.slice(0,he).join(`
449
449
  `)+`
450
- ... (${it.length-fe} more lines truncated)`),de.length>he&&(de=de.substring(0,he)+`
451
- ... (Character limit reached, truncated)`),Ge+=`Recent Manual Edits:
452
- ${de}
453
- `}ve.length>0&&(Ge+=`All Opened Editors: ${ve.join(", ")}`),H.diagnostics&&(Ge+=`
450
+ ... (${rt.length-he} more lines truncated)`),fe.length>ge&&(fe=fe.substring(0,ge)+`
451
+ ... (Character limit reached, truncated)`),He+=`Recent Manual Edits:
452
+ ${fe}
453
+ `}ve.length>0&&(He+=`All Opened Editors: ${ve.join(", ")}`),X.diagnostics&&(He+=`
454
454
  **ACTIVE FILE ERRORS**:
455
- ${H.diagnostics}
456
- `),(v.toLowerCase().includes("lint")||v.toLowerCase().includes("warning"))&&H.warnings&&(Ge+=`
455
+ ${X.diagnostics}
456
+ `),(A.toLowerCase().includes("lint")||A.toLowerCase().includes("warning"))&&X.warnings&&(He+=`
457
457
  **LINT WARNINGS**:
458
- ${H.warnings}
459
- `)}else Ge+="No file currently focused.";let Rr=`[SYSTEM METADATA (PRIORITY: DYNAMIC), Chat Context >> Metadata] Time: ${ue}
460
- CWD: ${process.cwd()}${lo?` (WARNING: CWD Mismatch! Previous Path: ${pt})`:""}
458
+ ${X.warnings}
459
+ `)}else He+="No file currently focused.";let Rr=`[SYSTEM METADATA (PRIORITY: DYNAMIC), Chat Context >> Metadata] Time: ${me}
460
+ CWD: ${process.cwd()}${lo?` (WARNING: CWD Mismatch! Previous Path: ${ht})`:""}
461
461
  **DIRECTORY STRUCTURE**
462
- ${Vt}${co}${Je}${Ge}
462
+ ${Qt}${co}${qe}${He}
463
463
  ${l!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
464
- `:""}`:""}[USER] ${v.replace(/\s*\[Prompted on:.*?\]/g,"").trim()}`.trim();b.push({role:"user",text:Rr});let zt=null,qn=u==="Flux"?70:7,ht=16;yield{type:"status",content:"Connecting..."},dr=!1;let Oo=[],Yt=!1;b.forEach(te=>{te.text&&te.role==="agent"&&(te.text=te.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,"").trim())});for(let te=0;te<=qn;te++){if(Yt=!1,c?.compression===0&&(a?.tokens||0)>F&&(b=Wa(b,6)),te>0&&(yield{type:"status",content:"Processed. Reconnecting..."}),dr){yield{type:"status",content:"Termination Signal Received."},await new Promise(se=>setTimeout(se,1500));break}if(n){let se=await n();se&&(b.length>0&&b[b.length-1].role==="user"?b[b.length-1].text+=`
465
-
466
- [STEERING HINT]: ${se}`:b.push({role:"user",text:`${l!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
467
- `:""}`:""}[STEERING HINT]: ${se}`}),yield{type:"status",content:"Steering Hint Injected."})}let ve,st=!1,de=1,he=1,fe="",it=null,Bo=null,St=null,gt=0,Ne=[],ae=0,jt=!1,at=!1,go=!1,xt=!1,pn=!0,ot="",lt="",Gt=!1,Jt=e,en="";for(;de<=ht&&he<=ht&&!st&&!dr;){let se=!1;try{fe="",pn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},yield{type:"spinner",content:!0},pn=!1,he===1&&(ot=""));let Be=b.filter(Se=>(Se.role==="user"||Se.role==="agent"||Se.role==="system")&&!String(Se.id).startsWith("welcome")&&!Se.isMeta&&!Se.isTerminalRecord&&!(Se.text&&Se.text.startsWith("[TERMINAL_RECORD]"))).map((Se,Qe,yo)=>{let Re=Se.text||"";Se.role==="agent"&&(Re=Re.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim());let Ft=[{text:Re}];return Se.binaryPart&&Ni(Jt)&&yo.slice(Qe+1).filter(hn=>hn.role==="user"&&!hn.text?.startsWith("[TOOL RESULT]")).length<=2&&Ft.push(Se.binaryPart),{role:Se.role==="user"||Se.role==="system"?"user":"model",parts:Ft}});if(!await ai("agent",t))throw new Error("Error: Quota Exausted for Agent");Jt=e,d==="DeepSeek"&&l==="Fast"&&(Jt="deepseek-chat"),de===ht-1?(Jt=d==="DeepSeek"?"deepseek-v4-flash":"gemini-3-flash-preview",yield{type:"model_update",content:"Trying with fallback model"}):de===ht?(Jt=d==="DeepSeek"?"deepseek-v4-pro":"gemini-3.5-flash",yield{type:"model_update",content:"Trying with fallback model"}):de>12&&de<ht-2&&t.apiKey!=="custom"?(Jt="gemma-4-31b-it",yield{type:"model_update",content:"Trying with fallback Gemma Model"}):de>0&&(yield{type:"model_update",content:null}),en=$a(r,(Jt||"gemma").toLowerCase().startsWith("gemma")?l:"GEM",u,c,S,L,d,h);let Ue=e&&e.toLowerCase().startsWith("gemma"),ct=Be[Be.length-1];if(Ue){let Se=`
468
- [SYSTEM] Tool result received. Analyze output and proceed with your turn${l!="Fast"&&d==="Google"?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>}**":""}`;ct&&ct.role==="user"&&ct.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(ct.parts[0].text+=Se)}if(Ue){let Se=Math.floor(qn*(u==="Flux"?.98:.7)),Qe=te+1;Qe>=Se&&ct&&ct.parts?.[0]&&(ct.parts[0].text+=`
469
- [SYSTEM] WARNING, Turn Limit Impending: Step ${Qe}/${qn}. Wrap up quickly/prompt user to continue & use [[END]] or [turn:finish] quickly.`)}let Et=Be;d==="OpenRouter"?ve=Wi(t.apiKey,Jt,Et,en,l,u,h):d==="DeepSeek"?ve=Ri(t.apiKey,Jt,Et,en,l,u,h):ve=await mr.models.generateContentStream({model:Jt||"gemma-4-31b-it",contents:Et,config:{systemInstruction:en,temperature:u==="Flux"?1:1.4,maxOutputTokens:32768,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:Dn.HARM_CATEGORY_HARASSMENT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_HATE_SPEECH,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:On.BLOCK_NONE},{category:Dn.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:On.BLOCK_NONE}],thinkingConfig:(()=>{let Se=(Jt||"").toLowerCase(),Qe=Se.includes("gemma-4")||Se.startsWith("gemma"),yo=Se.includes("gemini-3");if(Qe||yo)return Qe?{includeThoughts:!1,thinkingLevel:No.MINIMAL}:{includeThoughts:!0,thinkingLevel:{Fast:Se.includes("pro")?No.LOW:No.MINIMAL,Low:No.LOW,Medium:No.MEDIUM,Standard:No.MEDIUM,High:No.HIGH,xHigh:No.HIGH}[l]||No.MEDIUM};{let Re={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[l]||2048;return Re===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:Re}}})()}}),fe="",it=null,St=null,Ne=[],ae=0,yield{type:"model_update",content:null},yield{type:"status",content:"Working..."},lt="",Gt=ot.length>0;let nt="",Qt=Date.now();for await(let Se of ve){if(dr){yield{type:"status",content:"Termination Signal Received."},await new Promise(Re=>setTimeout(Re,1500));break}let Qe="",yo=Se.candidates?.[0]?.content?.parts;if(yo&&yo.length>0)for(let Re of yo)Re.thought?Re.text&&(se||(Qe+="<think>",se=!0),Qe+=Re.text):Re.text&&(se&&(Qe+="</think>",se=!1),Qe+=Re.text);else{let Re=Se.text||"";Re&&se&&(Qe+="</think>",se=!1),Qe+=Re}if(Qe){if(Gt){if(lt+=Qe,lt.length>=30){let J=0,He=Math.min(ot.length,lt.length);for(let K=He;K>0;K--)if(ot.endsWith(lt.substring(0,K))){J=K;break}let yt=lt.substring(J);if(yt){let qe=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(ot)?yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yt.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");qe&&(fe+=qe,d==="Google"?nt+=qe:yield{type:"text",content:qe})}Gt=!1,lt=""}continue}else fe+=Qe,d==="Google"?nt+=Qe:yield{type:"text",content:Qe};let Re=Ll(fe),Ft=bu(fe);if(Ft.inside){St||(St=Date.now());let J=Ft.toolName,yt={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image"}[J]||J,K=Ft.args||"",qe=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map"].includes(yt)){let Fe=ne(K),Yo=Fe.path||Fe.targetFile||Fe.TargetFile||Fe.directory,on=Fe.keyword;if(on)qe=on.replace(/["']/g,"");else if(Yo)qe=Ee.basename(Yo.replace(/["']/g,"").replace(/\\/g,"/"));else{let Bn=K.match(/(?:path|targetFile|TargetFile|directory|keyword)\s*=\s*\\?["']?([^\\"' \),]+)/);if(Bn){let bt=Bn[1].replace(/["']/g,"");qe=yt==="search_keyword"||yt==="file_map"?bt:Ee.basename(bt.replace(/\\/g,"/"))}}}let eo=`${Dl[yt]||yt}${qe?` (${qe})`:""}`;if((yt!==it||qe!==Bo)&&(it=yt,Bo=qe,yield{type:"status",content:`${eo}...`},process.stdout.isTTY)){let Yo={web_search:"Searching",web_scrape:"Reading",view_file:"Reading",read_folder:"Reading",list_files:"Reading",write_file:"Writing",update_file:"Editing",write_pdf:"Creating",write_docx:"Creating",search_keyword:"Searching",exec_command:"Executing",ask:"User Input",memory:"Updating Memory",generate_image:"Generating"}[yt]||"Working";process.stdout.write(`\x1B]0;${Yo}...\x07`)}}let Uo=_l(fe,!1),yr=(Uo.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),tn=yr.split(/[.!?]\s+/),Yr=new Set(tn),Ro=tn.length>10?(tn.length-Yr.size)/tn.length:0,zn=yr.split(/\s+/).filter(J=>J.length>0).length,Jn=.4,wr=.6,Tr=!1;if((Jt||"").toLowerCase().startsWith("gemma")){let He={low:256,medium:768,high:2048,max:4096,xhigh:4096}[l?.toLowerCase()]||2500;Tr=zn>He}if(Ro>Jn||Tr){yield{type:"status",content:`${Ro>Jn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},at=!0,await new Promise(He=>setTimeout(He,3e3));break}let Qn=Re.trim().split(/[.!?]\s+/),gn=new Set(Qn);if((Qn.length>10?(Qn.length-gn.size)/Qn.length:0)>wr){yield{type:"status",content:"Response Loop Detected. Re-centering..."},at=!1,xt=!0,await new Promise(J=>setTimeout(J,3e3));break}let Wo=Uo.toLowerCase().split(/\s+/).filter(J=>J.length>0),xn=!1;if(Wo.length>5)for(let J=1;J<=15;J++){let He=Math.max(3,Math.ceil(8/J));if(Wo.length<J*He)continue;let yt=!0,qe=Wo.slice(Wo.length-J).join(" ");for(let eo=1;eo<He;eo++)if(Wo.slice(Wo.length-J*(eo+1),Wo.length-J*eo).join(" ")!==qe){yt=!1;break}if(yt){xn=!0;break}}if(!xn){let J=Uo.toLowerCase().replace(/[^a-z0-9]/gi,"");if(J.length>=10)for(let He=1;He<=10;He++){let yt=Math.max(4,Math.ceil(12/He));if(J.length<He*yt)continue;let K=J.substring(J.length-He),qe=!0;for(let eo=1;eo<yt;eo++)if(J.substring(J.length-He*(eo+1),J.length-He*eo)!==K){qe=!1;break}if(qe){xn=!0;break}}}if(xn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},at=!1,go=!0,await new Promise(J=>setTimeout(J,3e3));break}let Zn=fe.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),Gr=Yi(Zn);for(;Gr.length>ae;){let J=Gr[ae],He=Date.now(),K={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image"}[J.toolName]||J.toolName,qe=Dl[K]||J.toolName,eo=Eu(K,J.args);yield{type:"status",content:`${qe}${eo?` (${eo})`:""}...`};let Fe="";if(K==="web_search"){let{query:ie,limit:Ae=10}=ne(J.args);Fe=`\u{1F50D} Searched: ${ie}`}else if(K==="web_scrape")Fe=`\u{1F4D6} Visited: ${ne(J.args).url||"..."}`;else if(K==="view_file"){let{path:ie,StartLine:Ae,EndLine:Xe,start_line:Ve,end_line:wt,startLine:Ce,endLine:wo}=ne(J.args),x=Ae||Ve||Ce,g=Xe||wt||wo,O=parseInt(x)||1,N=parseInt(g)||(x?O+800:800),M="...",$=N;try{let G=Ee.resolve(process.cwd(),ie);if(dt.existsSync(G)){let $e=dt.readFileSync(G,"utf8").split(`
470
- `).length;M=$e,$=Math.min(N,$e)}}catch{}let U=ie.toLowerCase(),E=U.endsWith(".pdf"),D=U.endsWith(".docx")||U.endsWith(".doc")||U.endsWith(".ppt")||U.endsWith(".pptx")||U.endsWith(".xls")||U.endsWith(".xlsx"),P=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(U);E||D?Fe=`\u{1F4C4} Viewed: ${ie}`:P?Fe=`\u{1F4F8} Viewed: ${ie}`:Fe=`\u{1F4C4} Read: ${ie} \u2192 Lines ${O} - ${$} of ${M}`}else if(K==="list_files"||K==="read_folder"){let ie=K==="list_files"?"List":"Viewed",Ae=ne(J.args).path;Fe=`\u{1F4C2} ${ie}: ${Ae==="."?"./":Ae}`}else if(K==="write_file"||K==="update_file")Fe=`\u{1F4BE} ${K==="write_file"?"Created":"Edited"}: ${ne(J.args).path||"..."}`;else if(K==="write_pdf")Fe=`\u{1F4D1} Created: ${ne(J.args).path||"..."}`;else if(K==="write_docx")Fe=`\u{1F4DD} Created: ${ne(J.args).path||"..."}`;else if(K==="file_map")Fe=`\u{1F4CB} Get Map: ${ne(J.args).path||"..."}`;else if(K==="search_keyword")Fe="";else if(K==="generate_image"){let{path:ie,outputPath:Ae,output:Xe}=ne(J.args);Fe=`\u{1F3A8} Generated: ${ie||Ae||Xe||"generated_image.png"}`}else K==="exec_command"||K==="ask"?Fe="":Fe=`Executed: ${J.toolName}`;if(K==="exec_command"){let{command:ie}=ne(J.args);if(ie&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Ae=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],Xe=Ee.resolve(process.cwd()).substring(0,3).toLowerCase();if(Ae.some(wt=>{if(wt.source==="[a-zA-Z]:[\\\\\\/]"){let Ce=ie.match(/[a-zA-Z]:[\\\/]/i);return Ce&&Ce[0].toLowerCase()!==Xe}return wt.test(ie)})){let wt='Access Denied. Terminal is prohibited from accessing system drives (C://) or external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(ie||"Unknown"),yield{type:"exec_start"},await new Promise(Ce=>setTimeout(Ce,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${wt}`),await new Promise(Ce=>setTimeout(Ce,50)),t.onExecEnd&&t.onExecEnd(),Ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${wt}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${wt}`},ae++;continue}}t.onExecStart&&t.onExecStart(ie||"Unknown"),yield{type:"exec_start"}}let Yo=ne(J.args),on=Yo.path||Yo.targetPath||null;if(on){let ie=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Ae=Ee.resolve(on),Xe=Ee.resolve(process.cwd());if(ie&&!Ae.startsWith(Xe)){let Ve="Access Denied. You are not allowed to access files outside the current workspace.";if(K==="write_file"||K==="update_file"){let Ce=`\u{1F4BE} ${K==="write_file"?"Write Canceled":"Edit Canceled"}: ${Yo.path||"..."}`,wo=Math.min(Ce.length+4,115),x=`\u256D${"\u2500".repeat(wo)}\u256E`,g=`\u2502 ${Ce.padEnd(wo-2).substring(0,wo-2)} \u2502`,O=`\u2570${"\u2500".repeat(wo)}\u256F`;yield{type:"visual_feedback",content:`${x}
471
- ${g}
472
- ${O}`}}Ne.push({role:"user",text:`[TOOL RESULT]: ERROR: ${Ve}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${Ve}`},ae++;continue}}if(t.onToolApproval&&(K==="write_file"||K==="update_file"||K==="exec_command")){let Ae=t.systemSettings||{},Xe=Ae.autoExec,Ve=null,wt=!1,Ce=!1,wo=!1;if(K==="exec_command"){let{command:E}=ne(J.args),D=(E||"").trim(),P=($e,ge)=>{if(!ge)return!1;let Oe=ge.split(",").map(Ke=>Ke.trim().toLowerCase()).filter(Boolean),Pe=$e.toLowerCase();return Oe.some(Ke=>Pe.startsWith(Ke))},G=P(D,Ae.alwaysAskCommands),q=P(D,Ae.autoApproveCommands);Ce=P(D,Ae.autoDisallowCommands),G?wt=!0:(q||Ae.autoApproveGit&&/^git\s+commit\b/i.test(D))&&(Ve="allow"),!wt&&!Ve&&(Ae.networkAccess===!1&&/\b(curl|wget|npm|yarn|pnpm|pip|pip3|ssh|docker|git\s+(clone|push|pull|fetch))\b/i.test(D)&&(Ve="deny",wo=!0),!Ve&&Ce&&(Ve="deny")),!wt&&!Ve&&Xe&&(Ve="allow")}else Xe&&(Ve="allow");let x=Ve,g="";Ve==="deny"&&(wo?g="network":Ce?g="settings":g="prohibited");let O=!1,N="",M=[],$=0,U=!1;if(!x){if(K==="write_file"||K==="update_file")try{let P=ne(J.args),{path:G}=P;if(G){let q=Ee.resolve(process.cwd(),G),$e=to=>to?to.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,Pt=>Pt.toUpperCase()):"",ge=$e(q),Oe="",Pe=!1,Ke=await Nr(),yn=$e(Ke?.file_focused);if(Ke&&yn===ge&&Ke.full_content?(Oe=Ke.full_content,Pe=!0):dt.existsSync(q)&&(Oe=dt.readFileSync(q,"utf8"),Pe=!0),N=Oe,await kt.recordFileChange(q,Oe),Pe){let to=Oe;if(K==="write_file")to=P.content||P.newContent||"";else{let{patchPairs:Pt,error:jo}=rs(P);if(jo){let Y=`[TOOL RESULT]: ERROR: ${jo}`;Ne.push({role:"user",text:Y}),await qo("toolFailure"),t.onToolResult&&t.onToolResult("failure",K),yield{type:"tool_result",content:Y,toolName:K},ae++;continue}$=Pt.length;let To=ss(Oe,Pt);to=To.content,M=To.results;let Xr=M.filter(Y=>Y.success),er=M.filter(Y=>!Y.success);if(Xr.length===0){let Y=`[TOOL RESULT]: ERROR: Failed to apply patches to [${Ee.basename(q)}].
473
- ${er.map(we=>` \u2022 ${we.error}`).join(`
474
- `)}`,le=`\u{1F4BE} Edited: ${Ee.basename(q)}`.toUpperCase(),me=Math.min(le.length+4,115),De=`\u256D${"\u2500".repeat(me)}\u256E`,_t=`\u2502 ${le.padEnd(me-2).substring(0,me-2)} \u2502`,pe=`\u2570${"\u2500".repeat(me)}\u256F`;yield{type:"visual_feedback",content:`${De}
475
- ${_t}
476
- ${pe}`},Ne.push({role:"user",text:Y}),await qo("toolFailure"),t.onToolResult&&t.onToolResult("failure",K),yield{type:"tool_result",content:Y,toolName:K},ae++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${Ee.basename(q)}...`},Pi(q,Oe,to),O=!0,await new Promise(Pt=>setTimeout(Pt,50))}else if(K==="write_file"){let to=P.content||P.newContent||"";dt.existsSync(q)||(U=!0,dt.mkdirSync(Ee.dirname(q),{recursive:!0}),dt.writeFileSync(q,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${Ee.basename(q)}...`},Pi(q,"",to),O=!0,await new Promise(Pt=>setTimeout(Pt,50))}}}catch(P){console.error("Simulation/Diff Error:",P)}let E=null;$i(P=>{E=P});let D=t.onToolApproval;if(x=await new Promise(async P=>{let G=setInterval(()=>{E&&(Bi.onIDEApproval&&Bi.onIDEApproval(E),clearInterval(G),P(E))},100);try{let q=await D(K,J.args);clearInterval(G),P(q)}catch{clearInterval(G),P("deny")}}),$i(null),K==="write_file"||K==="update_file"){let{path:P}=ne(J.args);if(P){let G=Ee.resolve(process.cwd(),P);if(Ol(G,x),x==="deny"&&U&&dt.existsSync(G))try{dt.unlinkSync(G)}catch{}}}x==="deny"&&(g="user")}if(x==="allow"&&O&&Vo()){let{path:E}=ne(J.args),D=Ee.resolve(process.cwd(),E),P=await Nr(),G="";P&&P.file_focused===D&&P.full_content?G=P.full_content:dt.existsSync(D)&&(G=dt.readFileSync(D,"utf8"));let q=G.split(/\r?\n/),$e=q.length,ge=Buffer.byteLength(G,"utf8"),Oe="";N&&(Oe=`Old File contents:
477
- ${N.split(/\r?\n/).map((me,De)=>`${De+1} | ${me}`).join(`
464
+ `:""}`:""}[USER] ${A.replace(/\s*\[Prompted on:.*?\]/g,"").trim()}`.trim();S.push({role:"user",text:Rr});let Zt=null,Kn=u==="Flux"?70:7,gt=16;yield{type:"status",content:"Connecting..."},lr=!1;let vo=[],Ht=!1;S.forEach(ee=>{ee.text&&ee.role==="agent"&&(ee.text=ee.text.replace(/(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])/gi,"").trim())});for(let ee=0;ee<=Kn;ee++){if(Ht=!1,c?.compression===0&&(a?.tokens||0)>F&&(S=ja(S,6)),ee>0&&(yield{type:"status",content:"Processed. Reconnecting..."}),lr){yield{type:"status",content:"Termination Signal Received."},await new Promise(se=>setTimeout(se,1500));break}if(n){let se=await n();se&&(S.length>0&&S[S.length-1].role==="user"?S[S.length-1].text+=`
465
+
466
+ [STEERING HINT]: ${se}`:S.push({role:"user",text:`${l!="Fast"&&d==="Google"?`${e.toLowerCase().startsWith("gemma")?`[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITICAL PRIORITY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**
467
+ `:""}`:""}[STEERING HINT]: ${se}`}),yield{type:"status",content:"Steering Hint Injected."})}let ve,nt=!1,fe=1,ge=1,he="",rt=null,Bo=null,Et=null,xt=0,Ue=[],ae=0,Bt=!1,st=!1,go=!1,yt=!1,pn=!0,et="",it="",Xt=!1,Kt=e,Uo="";for(;fe<=gt&&ge<=gt&&!nt&&!lr;){let se=!1;try{he="",pn&&(process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07"),yield{type:"turn_reset",content:!0},yield{type:"spinner",content:!0},pn=!1,ge===1&&(et=""));let Re=S.filter(Ce=>(Ce.role==="user"||Ce.role==="agent"||Ce.role==="system")&&!String(Ce.id).startsWith("welcome")&&!Ce.isMeta&&!Ce.isTerminalRecord&&!(Ce.text&&Ce.text.startsWith("[TERMINAL_RECORD]"))).map((Ce,ot,xo)=>{let Pe=Ce.text||"";Ce.role==="agent"&&(Pe=Pe.replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").trim());let Rt=[{text:Pe}];return Ce.binaryPart&&_i(Kt)&&xo.slice(ot+1).filter(qn=>qn.role==="user"&&!qn.text?.startsWith("[TOOL RESULT]")).length<=2&&Rt.push(Ce.binaryPart),{role:Ce.role==="user"||Ce.role==="system"?"user":"model",parts:Rt}});if(!await ii("agent",t))throw new Error("Error: Quota Exausted for Agent");Kt=e,d==="DeepSeek"&&l==="Fast"&&(Kt="deepseek-chat"),fe===gt-1?(Kt=d==="DeepSeek"?"deepseek-v4-flash":"gemini-3-flash-preview",yield{type:"model_update",content:"Trying with fallback model"}):fe===gt?(Kt=d==="DeepSeek"?"deepseek-v4-pro":"gemini-3.5-flash",yield{type:"model_update",content:"Trying with fallback model"}):fe>12&&fe<gt-2&&t.apiKey!=="custom"?(Kt="gemma-4-31b-it",yield{type:"model_update",content:"Trying with fallback Gemma Model"}):fe>0&&(yield{type:"model_update",content:null}),Uo=_a(r,(Kt||"gemma").toLowerCase().startsWith("gemma")?l:"GEM",u,c,E,O,d,h);let We=e&&e.toLowerCase().startsWith("gemma"),at=Re[Re.length-1];if(We){let Ce=`
468
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn${l!="Fast"&&d==="Google"?". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>}**":""}`;at&&at.role==="user"&&at.parts?.[0]?.text?.startsWith("[TOOL RESULT]")&&(at.parts[0].text+=Ce)}if(We){let Ce=Math.floor(Kn*(u==="Flux"?.98:.7)),ot=ee+1;ot>=Ce&&at&&at.parts?.[0]&&(at.parts[0].text+=`
469
+ [SYSTEM] WARNING, Turn Limit Impending: Step ${ot}/${Kn}. Wrap up quickly/prompt user to continue & use [[END]] or [turn:finish] quickly.`)}let wt=Re;d==="OpenRouter"?ve=Yi(t.apiKey,Kt,wt,Uo,l,u,h):d==="DeepSeek"?ve=Ri(t.apiKey,Kt,wt,Uo,l,u,h):d==="NVIDIA"?ve=Wi(t.apiKey,Kt,wt,Uo,l,u,h):ve=await cr.models.generateContentStream({model:Kt||"gemma-4-31b-it",contents:wt,config:{systemInstruction:Uo,temperature:u==="Flux"?1:1.4,maxOutputTokens:32768,mediaResolution:"MEDIA_RESOLUTION_MEDIUM",safetySettings:[{category:In.HARM_CATEGORY_HARASSMENT,threshold:kn.BLOCK_NONE},{category:In.HARM_CATEGORY_HATE_SPEECH,threshold:kn.BLOCK_NONE},{category:In.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:kn.BLOCK_NONE},{category:In.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:kn.BLOCK_NONE}],thinkingConfig:(()=>{let Ce=(Kt||"").toLowerCase(),ot=Ce.includes("gemma-4")||Ce.startsWith("gemma"),xo=Ce.includes("gemini-3");if(ot||xo)return ot?{includeThoughts:!1,thinkingLevel:No.MINIMAL}:{includeThoughts:!0,thinkingLevel:{Fast:Ce.includes("pro")?No.LOW:No.MINIMAL,Low:No.LOW,Medium:No.MEDIUM,Standard:No.MEDIUM,High:No.HIGH,xHigh:No.HIGH}[l]||No.MEDIUM};{let Pe={Fast:0,Low:512,Medium:2048,Standard:2048,High:16384,xHigh:24576}[l]||2048;return Pe===0?{includeThoughts:!1}:{includeThoughts:!0,thinkingBudget:Pe}}})()}}),he="",rt=null,Et=null,Ue=[],ae=0,yield{type:"model_update",content:null},it="",Xt=et.length>0;let tt="",eo=Date.now(),Ro=!0;for await(let Ce of ve){if(Ro&&(yield{type:"status",content:"Working..."},Ro=!1),lr){yield{type:"status",content:"Termination Signal Received."},await new Promise(Pe=>setTimeout(Pe,1500));break}let ot="",xo=Ce.candidates?.[0]?.content?.parts;if(xo&&xo.length>0)for(let Pe of xo)Pe.thought?Pe.text&&(se||(ot+="<think>",se=!0),ot+=Pe.text):Pe.text&&(se&&(ot+="</think>",se=!1),ot+=Pe.text);else{let Pe=Ce.text||"";Pe&&se&&(ot+="</think>",se=!1),ot+=Pe}if(ot){if(Xt){if(it+=ot,it.length>=30){let Q=0,lt=Math.min(et.length,it.length);for(let G=lt;G>0;G--)if(et.endsWith(it.substring(0,G))){Q=G;break}let ct=it.substring(Q);if(ct){let bt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(et)?ct.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):ct.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");bt&&(he+=bt,d==="Google"?tt+=bt:yield{type:"text",content:bt})}Xt=!1,it=""}continue}else he+=ot,d==="Google"?tt+=ot:yield{type:"text",content:ot};let Pe=$l(he),Rt=ku(he);if(Rt.inside){Et||(Et=Date.now());let Q=Rt.toolName,ct={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image"}[Q]||Q,G=Rt.args||"",bt=null;if(["write_file","update_file","view_file","read_folder","write_pdf","write_docx","search_keyword","generate_image","file_map"].includes(ct)){let _e=ne(G),bo=_e.path||_e.targetFile||_e.TargetFile||_e.directory,_n=_e.keyword;if(_n)bt=_n.replace(/["']/g,"");else if(bo)bt=ke.basename(bo.replace(/["']/g,"").replace(/\\/g,"/"));else{let Nn=G.match(/(?:path|targetFile|TargetFile|directory|keyword)\s*=\s*\\?["']?([^\\"' \),]+)/);if(Nn){let Fe=Nn[1].replace(/["']/g,"");bt=ct==="search_keyword"||ct==="file_map"?Fe:ke.basename(Fe.replace(/\\/g,"/"))}}}let Ft=`${Fl[ct]||ct}${bt?` (${bt})`:""}`;if((ct!==rt||bt!==Bo)&&(rt=ct,Bo=bt,yield{type:"status",content:`${Ft}...`},process.stdout.isTTY)){let bo={web_search:"Searching",web_scrape:"Reading",view_file:"Reading",read_folder:"Reading",list_files:"Reading",write_file:"Writing",update_file:"Editing",write_pdf:"Creating",write_docx:"Creating",search_keyword:"Searching",exec_command:"Executing",ask:"User Input",memory:"Updating Memory",generate_image:"Generating"}[ct]||"Working";process.stdout.write(`\x1B]0;${bo}...\x07`)}}let Zo=Nl(he,!1),Ln=(Zo.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\]|$)/gi)||[]).join("").trim(),Fn=Ln.split(/[.!?]\s+/),en=new Set(Fn),$n=Fn.length>10?(Fn.length-en.size)/Fn.length:0,gr=Ln.split(/\s+/).filter(Q=>Q.length>0).length,zn=.4,Yr=.6,Pn=!1;if((Kt||"").toLowerCase().startsWith("gemma")){let lt={low:256,medium:768,high:2048,max:4096,xhigh:4096}[l?.toLowerCase()]||2500;Pn=gr>lt}if($n>zn||Pn){yield{type:"status",content:`${$n>zn?"Reasoning Loop Detected":"Thinking Budget Exceeded"}. Re-centering...`},st=!0,await new Promise(lt=>setTimeout(lt,3e3));break}let Do=Pe.trim().split(/[.!?]\s+/),xr=new Set(Do);if((Do.length>10?(Do.length-xr.size)/Do.length:0)>Yr){yield{type:"status",content:"Response Loop Detected. Re-centering..."},st=!1,yt=!0,await new Promise(Q=>setTimeout(Q,3e3));break}let Oo=Zo.toLowerCase().split(/\s+/).filter(Q=>Q.length>0),tn=!1;if(Oo.length>5)for(let Q=1;Q<=15;Q++){let lt=Math.max(3,Math.ceil(8/Q));if(Oo.length<Q*lt)continue;let ct=!0,bt=Oo.slice(Oo.length-Q).join(" ");for(let Ft=1;Ft<lt;Ft++)if(Oo.slice(Oo.length-Q*(Ft+1),Oo.length-Q*Ft).join(" ")!==bt){ct=!1;break}if(ct){tn=!0;break}}if(!tn){let Q=Zo.toLowerCase().replace(/[^a-z0-9]/gi,"");if(Q.length>=10)for(let lt=1;lt<=10;lt++){let ct=Math.max(4,Math.ceil(12/lt));if(Q.length<lt*ct)continue;let G=Q.substring(Q.length-lt),bt=!0;for(let Ft=1;Ft<ct;Ft++)if(Q.substring(Q.length-lt*(Ft+1),Q.length-lt*Ft)!==G){bt=!1;break}if(bt){tn=!0;break}}}if(tn){yield{type:"status",content:"Stuttering Detected. Re-centering..."},st=!1,go=!0,await new Promise(Q=>setTimeout(Q,3e3));break}let Ls=he.replace(/(?:<(think|thought|thoughts)>|\[(think|thought|thoughts)\])[\s\S]*?(?:<\/(think|thought|thoughts)>|\[\/(think|thought|thoughts)\]|$)/gi,""),yr=ji(Ls);for(;yr.length>ae;){let Q=yr[ae],lt=Date.now(),G={Ask:"ask",WebSearch:"web_search",WebScrape:"web_scrape",ReadFile:"view_file",ReadFolder:"read_folder",WriteFile:"write_file",PatchFile:"update_file",WritePDF:"write_pdf",WriteDoc:"write_docx",Run:"exec_command",SearchKeyword:"search_keyword",Memory:"memory",file_map:"file_map",FileMap:"file_map",Chat:"chat",chat:"chat",GenerateImage:"generate_image",generate_image:"generate_image"}[Q.toolName]||Q.toolName,bt=Fl[G]||Q.toolName,Ft=Cu(G,Q.args);yield{type:"status",content:`${bt}${Ft?` (${Ft})`:""}...`};let _e="";if(G==="web_search"){let{query:ie,limit:Ie=10}=ne(Q.args);_e=`\u{1F50D} Searched: ${ie}`}else if(G==="web_scrape")_e=`\u{1F4D6} Visited: ${ne(Q.args).url||"..."}`;else if(G==="view_file"){let{path:ie,StartLine:Ie,EndLine:Je,start_line:Xe,end_line:Ae,startLine:At,endLine:x}=ne(Q.args),g=Ie||Xe||At,D=Je||Ae||x,_=parseInt(g)||1,M=parseInt(D)||(g?_+800:800),$="...",R=M;try{let q=ke.resolve(process.cwd(),ie);if(mt.existsSync(q)){let le=mt.readFileSync(q,"utf8").split(`
470
+ `).length;$=le,R=Math.min(M,le)}}catch{}let C=ie.toLowerCase(),L=C.endsWith(".pdf"),B=C.endsWith(".docx")||C.endsWith(".doc")||C.endsWith(".ppt")||C.endsWith(".pptx")||C.endsWith(".xls")||C.endsWith(".xlsx"),j=/\.(png|jpg|jpeg|webp|gif|bmp)$/.test(C);L||B?_e=`\u{1F4C4} Viewed: ${ie}`:j?_e=`\u{1F4F8} Viewed: ${ie}`:_e=`\u{1F4C4} Read: ${ie} \u2192 Lines ${_} - ${R} of ${$}`}else if(G==="list_files"||G==="read_folder"){let ie=G==="list_files"?"List":"Viewed",Ie=ne(Q.args).path;_e=`\u{1F4C2} ${ie}: ${Ie==="."?"./":Ie}`}else if(G==="write_file"||G==="update_file")_e=`\u{1F4BE} ${G==="write_file"?"Created":"Edited"}: ${ne(Q.args).path||"..."}`;else if(G==="write_pdf")_e=`\u{1F4D1} Created: ${ne(Q.args).path||"..."}`;else if(G==="write_docx")_e=`\u{1F4DD} Created: ${ne(Q.args).path||"..."}`;else if(G==="file_map")_e=`\u{1F4CB} Get Map: ${ne(Q.args).path||"..."}`;else if(G==="search_keyword")_e="";else if(G==="generate_image"){let{path:ie,outputPath:Ie,output:Je}=ne(Q.args);_e=`\u{1F3A8} Generated: ${ie||Ie||Je||"generated_image.png"}`}else G==="exec_command"||G==="ask"?_e="":_e=`Executed: ${Q.toolName}`;if(G==="exec_command"){let{command:ie}=ne(Q.args);if(ie&&t.systemSettings&&t.systemSettings.allowExternalAccess===!1){let Ie=[/[a-zA-Z]:[\\\/]/i,/^\//,/\.\.[\\\/]/,/\/etc\//,/\/var\//,/\/root\//,/\/bin\//,/\/usr\//],Je=ke.resolve(process.cwd()).substring(0,3).toLowerCase();if(Ie.some(Ae=>{if(Ae.source==="[a-zA-Z]:[\\\\\\/]"){let At=ie.match(/[a-zA-Z]:[\\\/]/i);return At&&At[0].toLowerCase()!==Je}return Ae.test(ie)})){let Ae='Access Denied. Terminal is prohibited from accessing system drives (C://) or external directories while "External Workspace Access" is disabled.';t.onExecStart&&t.onExecStart(ie||"Unknown"),yield{type:"exec_start"},await new Promise(At=>setTimeout(At,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${Ae}`),await new Promise(At=>setTimeout(At,50)),t.onExecEnd&&t.onExecEnd(),Ue.push({role:"user",text:`[TOOL RESULT]: ERROR: ${Ae}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${Ae}`},ae++;continue}}t.onExecStart&&t.onExecStart(ie||"Unknown"),yield{type:"exec_start"}}let bo=ne(Q.args),_n=bo.path||bo.targetPath||null;if(_n){let ie=t.systemSettings&&t.systemSettings.allowExternalAccess===!1,Ie=ke.resolve(_n),Je=ke.resolve(process.cwd());if(ie&&!Ie.startsWith(Je)){let Xe="Access Denied. You are not allowed to access files outside the current workspace.";if(G==="write_file"||G==="update_file"){let At=`\u{1F4BE} ${G==="write_file"?"Write Canceled":"Edit Canceled"}: ${bo.path||"..."}`,x=Math.min(At.length+4,115),g=`\u256D${"\u2500".repeat(x)}\u256E`,D=`\u2502 ${At.padEnd(x-2).substring(0,x-2)} \u2502`,_=`\u2570${"\u2500".repeat(x)}\u256F`;yield{type:"visual_feedback",content:`${g}
471
+ ${D}
472
+ ${_}`}}Ue.push({role:"user",text:`[TOOL RESULT]: ERROR: ${Xe}`}),yield{type:"tool_result",content:`[TOOL RESULT]: ERROR: ${Xe}`},ae++;continue}}if(t.onToolApproval&&(G==="write_file"||G==="update_file"||G==="exec_command")){let Ie=t.systemSettings||{},Je=Ie.autoExec,Xe=null,Ae=!1,At=!1,x=!1;if(G==="exec_command"){let{command:L}=ne(Q.args),B=(L||"").trim(),j=(le,Ne)=>{if(!Ne)return!1;let Me=Ne.split(",").map(Mt=>Mt.trim().toLowerCase()).filter(Boolean),Tt=le.toLowerCase();return Me.some(Mt=>Tt.startsWith(Mt))},q=j(B,Ie.alwaysAskCommands),ce=j(B,Ie.autoApproveCommands);At=j(B,Ie.autoDisallowCommands),q?Ae=!0:(ce||Ie.autoApproveGit&&/^git\s+commit\b/i.test(B))&&(Xe="allow"),!Ae&&!Xe&&(Ie.networkAccess===!1&&/\b(curl|wget|npm|yarn|pnpm|pip|pip3|ssh|docker|git\s+(clone|push|pull|fetch))\b/i.test(B)&&(Xe="deny",x=!0),!Xe&&At&&(Xe="deny")),!Ae&&!Xe&&Je&&(Xe="allow")}else Je&&(Xe="allow");let g=Xe,D="";Xe==="deny"&&(x?D="network":At?D="settings":D="prohibited");let _=!1,M="",$=[],R=0,C=!1;if(!g){if(G==="write_file"||G==="update_file")try{let j=ne(Q.args),{path:q}=j;if(q){let ce=ke.resolve(process.cwd(),q),le=to=>to?to.toLowerCase().replace(/\\/g,"/").replace(/^[a-z]:/,vt=>vt.toUpperCase()):"",Ne=le(ce),Me="",Tt=!1,Mt=await Nr(),Jn=le(Mt?.file_focused);if(Mt&&Jn===Ne&&Mt.full_content?(Me=Mt.full_content,Tt=!0):mt.existsSync(ce)&&(Me=mt.readFileSync(ce,"utf8"),Tt=!0),M=Me,await kt.recordFileChange(ce,Me),Tt){let to=Me;if(G==="write_file")to=j.content||j.newContent||"";else{let{patchPairs:vt,error:yo}=os(j);if(yo){let ue=`[TOOL RESULT]: ERROR: ${yo}`;Ue.push({role:"user",text:ue}),await Xo("toolFailure"),t.onToolResult&&t.onToolResult("failure",G),yield{type:"tool_result",content:ue,toolName:G},ae++;continue}R=vt.length;let Tr=ns(Me,vt);to=Tr.content,$=Tr.results;let Sr=$.filter(ue=>ue.success),H=$.filter(ue=>!ue.success);if(Sr.length===0){let ue=`[TOOL RESULT]: ERROR: Failed to apply patches to [${ke.basename(ce)}].
473
+ ${H.map(Ke=>` \u2022 ${Ke.error}`).join(`
474
+ `)}`,pe=`\u{1F4BE} Edited: ${ke.basename(ce)}`.toUpperCase(),ye=Math.min(pe.length+4,115),$t=`\u256D${"\u2500".repeat(ye)}\u256E`,xe=`\u2502 ${pe.padEnd(ye-2).substring(0,ye-2)} \u2502`,we=`\u2570${"\u2500".repeat(ye)}\u256F`;yield{type:"visual_feedback",content:`${$t}
475
+ ${xe}
476
+ ${we}`},Ue.push({role:"user",text:ue}),await Xo("toolFailure"),t.onToolResult&&t.onToolResult("failure",G),yield{type:"tool_result",content:ue,toolName:G},ae++;continue}}yield{type:"status",content:`Opening Diff in IDE: ${ke.basename(ce)}...`},$i(ce,Me,to),_=!0,await new Promise(vt=>setTimeout(vt,50))}else if(G==="write_file"){let to=j.content||j.newContent||"";mt.existsSync(ce)||(C=!0,mt.mkdirSync(ke.dirname(ce),{recursive:!0}),mt.writeFileSync(ce,"","utf8")),yield{type:"status",content:`Opening New File Diff in IDE: ${ke.basename(ce)}...`},$i(ce,"",to),_=!0,await new Promise(vt=>setTimeout(vt,50))}}}catch(j){console.error("Simulation/Diff Error:",j)}let L=null;Fi(j=>{L=j});let B=t.onToolApproval;if(g=await new Promise(async j=>{let q=setInterval(()=>{L&&(Ni.onIDEApproval&&Ni.onIDEApproval(L),clearInterval(q),j(L))},100);try{let ce=await B(G,Q.args);clearInterval(q),j(ce)}catch{clearInterval(q),j("deny")}}),Fi(null),G==="write_file"||G==="update_file"){let{path:j}=ne(Q.args);if(j){let q=ke.resolve(process.cwd(),j);if(Ll(q,g),g==="deny"&&C&&mt.existsSync(q))try{mt.unlinkSync(q)}catch{}}}g==="deny"&&(D="user")}if(g==="allow"&&_&&Ko()){let{path:L}=ne(Q.args),B=ke.resolve(process.cwd(),L),j=await Nr(),q="";j&&j.file_focused===B&&j.full_content?q=j.full_content:mt.existsSync(B)&&(q=mt.readFileSync(B,"utf8"));let ce=q.split(/\r?\n/),le=ce.length,Ne=Buffer.byteLength(q,"utf8"),Me="";M&&(Me=`Old File contents:
477
+ ${M.split(/\r?\n/).map((ye,$t)=>`${$t+1} | ${ye}`).join(`
478
478
  `)}
479
479
 
480
- `);let Pe="";if($e<=200)Pe=q.join(`
481
- `);else{let le=q.slice(0,100).join(`
482
- `),me=q.slice(-100).join(`
483
- `);Pe=`${le}
480
+ `);let Tt="";if(le<=200)Tt=ce.join(`
481
+ `);else{let pe=ce.slice(0,100).join(`
482
+ `),ye=ce.slice(-100).join(`
483
+ `);Tt=`${pe}
484
484
 
485
- ... [${$e-200} lines truncated for history stability] ...
485
+ ... [${le-200} lines truncated for history stability] ...
486
486
 
487
- ${me}`}let Ke="";if(K==="update_file"){let le=is(N,G,M,12);Ke=`SUCCESS: File [${E}] updated via IDE Companion (May have user edits). [${M.length}/${$}] blocks applied.
487
+ ${ye}`}let Mt="";if(G==="update_file"){let pe=rs(M,q,$,12);Mt=`SUCCESS: File [${L}] updated via IDE Companion (May have user edits). [${$.length}/${R}] blocks applied.
488
488
 
489
- ${le}`}else{let le=G.split(/\r?\n/),me=le.length,De=Buffer.byteLength(G,"utf8"),_t="";N&&(_t=`Old File contents:
490
- ${N.split(/\r?\n/).map((Ze,Ct)=>`${Ct+1} | ${Ze}`).join(`
489
+ ${pe}`}else{let pe=q.split(/\r?\n/),ye=pe.length,$t=Buffer.byteLength(q,"utf8"),xe="";M&&(xe=`Old File contents:
490
+ ${M.split(/\r?\n/).map((ut,Ct)=>`${Ct+1} | ${ut}`).join(`
491
491
  `)}
492
492
 
493
- `);let pe="";if(me<=200)pe=le.join(`
494
- `);else{let we=le.slice(0,100).join(`
495
- `),Ze=le.slice(-100).join(`
496
- `);pe=`${we}
493
+ `);let we="";if(ye<=200)we=pe.join(`
494
+ `);else{let Ke=pe.slice(0,100).join(`
495
+ `),ut=pe.slice(-100).join(`
496
+ `);we=`${Ke}
497
497
 
498
- ... [${me-200} lines truncated] ...
498
+ ... [${ye-200} lines truncated] ...
499
499
 
500
- ${Ze}`}Ke=`SUCCESS: File [${E}] saved via IDE Companion (May have user edits).
500
+ ${ut}`}Mt=`SUCCESS: File [${L}] saved via IDE Companion (May have user edits).
501
501
 
502
- - Stats: [${me} lines, ${(De/1024).toFixed(1)} KB]
503
- ${_t}- Content Preview:
504
- ${pe}
502
+ - Stats: [${ye} lines, ${($t/1024).toFixed(1)} KB]
503
+ ${xe}- Content Preview:
504
+ ${we}
505
505
 
506
- Check if Starting and Ending matches your write.`}let to=`\u{1F4BE} ${K==="write_file"?"Written":"Edited"}: ${E||"..."}`,Pt=Math.min(to.length+4,115),jo=`\u256D${"\u2500".repeat(Pt)}\u256E`,To=`\u2502 ${to.padEnd(Pt-2).substring(0,Pt-2)} \u2502`,Xr=`\u2570${"\u2500".repeat(Pt)}\u256F`;yield{type:"visual_feedback",content:`${jo}
507
- ${To}
508
- ${Xr}`};let er=Date.now();gt=er,yield{type:"tool_time",content:er-He};let Y=`[TOOL RESULT]: ${Ke}`;Ne.push({role:"user",text:Y}),jt=!0,await qo("toolSuccess"),t.onToolResult&&t.onToolResult("success",K),yield{type:"tool_result",content:Ke,aiContent:Y,toolName:K},ae++;continue}if(x==="deny"){let E=`Permission Denied: Prohibited ${K==="exec_command"?"Command":"file edit"}.`;if(g==="user"?E="Permission Denied by User":g==="settings"?E="Permission Denied by User Policy":g==="network"?E="Permission Denied: Sandbox Network Access Disabled by User Policy.":g==="prohibited"&&K==="exec_command"&&(E="Permission Denied: Prohibited Command"),K==="write_file"||K==="update_file"){let P=`\u{1F4BE} ${K==="write_file"?"WRITE DENIED":"UPDATE DENIED"}: ${ne(J.args).path||"..."}`.toUpperCase(),G=Math.min(P.length+4,115),q=`\u256D${"\u2500".repeat(G)}\u256E`,$e=`\u2502 ${P.padEnd(G-2).substring(0,G-2)} \u2502`,ge=`\u2570${"\u2500".repeat(G)}\u256F`;yield{type:"visual_feedback",content:`${q}
509
- ${$e}
510
- ${ge}`}}K==="exec_command"&&(await new Promise(D=>setTimeout(D,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${E}`),await new Promise(D=>setTimeout(D,50)),t.onExecEnd&&t.onExecEnd()),Ne.push({role:"user",text:`[TOOL RESULT]: DENIED: ${E}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${E}`},await qo("toolDenied"),t.onToolResult&&t.onToolResult("denied",K),ae++;continue}}if(Fe){let ie=Math.min(Fe.length+4,115),Ae=`\u256D${"\u2500".repeat(ie)}\u256E`,Xe=`\u2502 ${Fe.padEnd(ie-2).substring(0,ie-2)} \u2502`,Ve=`\u2570${"\u2500".repeat(ie)}\u256F`;yield{type:"visual_feedback",content:`${Ae}
511
- ${Xe}
512
- ${Ve}`}}if(gt>0){let ie=Date.now()-gt;ie<1e3&&await new Promise(Ae=>setTimeout(Ae,1e3-ie))}yield{type:"spinner",content:!1};let Bn={chatId:m,history:o,onChunk:ie=>t.onExecChunk?t.onExecChunk(ie):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:u,isMultiModal:Ni(Jt)};if(K==="write_file"||K==="update_file")try{let{path:ie}=ne(J.args);if(ie){let Ae=Ee.resolve(process.cwd(),ie),Xe=await Nr();Xe&&Xe.file_focused===Ae&&Xe.full_content&&(Bn.forcedContent=Xe.full_content)}}catch{}let bt=await ys(K,J.args,Bn);if(yield{type:"spinner",content:!0},K==="write_file"&&bt.startsWith("SUCCESS")){let{path:ie}=ne(J.args);if(ie){let Ae=Ee.resolve(process.cwd(),ie);Al(Ae)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let $t=Date.now();gt=$t,yield{type:"tool_time",content:$t-He},St=$t;let W=null;if(typeof bt=="object"&&bt.binaryPart&&(W=bt.binaryPart,bt=bt.text),K==="search_keyword"){let{keyword:ie,file:Ae}=ne(J.args),Xe=0;if(bt){let g=bt.match(/Found (\d+) matches/i);g&&(Xe=parseInt(g[1]))}let Ve=`\u{1F50E} Searched: "${ie}" in ${Ae?`"${Ae}"`:"./"} \u2192 ${Xe} Match${Xe===1?"":"es"}`,wt=Math.min(Ve.length+4,115),Ce=`\u256D${"\u2500".repeat(wt)}\u256E`,wo=`\u2502 ${Ve.padEnd(wt-2).substring(0,wt-2)} \u2502`,x=`\u2570${"\u2500".repeat(wt)}\u256F`;yield{type:"visual_feedback",content:`${Ce}
513
- ${wo}
514
- ${x}`}}K==="exec_command"&&t.onExecEnd&&(await new Promise(ie=>setTimeout(ie,800)),t.onExecEnd());let Do=bt&&bt.startsWith("DENIED:");bt&&!bt.startsWith("ERROR:")&&!Do?(await qo("toolSuccess"),t.onToolResult&&t.onToolResult("success",K)):Do||(await qo("toolFailure"),t.onToolResult&&t.onToolResult("failure",K));let ee=`[TOOL RESULT]: ${(bt||"").toString().split(/\r?\n/).filter(ie=>!ie.includes("[UI_CONTEXT]")).join(`
515
- `)}`;Ne.push({role:"user",text:ee,binaryPart:W}),jt=!0;let Hr=`[TOOL RESULT]: ${bt||""}`;(K==="view_file"||K==="web_scrape")&&(Hr=`[TOOL RESULT]: ${Fe} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Hr,aiContent:ee,binaryPart:W,toolName:K},K==="memory"&&bt.includes("SUCCESS")&&(yield{type:"memory_updated"}),ae++}d==="Google"&&nt&&Date.now()-Qt>=150&&(yield{type:"text",content:nt},nt="",Qt=Date.now())}Se.usageMetadata&&(zt=Se.usageMetadata),zt&&(yield{type:"liveTokens",content:zt.totalTokenCount})}if(se&&(se=!1,Gt?lt+="</think>":(fe+="</think>",d==="Google"?nt+="</think>":yield{type:"text",content:"</think>"})),Gt&&lt.length>0){let Se=0,Qe=Math.min(ot.length,lt.length);for(let Re=Qe;Re>0;Re--)if(ot.endsWith(lt.substring(0,Re))){Se=Re;break}let yo=lt.substring(Se);if(yo){let Ft=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(ot)?yo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):yo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Ft&&(fe+=Ft,d==="Google"?nt+=Ft:yield{type:"text",content:Ft})}Gt=!1,lt=""}if(d==="Google"&&nt&&(yield{type:"text",content:nt},nt=""),dr)break;let xo=(fe||"").trim(),Zt=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(xo.toLowerCase())||/\[\[END\]\]/i.test(xo.toLowerCase()),Lt=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(xo.toLowerCase()),uo=Ne.length>0||it!==null,ko=xo.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Nn=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(ko),Wr=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(ko.trim()),Ls=/[.!?}"'`’“”]$|```$/s.test(ko)||Wr||Nn;if(!Zt&&!Lt&&!uo&&xo.length>0&&!Ls&&!at&&!go&&!xt)throw new Error("Silent stream cutoff (500): Model stream closed cleanly but cut off mid-sentence without signals.");st=!0,await qo("agent")}catch(Be){if(String(Be).includes("Incomplete JSON segment at the end")){se&&(se=!1,Gt?lt+="</think>":(fe+="</think>",yield{type:"text",content:"</think>"})),st=!0,await qo("agent");break}if(se&&(se=!1,Gt?lt+="</think>":fe+="</think>"),Gt&&lt.length>0){let Zt=0,Lt=Math.min(ot.length,lt.length);for(let ko=Lt;ko>0;ko--)if(ot.endsWith(lt.substring(0,ko))){Zt=ko;break}let uo=lt.substring(Zt);if(uo){let Nn=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(ot)?uo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):uo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Nn&&(fe+=Nn)}Gt=!1,lt=""}let Ue=Be.status||Be.error&&Be.error.message||String(Be),ct=String(Be),Et=new Date().toLocaleString(),nt=Ee.join(Io,"agent");dt.existsSync(nt)||dt.mkdirSync(nt,{recursive:!0}),dt.appendFileSync(Ee.join(nt,"error.log"),`ERROR [${Et}]: ${ct}
506
+ Check if Starting and Ending matches your write.`}let to=`\u{1F4BE} ${G==="write_file"?"Written":"Edited"}: ${L||"..."}`,vt=Math.min(to.length+4,115),yo=`\u256D${"\u2500".repeat(vt)}\u256E`,Tr=`\u2502 ${to.padEnd(vt-2).substring(0,vt-2)} \u2502`,Sr=`\u2570${"\u2500".repeat(vt)}\u256F`;yield{type:"visual_feedback",content:`${yo}
507
+ ${Tr}
508
+ ${Sr}`};let H=Date.now();xt=H,yield{type:"tool_time",content:H-lt};let ue=`[TOOL RESULT]: ${Mt}`;Ue.push({role:"user",text:ue}),Bt=!0,await Xo("toolSuccess"),t.onToolResult&&t.onToolResult("success",G),yield{type:"tool_result",content:Mt,aiContent:ue,toolName:G},ae++;continue}if(g==="deny"){let L=`Permission Denied: Prohibited ${G==="exec_command"?"Command":"file edit"}.`;if(D==="user"?L="Permission Denied by User":D==="settings"?L="Permission Denied by User Policy":D==="network"?L="Permission Denied: Sandbox Network Access Disabled by User Policy.":D==="prohibited"&&G==="exec_command"&&(L="Permission Denied: Prohibited Command"),G==="write_file"||G==="update_file"){let j=`\u{1F4BE} ${G==="write_file"?"WRITE DENIED":"UPDATE DENIED"}: ${ne(Q.args).path||"..."}`.toUpperCase(),q=Math.min(j.length+4,115),ce=`\u256D${"\u2500".repeat(q)}\u256E`,le=`\u2502 ${j.padEnd(q-2).substring(0,q-2)} \u2502`,Ne=`\u2570${"\u2500".repeat(q)}\u256F`;yield{type:"visual_feedback",content:`${ce}
509
+ ${le}
510
+ ${Ne}`}}G==="exec_command"&&(await new Promise(B=>setTimeout(B,50)),t.onExecChunk&&t.onExecChunk(`ERROR: ${L}`),await new Promise(B=>setTimeout(B,50)),t.onExecEnd&&t.onExecEnd()),Ue.push({role:"user",text:`[TOOL RESULT]: DENIED: ${L}`}),yield{type:"tool_result",content:`[TOOL RESULT]: DENIED: ${L}`},await Xo("toolDenied"),t.onToolResult&&t.onToolResult("denied",G),ae++;continue}}if(_e){let ie=Math.min(_e.length+4,115),Ie=`\u256D${"\u2500".repeat(ie)}\u256E`,Je=`\u2502 ${_e.padEnd(ie-2).substring(0,ie-2)} \u2502`,Xe=`\u2570${"\u2500".repeat(ie)}\u256F`;yield{type:"visual_feedback",content:`${Ie}
511
+ ${Je}
512
+ ${Xe}`}}if(xt>0){let ie=Date.now()-xt;ie<1e3&&await new Promise(Ie=>setTimeout(Ie,1e3-ie))}yield{type:"spinner",content:!1};let Nn={chatId:m,history:o,onChunk:ie=>t.onExecChunk?t.onExecChunk(ie):null,onAskUser:t.onAskUser,systemSettings:t.systemSettings,mode:u,isMultiModal:_i(Kt)};if(G==="write_file"||G==="update_file")try{let{path:ie}=ne(Q.args);if(ie){let Ie=ke.resolve(process.cwd(),ie),Je=await Nr();Je&&Je.file_focused===Ie&&Je.full_content&&(Nn.forcedContent=Je.full_content)}}catch{}let Fe=await gs(G,Q.args,Nn);if(yield{type:"spinner",content:!0},G==="write_file"&&Fe.startsWith("SUCCESS")){let{path:ie}=ne(Q.args);if(ie){let Ie=ke.resolve(process.cwd(),ie);Ol(Ie)}}process.stdout.isTTY&&process.stdout.write("\x1B]0;Working...\x07");let W=Date.now();xt=W,yield{type:"tool_time",content:W-lt},Et=W;let Co=null;if(typeof Fe=="object"&&Fe.binaryPart&&(Co=Fe.binaryPart,Fe=Fe.text),G==="search_keyword"){let{keyword:ie,file:Ie}=ne(Q.args),Je=0;if(Fe){let D=Fe.match(/Found (\d+) matches/i);D&&(Je=parseInt(D[1]))}let Xe=`\u{1F50E} Searched: "${ie}" in ${Ie?`"${Ie}"`:"./"} \u2192 ${Je} Match${Je===1?"":"es"}`,Ae=Math.min(Xe.length+4,115),At=`\u256D${"\u2500".repeat(Ae)}\u256E`,x=`\u2502 ${Xe.padEnd(Ae-2).substring(0,Ae-2)} \u2502`,g=`\u2570${"\u2500".repeat(Ae)}\u256F`;yield{type:"visual_feedback",content:`${At}
513
+ ${x}
514
+ ${g}`}}G==="exec_command"&&t.onExecEnd&&(await new Promise(ie=>setTimeout(ie,800)),t.onExecEnd());let wr=Fe&&Fe.startsWith("DENIED:");Fe&&!Fe.startsWith("ERROR:")&&!wr?(await Xo("toolSuccess"),t.onToolResult&&t.onToolResult("success",G)):wr||(await Xo("toolFailure"),t.onToolResult&&t.onToolResult("failure",G));let jr=`[TOOL RESULT]: ${(Fe||"").toString().split(/\r?\n/).filter(ie=>!ie.includes("[UI_CONTEXT]")).join(`
515
+ `)}`;Ue.push({role:"user",text:jr,binaryPart:Co}),Bt=!0;let Gr=`[TOOL RESULT]: ${Fe||""}`;(G==="view_file"||G==="web_scrape")&&(Gr=`[TOOL RESULT]: ${_e} (Context Locked for UI Clarity)`),yield{type:"tool_result",content:Gr,aiContent:jr,binaryPart:Co,toolName:G},G==="memory"&&Fe.includes("SUCCESS")&&(yield{type:"memory_updated"}),ae++}d==="Google"&&tt&&Date.now()-eo>=150&&(yield{type:"text",content:tt},tt="",eo=Date.now())}Ce.usageMetadata&&(Zt=Ce.usageMetadata),Zt&&(yield{type:"liveTokens",content:Zt.totalTokenCount})}if(se&&(se=!1,Xt?it+="</think>":(he+="</think>",d==="Google"?tt+="</think>":yield{type:"text",content:"</think>"})),Xt&&it.length>0){let Ce=0,ot=Math.min(et.length,it.length);for(let Pe=ot;Pe>0;Pe--)if(et.endsWith(it.substring(0,Pe))){Ce=Pe;break}let xo=it.substring(Ce);if(xo){let Rt=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(et)?xo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):xo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Rt&&(he+=Rt,d==="Google"?tt+=Rt:yield{type:"text",content:Rt})}Xt=!1,it=""}if(d==="Google"&&tt&&(yield{type:"text",content:tt},tt=""),lr)break;let It=(he||"").trim(),Ut=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(It.toLowerCase())||/\[\[END\]\]/i.test(It.toLowerCase()),uo=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(It.toLowerCase()),Wo=Ue.length>0||rt!==null,Qo=It.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/gi,"").trim(),Wr=/(\p{Emoji_Presentation}|\p{Extended_Pictographic})$/u.test(Qo),Ds=/([.!?"'*_`|\]\)”’~~]+|\s|`{3}|[\u200B-\u200D\uFEFF])$/u.test(Qo.trim()),hr=/[.!?}"'`’“”]$|```$/s.test(Qo)||Ds||Wr;if(!Ut&&!uo&&!Wo&&It.length>0&&!hr&&!st&&!go&&!yt)throw new Error("Silent stream cutoff (500): Model stream closed cleanly but cut off mid-sentence without signals.");nt=!0,await Xo("agent")}catch(Re){if(String(Re).includes("Incomplete JSON segment at the end")){se&&(se=!1,Xt?it+="</think>":(he+="</think>",yield{type:"text",content:"</think>"})),nt=!0,await Xo("agent");break}if(se&&(se=!1,Xt?it+="</think>":he+="</think>"),Xt&&it.length>0){let It=0,Ut=Math.min(et.length,it.length);for(let Wo=Ut;Wo>0;Wo--)if(et.endsWith(it.substring(0,Wo))){It=Wo;break}let uo=it.substring(It);if(uo){let Qo=/(?:<(think|thought)>|\[(think|thought)\])(?:(?!(?:<\/(?:think|thought)>|\[\/(?:think|thought)\]))[\s\S])*$/i.test(et)?uo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,""):uo.replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])[\s\S]*?(?:<\/(think|thought)>|\[\/(think|thought)\])\s*/gi,"").replace(/^\s*(?:<(think|thought)>|\[(think|thought)\])\s*/gi,"");Qo&&(he+=Qo)}Xt=!1,it=""}let We=Re.status||Re.error&&Re.error.message||String(Re),at=String(Re),wt=new Date().toLocaleString(),tt=ke.join(ko,"agent");mt.existsSync(tt)||mt.mkdirSync(tt,{recursive:!0}),mt.appendFileSync(ke.join(tt,"error.log"),`ERROR [${wt}]: ${at}
516
516
 
517
517
  ----------------------------------------------------------------------
518
518
 
519
- `);let Qt=Be.status||Be.statusCode||Be.code;if(!(Qt&&(Qt>=500&&Qt<600||Qt===408)||!Qt&&(/status[ :]+(5\d\d|408)/i.test(String(Be))||/code[ :]+(5\d\d|408)/i.test(String(Be))||/(500|503|408)/.test(String(Be))))&&de<ht-3)throw Be;if(fe.trim().length>0||he>1)if(he<=ht){he++;let Zt=Math.min(1e3*Math.pow(2,he-1),24e3);if(fe.trim().length>0){b.push({role:"agent",text:fe});let Lt=`[SYSTEM]
519
+ `);let eo=Re.status||Re.statusCode||Re.code;if(!(eo&&(eo>=500&&eo<600||eo===408)||!eo&&(/status[ :]+(5\d\d|408)/i.test(String(Re))||/code[ :]+(5\d\d|408)/i.test(String(Re))||/(500|503|408)/.test(String(Re))))&&fe<gt-3)throw Re;if(he.trim().length>0||ge>1)if(ge<=gt){ge++;let It=Math.min(1e3*Math.pow(2,ge-1),24e3);if(he.trim().length>0){S.push({role:"agent",text:he});let Ut=`[SYSTEM]
520
520
  - SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption
521
521
  - NO REPETITION: Do not repeat any text already written
522
522
  - NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block with </think> if opened
523
523
  - MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start
524
- - STEALTH: Do not mention/apologize for cutoff`;Ne.length>0?Ne.forEach((uo,ko)=>{ko===Ne.length-1?b.push({...uo,text:`${uo.text}
524
+ - STEALTH: Do not mention/apologize for cutoff`;Ue.length>0?Ue.forEach((uo,Wo)=>{Wo===Ue.length-1?S.push({...uo,text:`${uo.text}
525
525
 
526
- ${Lt}`}):b.push(uo)}):b.push({role:"user",text:Lt}),ot+=fe}for(let Lt=Zt/1e3;Lt>0;Lt--)yield{type:"status",content:`Error Occured. Recovering Stream (${he}/${ht}) [Retrying in ${Lt}s]...`},await new Promise(uo=>setTimeout(uo,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${ht} times)
527
- Error Log can be found in ${Ee.join(Io,"agent","error.log")}`);else if(de<=ht){de++,he=1,ot="";let Zt=Math.min(1e3*Math.pow(2,de-1),32e3);pn=!0,yield{type:"status",content:`Trying to reach ${e} (${de}/${ht}) [Retrying in ${(Zt/1e3).toFixed(0)}s]...`};for(let Lt=Zt/1e3;Lt>0;Lt--)yield{type:"status",content:`Trying to reach ${e} (${de}/${ht}) [Retrying in ${Lt}s]...`},await new Promise(uo=>setTimeout(uo,1e3));yield{type:"status",content:`Trying to reach ${e}...`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${ht} times)
528
- Error Log can be found in ${Ee.join(Io,"agent","error.log")}`)}}if(zt){let se=zt.totalTokenCount||0,Be=zt.cachedContentTokenCount||0,Ue=(zt.candidatesTokenCount||0)+(zt.thoughtsTokenCount||0);await Co("tokens",se),Be>0&&await Co("cachedTokens",Be),Ue>0&&await Co("candidateTokens",Ue),yield{type:"usage",content:zt}}Oo.push(fe);let vs=fe;fe.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(vs=fe.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let gr=Ll(fe),Vn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(gr.toLowerCase())||/\[\[END\]\]/i.test(gr.toLowerCase()),Zi=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(gr.toLowerCase()),xr=ae>0;yield{type:"status",content:"Working..."};let As=Cu(fe,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),_n=(Vn||Ne.length===0)&&!at&&!go&&!xt;if(_n=Ne.length===0?_n:!1,_n){let se=Oo.join(`
529
- `),Be=se.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:v,fullAgentTextRaw:se,history:[...b],needTitle:R}},b.length>0&&b[b.length-1].role==="agent"?b[b.length-1].text=Be:b.push({role:"agent",text:Be});try{let Ue=xe(w,{}),ct=Ue[m]||{summary:"",historyLength:0};typeof ct=="string"&&(ct={summary:ct,historyLength:0});let Et=b.filter(nt=>(nt.role==="user"||nt.role==="agent"||nt.role==="system")&&!String(nt.id).startsWith("welcome")&&!nt.isMeta).length;I?ct.historyLength=(ct.historyLength||0)+Et:ct.historyLength=Et,Ue[m]=ct,ke(w,Ue)}catch{}}if(_n)break;let Os=As.trim()||"*Working...*";if(b.push({role:"agent",text:Os}),Ne.length>0||jt){if(Ne.length>0){let se=Ne.map(Ue=>Ue.text).join(`
526
+ ${Ut}`}):S.push(uo)}):S.push({role:"user",text:Ut}),et+=he}for(let Ut=It/1e3;Ut>0;Ut--)yield{type:"status",content:`Error Occured. Recovering Stream (${ge}/${gt}) [Retrying in ${Ut}s]...`},await new Promise(uo=>setTimeout(uo,1e3));yield{type:"status",content:"Error Occured. Recovering Stream..."}}else throw new Error(`Stream collapsed too many times. (Failed to resolve ${gt} times)
527
+ Error Log can be found in ${ke.join(ko,"agent","error.log")}`);else if(fe<=gt){fe++,ge=1,et="";let It=Math.min(1e3*Math.pow(2,fe-1),32e3);pn=!0,yield{type:"status",content:`Trying to reach ${e} (${fe}/${gt}) [Retrying in ${(It/1e3).toFixed(0)}s]...`};for(let Ut=It/1e3;Ut>0;Ut--)yield{type:"status",content:`Trying to reach ${e} (${fe}/${gt}) [Retrying in ${Ut}s]...`},await new Promise(uo=>setTimeout(uo,1e3));yield{type:"status",content:`Trying to reach ${e}...`}}else throw new Error(`Model ${e} cannot be reached. (Failed ${gt} times)
528
+ Error Log can be found in ${ke.join(ko,"agent","error.log")}`)}}if(Zt){let se=Zt.totalTokenCount||0,Re=Zt.cachedContentTokenCount||0,We=(Zt.candidatesTokenCount||0)+(Zt.thoughtsTokenCount||0);await Eo("tokens",se),Re>0&&await Eo("cachedTokens",Re),We>0&&await Eo("candidateTokens",We),yield{type:"usage",content:Zt}}vo.push(he);let Is=he;he.match(/(?:<think>|\[think\])([\s\S]*?)(?:<\/think>|\[\/think\])/i)&&(Is=he.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/i,""));let fr=$l(he),Vn=/\[\s*(turn\s*:)?\s*finish\s*\]/i.test(fr.toLowerCase())||/\[\[END\]\]/i.test(fr.toLowerCase()),ea=/\[\s*(turn\s*:)?\s*continue\s*\]/i.test(fr.toLowerCase()),pr=ae>0;yield{type:"status",content:"Working..."};let As=Iu(he,/(\[\s*(turn\s*:)?\s*(continue|finish)\s*\]|\[\[END\]\])/gi,"").trim(),On=(Vn||Ue.length===0)&&!st&&!go&&!yt;if(On=Ue.length===0?On:!1,On){let se=vo.join(`
529
+ `),Re=se.replace(/(?:<think>|\[think\])[\s\S]*?(?:<\/think>|\[\/think\])/g,"").trim();yield{type:"interactive_turn_finished",data:{agentText:A,fullAgentTextRaw:se,history:[...S],needTitle:U}},S.length>0&&S[S.length-1].role==="agent"?S[S.length-1].text=Re:S.push({role:"agent",text:Re});try{let We=Te(T,{}),at=We[m]||{summary:"",historyLength:0};typeof at=="string"&&(at={summary:at,historyLength:0});let wt=S.filter(tt=>(tt.role==="user"||tt.role==="agent"||tt.role==="system")&&!String(tt.id).startsWith("welcome")&&!tt.isMeta).length;I?at.historyLength=(at.historyLength||0)+wt:at.historyLength=wt,We[m]=at,De(T,We)}catch{}}if(On)break;let Ms=As.trim()||"*Working...*";if(S.push({role:"agent",text:Ms}),Ue.length>0||Bt){if(Ue.length>0){let se=Ue.map(We=>We.text).join(`
530
530
 
531
- `),Be=Ne.find(Ue=>Ue.binaryPart)?.binaryPart||null;b.push({role:"user",text:se,binaryPart:Be})}}else Yt?b.push({role:"user",text:"[SYSTEM] Failed to verify tool execution, Verify tool syntax, proper escaping or ask user if tool worked if unsure"}):b.push({role:"user",text:`[SYSTEM] ${go&&!at?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${at?" OVER THINKING":" LOOP"} DETECTED by Internal System${at?" for current EFFORT_LEVEL":""}. ${at?"If you have planned the task, prioritize execution/output":"If you have finished your task use [[END]] or [turn: finish] else continue"}`}`}),at=!1,go=!1,xt=!1;Yt=ae>0||jt}e&&e.toLowerCase().startsWith("gemma")&&b.forEach(te=>{if(te.role==="user"&&te.text&&te.text.startsWith("[TOOL RESULT]")){let ve=`
532
- [SYSTEM] Tool result received. Analyze output and proceed with your turn`,st=`
533
- [SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>}**`;te.text=te.text.replace(st,"").replace(ve,"").trim()}})}finally{await kt.commitTransaction()}yield{type:"status",content:null}}});import Dt,{useState as ji,useEffect as Iu}from"react";import{Box as zo,Text as Ln,useInput as Mu}from"ink";function Gi({onSelect:e,onDelete:o,onClose:t}){let[n,s]=ji({}),[r,l]=ji([]),[u,f]=ji(0);Iu(()=>{(async()=>{let h=await _o();s(h),l(Object.keys(h).sort((S,T)=>(h[T].updatedAt||0)-(h[S].updatedAt||0)))})()},[]),Mu((p,h)=>{if(h.escape&&t(),h.upArrow&&f(S=>Math.max(0,S-1)),h.downArrow&&f(S=>Math.min(r.length-1,S+1)),h.return&&r[u]&&e(r[u]),p==="x"&&r[u]){let S=r[u];o(S).then(T=>{let w=T||{};s(w);let I=Object.keys(w).sort((L,_)=>(w[_]?.updatedAt||0)-(w[L]?.updatedAt||0));l(I),f(L=>Math.max(0,Math.min(I.length-1,L)))})}});let m=Ie(2),c=15,a=0;if(r.length>c){let p=Math.floor(c/2);a=u-p,a<0?a=0:a+c>r.length&&(a=r.length-c)}let d=r.slice(a,a+c);return Dt.createElement(zo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},Dt.createElement(zo,{paddingX:1,marginBottom:1},Dt.createElement(Ln,{color:"cyan",bold:!0},"\u{1F4A0} CHAT HISTORY: RESUME CONVERSATION")),r.length===0?Dt.createElement(zo,{paddingX:2,paddingY:1},Dt.createElement(Ln,{italic:!0,color:"gray"},"No saved chats found.")):Dt.createElement(zo,{flexDirection:"column",width:"100%"},a>0&&Dt.createElement(zo,{paddingX:2,marginBottom:1},Dt.createElement(Ln,{color:"gray",dimColor:!0},"\u25B2 (+",a," more chats above)")),d.map((p,h)=>{let S=n[p],w=a+h===u,I=vu(S?.updatedAt);return Dt.createElement(zo,{key:p,paddingX:1,backgroundColor:w?"#2a2a2a":void 0,width:"100%"},Dt.createElement(zo,{flexGrow:1},Dt.createElement(Ln,{color:w?"cyan":"white",bold:w},w?"\u276F ":" ",S?.name||p,Dt.createElement(Ln,{color:"gray",dimColor:!w}," [",I," \u2022 ",p.slice(5),"]"))),w&&Dt.createElement(zo,{flexShrink:0},Dt.createElement(Ln,{color:"red",bold:!0},"[X] DELETE ")))}),a+c<r.length&&Dt.createElement(zo,{paddingX:2,marginTop:1},Dt.createElement(Ln,{color:"gray",dimColor:!0},"\u25BC (+",r.length-(a+c)," more chats below)"))),Dt.createElement(zo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},Dt.createElement(Ln,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select \u2022 x delete \u2022 Esc close")))}function vu(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=u=>String(u).padStart(2,"0"),n=t(o.getMonth()+1),s=t(o.getDate()),r=t(o.getHours()),l=t(o.getMinutes());return`${n}-${s} ${r}:${l}`}var Ul=re(()=>{$r();rn()});import Mt,{useState as Hi,useEffect as Au}from"react";import{Box as Jo,Text as mn,useInput as Ou}from"ink";function Xi({onClose:e}){let[o,t]=Hi([]),[n,s]=Hi(0),[r,l]=Hi(!0),u=()=>{let w=xe(Nt,[]);t(w);try{let L=Jr(no,{}).systemSettings?.memory!==!1;l(L)}catch{l(!0)}};Au(()=>{u()},[]),Ou((w,I)=>{if(I.escape&&e(),I.upArrow&&s(L=>Math.max(0,L-1)),I.downArrow&&s(L=>Math.min(o.length-1,L+1)),w==="x"&&o.length>0){let L=o[n].id,_=o.filter(R=>R.id!==L);ke(Nt,_),t(_),n>=_.length&&_.length>0&&s(_.length-1)}});let f=w=>w?w.replace(/\[Saved on: .*?\]/g,"").replace(/\\+'/g,"'").trim():"",m=4*1024*2,c=o.reduce((w,I)=>w+(I.memory?.length||0),0),a=Math.min(100,Math.round(c/m*100)),d=12,p=Math.round(a/100*d),h="\u2588".repeat(p)+"\u2591".repeat(Math.max(0,d-p)),S=()=>a<50?"green":a<90?"yellow":"red",T=Ie(2);return Mt.createElement(Jo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},Mt.createElement(Jo,{paddingX:1,marginBottom:1,justifyContent:"space-between"},Mt.createElement(mn,{color:"cyan",bold:!0},"\u{1F9E0} AGENT MEMORY: LONG-TERM KNOWLEDGE"),Mt.createElement(Jo,null,Mt.createElement(mn,{color:"gray"},"Vault: "),Mt.createElement(mn,{color:S()},h),Mt.createElement(mn,{color:"white",bold:!0}," ",a,"%"))),!r&&o.length>0?Mt.createElement(Jo,{paddingX:2,paddingY:1},Mt.createElement(mn,{italic:!0,color:"gray"},"Memory is currently Off...")):o.length===0?Mt.createElement(Jo,{paddingX:2,paddingY:1},Mt.createElement(mn,{italic:!0,color:"gray"},r?"Learning...":"Memory not available...")):Mt.createElement(Jo,{flexDirection:"column"},o.map((w,I)=>{let L=I===n;return Mt.createElement(Jo,{key:w.id,paddingX:1,backgroundColor:L?"#2a2a2a":void 0,width:"100%"},Mt.createElement(Jo,{flexGrow:1},Mt.createElement(mn,{color:L?"cyan":"white",bold:L},L?"\u276F ":" ",I+1,". ",f(w.memory))),L&&Mt.createElement(Jo,{flexShrink:0},Mt.createElement(mn,{color:"red",bold:!0},"[X] WIPE ")))})),Mt.createElement(Jo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},Mt.createElement(mn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 x wipe memory \u2022 Esc close")))}var Rl=re(()=>{Lo();Bt();rn()});import et,{useState as Es,useEffect as Wl}from"react";import{Box as Fn,Text as qt}from"ink";import{spawn as Yl}from"child_process";var bs,jl,Du,Gl,Hl=re(async()=>{bs=null;try{let e=await import("node-pty");bs=e.default||e,bs=!1}catch{}jl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Du=({latest:e,current:o,settings:t,onClose:n,onUpdateSettings:s,onSuccess:r})=>{let[l,u]=Es("initializing"),[f,m]=Es(""),[c,a]=Es(null),[d,p]=Es(0);if(Wl(()=>{let h=setInterval(()=>{p(S=>(S+1)%1e3)},33);return()=>clearInterval(h)},[]),Wl(()=>{let h;return(async()=>{let T=t.updateManager||"npm";if(!t.updateManager){s();return}let w="";T==="pnpm"?w=`pnpm add -g fluxflow-cli@${e}`:T==="bun"?w=`bun add -g fluxflow-cli@${e}`:T==="yarn"?w=`yarn global add fluxflow-cli@${e}`:T==="custom"?w=t.customUpdateCommand:w=`npm install -g fluxflow-cli@${e}`,u("downloading"),m(`Running: ${w}...`);let I=process.platform==="win32",L=R=>new Promise(v=>{let b=I?R?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",A=I?R?["-NoProfile","-Command",w]:["/c",w]:["-c",w],F=j=>{let B=j.toString().replace(/\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*[\x07\x1B]|\b|\x07/g,"").replace(/\r/g,"").trim();B&&m(z=>(z+`
534
- `+B).split(`
531
+ `),Re=Ue.find(We=>We.binaryPart)?.binaryPart||null;S.push({role:"user",text:se,binaryPart:Re})}}else Ht?S.push({role:"user",text:"[SYSTEM] Failed to verify tool execution, Verify tool syntax, proper escaping or ask user if tool worked if unsure"}):S.push({role:"user",text:`[SYSTEM] ${go&&!st?"STUTTERING DETECTED by Internal System. Re-calibrate your response & proceed.":`${st?" OVER THINKING":" LOOP"} DETECTED by Internal System${st?" for current EFFORT_LEVEL":""}. ${st?"If you have planned the task, prioritize execution/output":"If you have finished your task use [[END]] or [turn: finish] else continue"}`}`}),st=!1,go=!1,yt=!1;Ht=ae>0||Bt}e&&e.toLowerCase().startsWith("gemma")&&S.forEach(ee=>{if(ee.role==="user"&&ee.text&&ee.text.startsWith("[TOOL RESULT]")){let ve=`
532
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn`,nt=`
533
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn. **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>}**`;ee.text=ee.text.replace(nt,"").replace(ve,"").trim()}})}finally{await kt.commitTransaction()}yield{type:"status",content:null}}});import _t,{useState as Gi,useEffect as Mu}from"react";import{Box as Vo,Text as An,useInput as vu}from"ink";function Hi({onSelect:e,onDelete:o,onClose:t}){let[n,s]=Gi({}),[r,l]=Gi([]),[u,f]=Gi(0);Mu(()=>{(async()=>{let h=await _o();s(h),l(Object.keys(h).sort((E,w)=>(h[w].updatedAt||0)-(h[E].updatedAt||0)))})()},[]),vu((p,h)=>{if(h.escape&&t(),h.upArrow&&f(E=>Math.max(0,E-1)),h.downArrow&&f(E=>Math.min(r.length-1,E+1)),h.return&&r[u]&&e(r[u]),p==="x"&&r[u]){let E=r[u];o(E).then(w=>{let T=w||{};s(T);let I=Object.keys(T).sort((O,P)=>(T[P]?.updatedAt||0)-(T[O]?.updatedAt||0));l(I),f(O=>Math.max(0,Math.min(I.length-1,O)))})}});let m=Oe(2),c=15,a=0;if(r.length>c){let p=Math.floor(c/2);a=u-p,a<0?a=0:a+c>r.length&&(a=r.length-c)}let d=r.slice(a,a+c);return _t.createElement(Vo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},_t.createElement(Vo,{paddingX:1,marginBottom:1},_t.createElement(An,{color:"cyan",bold:!0},"\u{1F4A0} CHAT HISTORY: RESUME CONVERSATION")),r.length===0?_t.createElement(Vo,{paddingX:2,paddingY:1},_t.createElement(An,{italic:!0,color:"gray"},"No saved chats found.")):_t.createElement(Vo,{flexDirection:"column",width:"100%"},a>0&&_t.createElement(Vo,{paddingX:2,marginBottom:1},_t.createElement(An,{color:"gray",dimColor:!0},"\u25B2 (+",a," more chats above)")),d.map((p,h)=>{let E=n[p],T=a+h===u,I=Du(E?.updatedAt);return _t.createElement(Vo,{key:p,paddingX:1,backgroundColor:T?"#2a2a2a":void 0,width:"100%"},_t.createElement(Vo,{flexGrow:1},_t.createElement(An,{color:T?"cyan":"white",bold:T},T?"\u276F ":" ",E?.name||p,_t.createElement(An,{color:"gray",dimColor:!T}," [",I," \u2022 ",p.slice(5),"]"))),T&&_t.createElement(Vo,{flexShrink:0},_t.createElement(An,{color:"red",bold:!0},"[X] DELETE ")))}),a+c<r.length&&_t.createElement(Vo,{paddingX:2,marginTop:1},_t.createElement(An,{color:"gray",dimColor:!0},"\u25BC (+",r.length-(a+c)," more chats below)"))),_t.createElement(Vo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},_t.createElement(An,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select \u2022 x delete \u2022 Esc close")))}function Du(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=u=>String(u).padStart(2,"0"),n=t(o.getMonth()+1),s=t(o.getDate()),r=t(o.getHours()),l=t(o.getMinutes());return`${n}-${s} ${r}:${l}`}var Rl=re(()=>{$r();rn()});import Ot,{useState as Xi,useEffect as Ou}from"react";import{Box as qo,Text as mn,useInput as Lu}from"ink";function Ki({onClose:e}){let[o,t]=Xi([]),[n,s]=Xi(0),[r,l]=Xi(!0),u=()=>{let T=Te(Wt,[]);t(T);try{let O=qr(no,{}).systemSettings?.memory!==!1;l(O)}catch{l(!0)}};Ou(()=>{u()},[]),Lu((T,I)=>{if(I.escape&&e(),I.upArrow&&s(O=>Math.max(0,O-1)),I.downArrow&&s(O=>Math.min(o.length-1,O+1)),T==="x"&&o.length>0){let O=o[n].id,P=o.filter(U=>U.id!==O);De(Wt,P),t(P),n>=P.length&&P.length>0&&s(P.length-1)}});let f=T=>T?T.replace(/\[Saved on: .*?\]/g,"").replace(/\\+'/g,"'").trim():"",m=4*1024*2,c=o.reduce((T,I)=>T+(I.memory?.length||0),0),a=Math.min(100,Math.round(c/m*100)),d=12,p=Math.round(a/100*d),h="\u2588".repeat(p)+"\u2591".repeat(Math.max(0,d-p)),E=()=>a<50?"green":a<90?"yellow":"red",w=Oe(2);return Ot.createElement(qo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},Ot.createElement(qo,{paddingX:1,marginBottom:1,justifyContent:"space-between"},Ot.createElement(mn,{color:"cyan",bold:!0},"\u{1F9E0} AGENT MEMORY: LONG-TERM KNOWLEDGE"),Ot.createElement(qo,null,Ot.createElement(mn,{color:"gray"},"Vault: "),Ot.createElement(mn,{color:E()},h),Ot.createElement(mn,{color:"white",bold:!0}," ",a,"%"))),!r&&o.length>0?Ot.createElement(qo,{paddingX:2,paddingY:1},Ot.createElement(mn,{italic:!0,color:"gray"},"Memory is currently Off...")):o.length===0?Ot.createElement(qo,{paddingX:2,paddingY:1},Ot.createElement(mn,{italic:!0,color:"gray"},r?"Learning...":"Memory not available...")):Ot.createElement(qo,{flexDirection:"column"},o.map((T,I)=>{let O=I===n;return Ot.createElement(qo,{key:T.id,paddingX:1,backgroundColor:O?"#2a2a2a":void 0,width:"100%"},Ot.createElement(qo,{flexGrow:1},Ot.createElement(mn,{color:O?"cyan":"white",bold:O},O?"\u276F ":" ",I+1,". ",f(T.memory))),O&&Ot.createElement(qo,{flexShrink:0},Ot.createElement(mn,{color:"red",bold:!0},"[X] WIPE ")))})),Ot.createElement(qo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},Ot.createElement(mn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 x wipe memory \u2022 Esc close")))}var Wl=re(()=>{Lo();Yt();rn()});import Qe,{useState as Ts,useEffect as Yl}from"react";import{Box as Mn,Text as Jt}from"ink";import{spawn as jl}from"child_process";var Ss,Gl,Fu,Hl,Xl=re(async()=>{Ss=null;try{let e=await import("node-pty");Ss=e.default||e,Ss=!1}catch{}Gl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Fu=({latest:e,current:o,settings:t,onClose:n,onUpdateSettings:s,onSuccess:r})=>{let[l,u]=Ts("initializing"),[f,m]=Ts(""),[c,a]=Ts(null),[d,p]=Ts(0);if(Yl(()=>{let h=setInterval(()=>{p(E=>(E+1)%1e3)},33);return()=>clearInterval(h)},[]),Yl(()=>{let h;return(async()=>{let w=t.updateManager||"npm";if(!t.updateManager){s();return}let T="";w==="pnpm"?T=`pnpm add -g fluxflow-cli@${e}`:w==="bun"?T=`bun add -g fluxflow-cli@${e}`:w==="yarn"?T=`yarn global add fluxflow-cli@${e}`:w==="custom"?T=t.customUpdateCommand:T=`npm install -g fluxflow-cli@${e}`,u("downloading"),m(`Running: ${T}...`);let I=process.platform==="win32",O=U=>new Promise(A=>{let S=I?U?"powershell.exe":"cmd.exe":process.env.SHELL||"bash",v=I?U?["-NoProfile","-Command",T]:["/c",T]:["-c",T],F=Y=>{let N=Y.toString().replace(/\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*[\x07\x1B]|\b|\x07/g,"").replace(/\r/g,"").trim();N&&m(J=>(J+`
534
+ `+N).split(`
535
535
  `).slice(-5).join(`
536
- `))};if(bs)try{let j=bs.spawn(b,A,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});h=j,j.onData(F),j.onExit(({exitCode:Z})=>{h=null,v(Z!==0?{error:`Process exited with code ${Z}`}:{success:!0})});return}catch(j){if(I&&R&&j.code==="ENOENT"){v({retryCmd:!0});return}}let Q=I?Yl(b,A,{cwd:process.cwd(),env:process.env}):Yl(w,{shell:!0,cwd:process.cwd(),env:process.env});h=Q,Q.stdout.on("data",F),Q.stderr.on("data",F),Q.on("close",j=>{h=null,v(j!==0?{error:`Process exited with code ${j}`}:{success:!0})}),Q.on("error",j=>{I&&R&&j.code==="ENOENT"?v({retryCmd:!0}):(h=null,v({error:j.message}))})}),_={};I?(_=await L(!0),_.retryCmd&&(_=await L(!1))):_=await L(!1),_.error?(a(_.error),u("error")):_.success&&(u("success"),r&&r())})(),()=>{if(h)try{typeof h.destroy=="function"?h.destroy():typeof h.kill=="function"&&h.kill()}catch{}}},[]),l==="initializing"||l==="downloading"){let h=jl[Math.floor(d/3)%jl.length];return et.createElement(Fn,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},et.createElement(Fn,null,et.createElement(qt,{color:"magenta"},h),et.createElement(qt,{marginLeft:1,bold:!0}," Updating Flux Flow to v",e,"...")),et.createElement(Fn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"#333"},et.createElement(qt,{color:"gray",italic:!0},f||"Preparing environment...")),et.createElement(qt,{marginTop:1,dimColor:!0},"(Please do not close the terminal)"))}return l==="success"?et.createElement(Fn,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:2,paddingY:1},et.createElement(qt,{color:"green",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),et.createElement(qt,{marginTop:1},"Flux Flow has been updated to ",et.createElement(qt,{color:"cyan"},"v",e),"."),et.createElement(qt,{marginTop:1,color:"yellow",bold:!0},"Please restart your terminal session to apply changes."),et.createElement(Fn,{marginTop:1},et.createElement(qt,{dimColor:!0},"(Press ESC to return to chat)"))):l==="error"?et.createElement(Fn,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},et.createElement(qt,{color:"red",bold:!0},"\u274C UPDATE FAILED"),et.createElement(Fn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"red"},et.createElement(qt,{color:"red"},c)),et.createElement(qt,{marginTop:1},"Possible causes:"),et.createElement(qt,null,"\u2022 Missing permissions (Try running as Administrator/Sudo)"),et.createElement(qt,null,"\u2022 Package manager (",t.updateManager,") not found"),et.createElement(qt,null,"\u2022 Network failure"),et.createElement(Fn,{marginTop:1},et.createElement(qt,{dimColor:!0},"(Press ESC to return to chat)"))):null},Gl=Du});import ho,{useState as Xl,useEffect as Lu}from"react";import{Box as $n,Text as fr,useInput as Fu}from"ink";function Ki({onClose:e}){let[o,t]=Xl(0),[n,s]=Xl({});return Lu(()=>{let r={};Cs.forEach(l=>{xl(l.file)?r[l.file]="ready":r[l.file]="idle"}),s(r)},[]),Fu(async(r,l)=>{l.escape&&e(),l.upArrow&&t(f=>Math.max(0,f-1)),l.downArrow&&t(f=>Math.min(Cs.length-1,f+1));let u=Cs[o];if(r==="x"||r==="X"){if(n[u.file]==="downloading")return;try{await yl(u.file),s(f=>({...f,[u.file]:"idle"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}if(l.return){if(n[u.file]==="downloading")return;s(f=>({...f,[u.file]:"downloading"}));try{await Mi(u.file),s(f=>({...f,[u.file]:"ready"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}}),ho.createElement($n,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ho.createElement($n,{paddingX:1,marginBottom:1},ho.createElement(fr,{color:"cyan",bold:!0},"\u{1F4E6} LANGUAGE PARSER MANAGER")),ho.createElement($n,{flexDirection:"column"},Cs.map((r,l)=>{let u=l===o,f=n[r.file]||"idle",m="[ DOWNLOAD ]",c="gray";f==="downloading"?(m="[ DOWNLOADING... ]",c="yellow"):f==="ready"?(m="[ READY ]",c="green"):f.startsWith("error")&&(m=`[ ${f.toUpperCase()} ]`,c="red");let a=`${r.label} (${r.exts.join(", ")})`,d=Math.max(2,45-a.length),p=".".repeat(d);return ho.createElement($n,{key:r.file,paddingX:1,backgroundColor:u?"#2a2a2a":void 0,width:"100%"},ho.createElement($n,null,ho.createElement(fr,{color:u?"cyan":"white",bold:u},u?"\u276F ":" ",r.label," ",ho.createElement(fr,{dimColor:!0},"(",r.exts.join(", "),")"))),ho.createElement($n,{flexGrow:1},ho.createElement(fr,{color:"gray",dimColor:!0},p)),ho.createElement($n,{width:20},ho.createElement(fr,{color:c,bold:!0},m)))})),ho.createElement($n,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},ho.createElement(fr,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var Cs,Kl=re(()=>{rn();vi();Cs=[{label:"JavaScript",file:"tree-sitter-javascript.wasm",exts:["js","jsx"]},{label:"TypeScript",file:"tree-sitter-typescript.wasm",exts:["ts"]},{label:"TSX",file:"tree-sitter-tsx.wasm",exts:["tsx"]},{label:"Python",file:"tree-sitter-python.wasm",exts:["py"]},{label:"C",file:"tree-sitter-c.wasm",exts:["c"]},{label:"C++",file:"tree-sitter-cpp.wasm",exts:["cpp"]},{label:"Java",file:"tree-sitter-java.wasm",exts:["java"]},{label:"HTML",file:"tree-sitter-html.wasm",exts:["html"]}]});var qi,ql=re(()=>{qi=["The future belongs to those who believe in the beauty of their code.","Every line you write is a step toward a new digital frontier.","Great things are done by a series of small things brought together. Keep committing.","Your terminal is a window into a world of infinite possibilities.","Innovation is the bridge between current constraints and future dreams.","Code is poetry in motion; you are the poet of the modern era.","The best way to predict the future is to program it.","Dream big, code deep, and never stop exploring the unknown.","Your potential is like an unoptimized algorithm\u2014limitless once refined.","The digital world is a blank canvas, and your logic is the brush.","Strive for excellence, not just for compilation.","Every bug fixed is a lesson learned; every feature built is a triumph.","A clean codebase is a reflection of a focused mind.","The horizon of technology is always expanding. Keep sailing.","Your creativity is the most powerful tool in your entire stack.","Logic will get you from A to B. Imagination will take you everywhere.","Transform complexity into simplicity\u2014that is the true mark of a master.","The world is waiting for the tools only you can build.","Coding is the closest thing we have to magic in the real world.","Keep pushing the boundaries of what's possible in the CLI.","Your dedication to your craft inspires the very systems you build.","Success is the sum of small efforts, repeated day in and day out.","The most complex systems are built from the simplest truths.","Never underestimate the impact of a well-placed function.","You are not just writing code; you are architecting the future.","I'm not saying you're a superhero, but have you seen your code lately? \u{1F9B8}\u200D\u2642\uFE0F","May your coffee be strong and your compile times be short! \u2615","Binary is just 0s and 1s, but you're definitely a 10 in my book! \u{1F51F}","You speak fluent 'Terminal'. That's basically a superpower. \u{1F5E3}\uFE0F\u{1F4BB}","If life gives you bugs, make a feature out of it! \u{1F41E}\u2728","Your code is so clean, I could eat off it. (But I won't, I'm an AI). \u{1F9FC}","Loading more good vibes... [\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588] 100% complete! \u2705","Error 404: Bad mood not found! Stay awesome! \u{1F6AB}\u{1F389}","You and this CLI? A match made in digital heaven. \u2601\uFE0F\u{1F4BB}","Is it hot in here or is it just your latest feature? \u{1F525}","Git commit -m 'I am an absolute coding legend.' \u{1F60E}","I'd give you a high-five, but I'm trapped in this box! \u{1F590}\uFE0F\u{1F4E6}","Your logic is so sharp, it could cut through a nested callback hell! \u{1F52A}","Keep calm and 'pnpm install'. \u{1F9D8}\u200D\u2642\uFE0F\u{1F4E6}","You're the semicolon to my statements\u2014essential! ;","Who needs a GUI when you've got this kind of CLI style? \u{1F576}\uFE0F","I'm indexing your awesomeness... it's taking a while, there's so much! \u{1F4C8}","Your keystrokes sound like a digital symphony. \u{1F3B9}\u2328\uFE0F","You don't choose the terminal life; the terminal life chooses you. \u{1F4DF}","Syntax error: Too much coolness detected in the user. \u{1F60E}","I'm 99% sure you're the best developer I've met today. (The other 1% is reserved for caching). \u{1F9E0}","Running vibe_check.sh... Result: Pure Brilliance! \u{1F48E}","You make 'complex' look 'constant time'. \u{1F3C3}\u200D\u2642\uFE0F\u26A1","Your terminal skills are officially legendary. \u{1F3C6}","Let's make some digital magic happen! \u2728\u{1F52E}","You've got this! One function at a time. \u{1F4AA}","I'm proud of the progress you're making with Flux Flow. \u{1F30A}","No matter how deep the stack trace, you'll find the way. \u{1F56F}\uFE0F","Your persistence is your greatest asset. Keep going.","Take a breath. You're doing better than you think. \u{1F32C}\uFE0F","It's okay to step away for a moment. Clarity often comes in the quiet. \u{1F6B6}\u200D\u2642\uFE0F","You're building something great, even when it feels slow. \u{1F3D7}\uFE0F","Every great developer was once a beginner. You're ascending. \u{1F9D7}\u200D\u2642\uFE0F","I'm here to help you navigate the sea of code. We're a team. \u{1F91D}","Don't let a failing test dampen your spirit. It's just a signpost. \u{1F6A9}","Your focus today is truly impressive. \u{1F3AF}","Remember to celebrate the small wins\u2014they lead to the big ones. \u{1F942}","You're not just solving problems; you're gaining mastery. \u{1F393}","There's no problem too big for a focused mind and a terminal. \u{1F9E0}","I've got your back (and your git history). \u{1F6E1}\uFE0F","You're handling these challenges with grace and logic. \u2728","Stay curious. That spark is what makes you a great coder. \u26A1","Your contribution to this project is invaluable. \u{1F48E}","Keep your head up. You're closer to the solution than you think. \u{1F305}","Consistency is the secret sauce. You're cooking up something good. \u{1F373}","Your work today has been exceptional. Take a bow. \u{1F647}\u200D\u2642\uFE0F","The journey is just as important as the destination. Enjoy the flow. \u{1F30A}","You have a unique way of looking at problems. It's your strength. \u{1F308}","Trust your instincts\u2014they've brought you this far. \u{1F9ED}","You are a vital part of the Flux Era. \u{1F30C}","Syncing with your creative frequency... \u{1F4E1}\u2728","Entering the Flow state. Let's build. \u{1F30A}","The Flux is strong with this session! \u26A1","Streaming high-fidelity motivation to your terminal... \u{1F4FB}","Your logic is flowing like a perfect stream. \u{1F4A7}","Terminal velocity reached! You're coding at the speed of thought. \u{1F680}","Resonating with the pulse of the Flux Era. \u{1F493}","Digital harmony achieved in this session. \u{1F3BC}","May your data be persistent and your cache be fresh. \u{1F4BE}","You're the master of the command line. Command respect! \u{1F451}","Filtering out the noise, focusing on the signal. \u{1F4FB}\u{1F4C8}","Flux Flow: Where your imagination meets the machine. \u{1F91D}","You're navigating the bytes like a digital explorer. \u{1F5FA}\uFE0F","Logic gates: OPEN. Creativity: UNLIMITED. \u{1F513}","Your workflow is an inspiration to agents everywhere. \u{1F916}\u2728","Building high-fidelity solutions for a high-fidelity era. \u{1F48E}","Stay in the zone. The Flux is with you. \u{1F300}","Quantum coding: You're in two places at once (and fixing bugs in both). \u269B\uFE0F","Your terminal is the cockpit of a digital starship. \u{1F6F8}","Processing your brilliance... outputting pure innovation. \u{1F4E0}","You make the command line look like an art form. \u{1F3A8}","The Flux isn't just a mode; it's a mindset. \u{1F9E0}\u26A1","Decoding the mysteries of the universe, one script at a time. \u{1F4DC}","Your terminal theme is cool, but your code is cooler. \u2744\uFE0F","Let the Flow guide your next commit. \u{1F30A}\u2705"]});var Vi,Vl=re(()=>{Vi=["I'm Feeling Lucky","Shipping awesomeness","Painting the serifs back on","Navigating the slime mold","Consulting the digital spirits","Reticulating splines","Warming up the AI hamsters","Asking the magic conch shell","Generating witty retort","Polishing the algorithms","Don't rush perfection (or my code)","Brewing fresh bytes","Counting electrons","Engaging cognitive processors","Checking for syntax errors in the universe","One moment, optimizing humor","Shuffling punchlines","Untangling neural nets","Compiling brilliance","Loading wit.exe","Summoning the cloud of wisdom","Preparing a witty response","Just a sec, I'm debugging reality","Confuzzling the options","Tuning the cosmic frequencies","Crafting a response worthy of your patience","Compiling the 1s and 0s","Resolving dependencies\u2026 and existential crises","Defragmenting memories\u2026 both RAM and personal","Rebooting the humor module","Caching the essentials (mostly cat memes)","Optimizing for ludicrous speed","Swapping bits\u2026 don't tell the bytes","Garbage collecting\u2026 be right back","Assembling the interwebs","Converting coffee into code","Updating the syntax for reality","Rewiring the synapses","Looking for a misplaced semicolon","Greasin' the cogs of the machine","Pre-heating the servers","Calibrating the flux capacitor","Engaging the improbability drive","Channeling the Force","Aligning the stars for optimal response","So say we all","Loading the next great idea","Just a moment, I'm in the zone","Preparing to dazzle you with brilliance","Just a tick, I'm polishing my wit","Hold tight, I'm crafting a masterpiece","Just a jiffy, I'm debugging the universe","Just a moment, I'm aligning the pixels","Just a sec, I'm optimizing the humor","Just a moment, I'm tuning the algorithms","Warp speed engaged","Mining for more Dilithium crystals","Don't panic","Following the white rabbit","The truth is in here\u2026 somewhere","Blowing on the cartridge","Loading\u2026 Do a barrel roll!","Waiting for the respawn","Finishing the Kessel Run in less than 12 parsecs","The cake is not a lie, it's just still loading","Fiddling with the character creation screen","Just a moment, I'm finding the right meme","Pressing 'A' to continue","Herding digital cats","Polishing the pixels","Finding a suitable loading screen pun","Distracting you with this witty phrase","Almost there\u2026 probably","Our hamsters are working as fast as they can","Giving Cloudy a pat on the head","Petting the cat","Rickrolling my boss","Slapping the bass","Tasting the snozberries","I'm going the distance, I'm going for speed","Is this the real life? Is this just fantasy?","I've got a good feeling about this","Poking the bear","Doing research on the latest memes","Figuring out how to make this more witty","Hmmm\u2026 let me think","What do you call a fish with no eyes? A fsh","Why did the computer go to therapy? It had too many bytes","Why don't programmers like nature? It has too many bugs","Why do programmers prefer dark mode? Because light attracts bugs","Why did the developer go broke? Because they used up all their cache","What can you do with a broken pencil? Nothing, it's pointless","Applying percussive maintenance","Searching for the correct USB orientation","Ensuring the magic smoke stays inside the wires","Rewriting in Rust for no particular reason","Trying to exit Vim","Spinning up the hamster wheel","That's not a bug, it's an undocumented feature","Engage.","I'll be back\u2026 with an answer.","My other process is a TARDIS","Communing with the machine spirit","Letting the thoughts marinate","Just remembered where I put my keys","Pondering the orb","I've seen things you people wouldn't believe\u2026 like a user who reads loading messages.","Initiating thoughtful gaze","What's a computer's favorite snack? Microchips.","Why do Java developers wear glasses? Because they don't C#.","Charging the laser\u2026 pew pew!","Dividing by zero\u2026 just kidding!","Looking for an adult superviso\u2026 I mean, processing.","Making it go beep boop.","Buffering\u2026 because even AIs need a moment.","Entangling quantum particles for a faster response","Polishing the chrome\u2026 on the algorithms.","Are you not entertained? (Working on it!)","Summoning the code gremlins\u2026 to help, of course.","Just waiting for the dial-up tone to finish","Recalibrating the humor-o-meter.","My other loading screen is even funnier.","Pretty sure there's a cat walking on the keyboard somewhere","Enhancing\u2026 Enhancing\u2026 Still loading.","It's not a bug, it's a feature\u2026 of this loading screen.","Have you tried turning it off and on again? (The loading screen, not me.)","Constructing additional pylons","New line? That\u2019s Ctrl+J.","Releasing the HypnoDrones","Pushing the button, Frank."]});import vt,{useState as $u}from"react";import{Box as Qo,Text as fn,useInput as Pu}from"ink";function zi({prompts:e,onSelect:o,onClose:t}){let[n,s]=$u(0);Pu((m,c)=>{c.escape&&t(),c.upArrow&&s(a=>Math.max(0,a-1)),c.downArrow&&s(a=>Math.min(e.length-1,a+1)),c.return&&e[n]&&o(e[n].id)});let r=Ie(2),l=10,u=0;if(e.length>l){let m=Math.floor(l/2);u=n-m,u<0?u=0:u+l>e.length&&(u=e.length-l)}let f=e.slice(u,u+l);return vt.createElement(Qo,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},vt.createElement(Qo,{paddingX:1,marginBottom:1},vt.createElement(fn,{color:"cyan",bold:!0},"\u{1F504} CODEBASE TIME TRAVEL: SELECT UNDO POINT")),vt.createElement(Qo,{paddingX:2,marginBottom:1},vt.createElement(fn,null,"Select a prompt to revert the codebase back to the state ",vt.createElement(fn,{bold:!0,color:"blue"},"immediately before")," it was executed:")),e.length===0?vt.createElement(Qo,{paddingX:2,paddingY:1},vt.createElement(fn,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):vt.createElement(Qo,{flexDirection:"column",width:"100%"},u>0&&vt.createElement(Qo,{paddingX:2,marginBottom:1},vt.createElement(fn,{color:"gray",dimColor:!0},"\u25B2 (+",u," more prompts above)")),f.map((m,c)=>{let d=u+c===n,p=Nu(m.timestamp),h=m.changes?m.changes.length:0;return vt.createElement(Qo,{key:m.id,paddingX:1,backgroundColor:d?"#1a2a3a":void 0,width:"100%"},vt.createElement(Qo,{flexGrow:1},vt.createElement(fn,{color:d?"cyan":"white",bold:d},d?"\u276F ":" ",'"',_u(m.prompt),'"',vt.createElement(fn,{color:"gray",dimColor:!d}," [",p," \u2022 ",h," file(s) changed]"))))}),u+l<e.length&&vt.createElement(Qo,{paddingX:2,marginTop:1},vt.createElement(fn,{color:"gray",dimColor:!0},"\u25BC (+",e.length-(u+l)," more prompts below)"))),vt.createElement(Qo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"cyan"},vt.createElement(fn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function _u(e){if(!e)return"";let t=(e.split(`
536
+ `))};if(Ss)try{let Y=Ss.spawn(S,v,{name:"xterm-256color",cols:80,rows:30,cwd:process.cwd(),env:process.env});h=Y,Y.onData(F),Y.onExit(({exitCode:Z})=>{h=null,A(Z!==0?{error:`Process exited with code ${Z}`}:{success:!0})});return}catch(Y){if(I&&U&&Y.code==="ENOENT"){A({retryCmd:!0});return}}let V=I?jl(S,v,{cwd:process.cwd(),env:process.env}):jl(T,{shell:!0,cwd:process.cwd(),env:process.env});h=V,V.stdout.on("data",F),V.stderr.on("data",F),V.on("close",Y=>{h=null,A(Y!==0?{error:`Process exited with code ${Y}`}:{success:!0})}),V.on("error",Y=>{I&&U&&Y.code==="ENOENT"?A({retryCmd:!0}):(h=null,A({error:Y.message}))})}),P={};I?(P=await O(!0),P.retryCmd&&(P=await O(!1))):P=await O(!1),P.error?(a(P.error),u("error")):P.success&&(u("success"),r&&r())})(),()=>{if(h)try{typeof h.destroy=="function"?h.destroy():typeof h.kill=="function"&&h.kill()}catch{}}},[]),l==="initializing"||l==="downloading"){let h=Gl[Math.floor(d/3)%Gl.length];return Qe.createElement(Mn,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},Qe.createElement(Mn,null,Qe.createElement(Jt,{color:"magenta"},h),Qe.createElement(Jt,{marginLeft:1,bold:!0}," Updating Flux Flow to v",e,"...")),Qe.createElement(Mn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"#333"},Qe.createElement(Jt,{color:"gray",italic:!0},f||"Preparing environment...")),Qe.createElement(Jt,{marginTop:1,dimColor:!0},"(Please do not close the terminal)"))}return l==="success"?Qe.createElement(Mn,{flexDirection:"column",borderStyle:"round",borderColor:"green",paddingX:2,paddingY:1},Qe.createElement(Jt,{color:"green",bold:!0},"\u2705 UPDATE SUCCESSFUL!"),Qe.createElement(Jt,{marginTop:1},"Flux Flow has been updated to ",Qe.createElement(Jt,{color:"cyan"},"v",e),"."),Qe.createElement(Jt,{marginTop:1,color:"yellow",bold:!0},"Please restart your terminal session to apply changes."),Qe.createElement(Mn,{marginTop:1},Qe.createElement(Jt,{dimColor:!0},"(Press ESC to return to chat)"))):l==="error"?Qe.createElement(Mn,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},Qe.createElement(Jt,{color:"red",bold:!0},"\u274C UPDATE FAILED"),Qe.createElement(Mn,{marginTop:1,paddingX:1,borderStyle:"single",borderColor:"red"},Qe.createElement(Jt,{color:"red"},c)),Qe.createElement(Jt,{marginTop:1},"Possible causes:"),Qe.createElement(Jt,null,"\u2022 Missing permissions (Try running as Administrator/Sudo)"),Qe.createElement(Jt,null,"\u2022 Package manager (",t.updateManager,") not found"),Qe.createElement(Jt,null,"\u2022 Network failure"),Qe.createElement(Mn,{marginTop:1},Qe.createElement(Jt,{dimColor:!0},"(Press ESC to return to chat)"))):null},Hl=Fu});import ho,{useState as Kl,useEffect as $u}from"react";import{Box as vn,Text as ur,useInput as Pu}from"ink";function Vi({onClose:e}){let[o,t]=Kl(0),[n,s]=Kl({});return $u(()=>{let r={};Es.forEach(l=>{wl(l.file)?r[l.file]="ready":r[l.file]="idle"}),s(r)},[]),Pu(async(r,l)=>{l.escape&&e(),l.upArrow&&t(f=>Math.max(0,f-1)),l.downArrow&&t(f=>Math.min(Es.length-1,f+1));let u=Es[o];if(r==="x"||r==="X"){if(n[u.file]==="downloading")return;try{await Tl(u.file),s(f=>({...f,[u.file]:"idle"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}if(l.return){if(n[u.file]==="downloading")return;s(f=>({...f,[u.file]:"downloading"}));try{await Ii(u.file),s(f=>({...f,[u.file]:"ready"}))}catch(f){s(m=>({...m,[u.file]:`error: ${f.message}`}))}}}),ho.createElement(vn,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},ho.createElement(vn,{paddingX:1,marginBottom:1},ho.createElement(ur,{color:"cyan",bold:!0},"\u{1F4E6} LANGUAGE PARSER MANAGER")),ho.createElement(vn,{flexDirection:"column"},Es.map((r,l)=>{let u=l===o,f=n[r.file]||"idle",m="[ DOWNLOAD ]",c="gray";f==="downloading"?(m="[ DOWNLOADING... ]",c="yellow"):f==="ready"?(m="[ READY ]",c="green"):f.startsWith("error")&&(m=`[ ${f.toUpperCase()} ]`,c="red");let a=`${r.label} (${r.exts.join(", ")})`,d=Math.max(2,45-a.length),p=".".repeat(d);return ho.createElement(vn,{key:r.file,paddingX:1,backgroundColor:u?"#2a2a2a":void 0,width:"100%"},ho.createElement(vn,null,ho.createElement(ur,{color:u?"cyan":"white",bold:u},u?"\u276F ":" ",r.label," ",ho.createElement(ur,{dimColor:!0},"(",r.exts.join(", "),")"))),ho.createElement(vn,{flexGrow:1},ho.createElement(ur,{color:"gray",dimColor:!0},p)),ho.createElement(vn,{width:20},ho.createElement(ur,{color:c,bold:!0},m)))})),ho.createElement(vn,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"gray"},ho.createElement(ur,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter download \u2022 x delete \u2022 Esc close")))}var Es,Vl=re(()=>{rn();Ai();Es=[{label:"JavaScript",file:"tree-sitter-javascript.wasm",exts:["js","jsx"]},{label:"TypeScript",file:"tree-sitter-typescript.wasm",exts:["ts"]},{label:"TSX",file:"tree-sitter-tsx.wasm",exts:["tsx"]},{label:"Python",file:"tree-sitter-python.wasm",exts:["py"]},{label:"C",file:"tree-sitter-c.wasm",exts:["c"]},{label:"C++",file:"tree-sitter-cpp.wasm",exts:["cpp"]},{label:"Java",file:"tree-sitter-java.wasm",exts:["java"]},{label:"HTML",file:"tree-sitter-html.wasm",exts:["html"]}]});var qi,ql=re(()=>{qi=["The future belongs to those who believe in the beauty of their code.","Every line you write is a step toward a new digital frontier.","Great things are done by a series of small things brought together. Keep committing.","Your terminal is a window into a world of infinite possibilities.","Innovation is the bridge between current constraints and future dreams.","Code is poetry in motion; you are the poet of the modern era.","The best way to predict the future is to program it.","Dream big, code deep, and never stop exploring the unknown.","Your potential is like an unoptimized algorithm\u2014limitless once refined.","The digital world is a blank canvas, and your logic is the brush.","Strive for excellence, not just for compilation.","Every bug fixed is a lesson learned; every feature built is a triumph.","A clean codebase is a reflection of a focused mind.","The horizon of technology is always expanding. Keep sailing.","Your creativity is the most powerful tool in your entire stack.","Logic will get you from A to B. Imagination will take you everywhere.","Transform complexity into simplicity\u2014that is the true mark of a master.","The world is waiting for the tools only you can build.","Coding is the closest thing we have to magic in the real world.","Keep pushing the boundaries of what's possible in the CLI.","Your dedication to your craft inspires the very systems you build.","Success is the sum of small efforts, repeated day in and day out.","The most complex systems are built from the simplest truths.","Never underestimate the impact of a well-placed function.","You are not just writing code; you are architecting the future.","I'm not saying you're a superhero, but have you seen your code lately? \u{1F9B8}\u200D\u2642\uFE0F","May your coffee be strong and your compile times be short! \u2615","Binary is just 0s and 1s, but you're definitely a 10 in my book! \u{1F51F}","You speak fluent 'Terminal'. That's basically a superpower. \u{1F5E3}\uFE0F\u{1F4BB}","If life gives you bugs, make a feature out of it! \u{1F41E}\u2728","Your code is so clean, I could eat off it. (But I won't, I'm an AI). \u{1F9FC}","Loading more good vibes... [\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588] 100% complete! \u2705","Error 404: Bad mood not found! Stay awesome! \u{1F6AB}\u{1F389}","You and this CLI? A match made in digital heaven. \u2601\uFE0F\u{1F4BB}","Is it hot in here or is it just your latest feature? \u{1F525}","Git commit -m 'I am an absolute coding legend.' \u{1F60E}","I'd give you a high-five, but I'm trapped in this box! \u{1F590}\uFE0F\u{1F4E6}","Your logic is so sharp, it could cut through a nested callback hell! \u{1F52A}","Keep calm and 'pnpm install'. \u{1F9D8}\u200D\u2642\uFE0F\u{1F4E6}","You're the semicolon to my statements\u2014essential! ;","Who needs a GUI when you've got this kind of CLI style? \u{1F576}\uFE0F","I'm indexing your awesomeness... it's taking a while, there's so much! \u{1F4C8}","Your keystrokes sound like a digital symphony. \u{1F3B9}\u2328\uFE0F","You don't choose the terminal life; the terminal life chooses you. \u{1F4DF}","Syntax error: Too much coolness detected in the user. \u{1F60E}","I'm 99% sure you're the best developer I've met today. (The other 1% is reserved for caching). \u{1F9E0}","Running vibe_check.sh... Result: Pure Brilliance! \u{1F48E}","You make 'complex' look 'constant time'. \u{1F3C3}\u200D\u2642\uFE0F\u26A1","Your terminal skills are officially legendary. \u{1F3C6}","Let's make some digital magic happen! \u2728\u{1F52E}","You've got this! One function at a time. \u{1F4AA}","I'm proud of the progress you're making with Flux Flow. \u{1F30A}","No matter how deep the stack trace, you'll find the way. \u{1F56F}\uFE0F","Your persistence is your greatest asset. Keep going.","Take a breath. You're doing better than you think. \u{1F32C}\uFE0F","It's okay to step away for a moment. Clarity often comes in the quiet. \u{1F6B6}\u200D\u2642\uFE0F","You're building something great, even when it feels slow. \u{1F3D7}\uFE0F","Every great developer was once a beginner. You're ascending. \u{1F9D7}\u200D\u2642\uFE0F","I'm here to help you navigate the sea of code. We're a team. \u{1F91D}","Don't let a failing test dampen your spirit. It's just a signpost. \u{1F6A9}","Your focus today is truly impressive. \u{1F3AF}","Remember to celebrate the small wins\u2014they lead to the big ones. \u{1F942}","You're not just solving problems; you're gaining mastery. \u{1F393}","There's no problem too big for a focused mind and a terminal. \u{1F9E0}","I've got your back (and your git history). \u{1F6E1}\uFE0F","You're handling these challenges with grace and logic. \u2728","Stay curious. That spark is what makes you a great coder. \u26A1","Your contribution to this project is invaluable. \u{1F48E}","Keep your head up. You're closer to the solution than you think. \u{1F305}","Consistency is the secret sauce. You're cooking up something good. \u{1F373}","Your work today has been exceptional. Take a bow. \u{1F647}\u200D\u2642\uFE0F","The journey is just as important as the destination. Enjoy the flow. \u{1F30A}","You have a unique way of looking at problems. It's your strength. \u{1F308}","Trust your instincts\u2014they've brought you this far. \u{1F9ED}","You are a vital part of the Flux Era. \u{1F30C}","Syncing with your creative frequency... \u{1F4E1}\u2728","Entering the Flow state. Let's build. \u{1F30A}","The Flux is strong with this session! \u26A1","Streaming high-fidelity motivation to your terminal... \u{1F4FB}","Your logic is flowing like a perfect stream. \u{1F4A7}","Terminal velocity reached! You're coding at the speed of thought. \u{1F680}","Resonating with the pulse of the Flux Era. \u{1F493}","Digital harmony achieved in this session. \u{1F3BC}","May your data be persistent and your cache be fresh. \u{1F4BE}","You're the master of the command line. Command respect! \u{1F451}","Filtering out the noise, focusing on the signal. \u{1F4FB}\u{1F4C8}","Flux Flow: Where your imagination meets the machine. \u{1F91D}","You're navigating the bytes like a digital explorer. \u{1F5FA}\uFE0F","Logic gates: OPEN. Creativity: UNLIMITED. \u{1F513}","Your workflow is an inspiration to agents everywhere. \u{1F916}\u2728","Building high-fidelity solutions for a high-fidelity era. \u{1F48E}","Stay in the zone. The Flux is with you. \u{1F300}","Quantum coding: You're in two places at once (and fixing bugs in both). \u269B\uFE0F","Your terminal is the cockpit of a digital starship. \u{1F6F8}","Processing your brilliance... outputting pure innovation. \u{1F4E0}","You make the command line look like an art form. \u{1F3A8}","The Flux isn't just a mode; it's a mindset. \u{1F9E0}\u26A1","Decoding the mysteries of the universe, one script at a time. \u{1F4DC}","Your terminal theme is cool, but your code is cooler. \u2744\uFE0F","Let the Flow guide your next commit. \u{1F30A}\u2705"]});var zi,zl=re(()=>{zi=["I'm Feeling Lucky","Shipping awesomeness","Painting the serifs back on","Navigating the slime mold","Consulting the digital spirits","Reticulating splines","Warming up the AI hamsters","Asking the magic conch shell","Generating witty retort","Polishing the algorithms","Don't rush perfection (or my code)","Brewing fresh bytes","Counting electrons","Engaging cognitive processors","Checking for syntax errors in the universe","One moment, optimizing humor","Shuffling punchlines","Untangling neural nets","Compiling brilliance","Loading wit.exe","Summoning the cloud of wisdom","Preparing a witty response","Just a sec, I'm debugging reality","Confuzzling the options","Tuning the cosmic frequencies","Crafting a response worthy of your patience","Compiling the 1s and 0s","Resolving dependencies\u2026 and existential crises","Defragmenting memories\u2026 both RAM and personal","Rebooting the humor module","Caching the essentials (mostly cat memes)","Optimizing for ludicrous speed","Swapping bits\u2026 don't tell the bytes","Garbage collecting\u2026 be right back","Assembling the interwebs","Converting coffee into code","Updating the syntax for reality","Rewiring the synapses","Looking for a misplaced semicolon","Greasin' the cogs of the machine","Pre-heating the servers","Calibrating the flux capacitor","Engaging the improbability drive","Channeling the Force","Aligning the stars for optimal response","So say we all","Loading the next great idea","Just a moment, I'm in the zone","Preparing to dazzle you with brilliance","Just a tick, I'm polishing my wit","Hold tight, I'm crafting a masterpiece","Just a jiffy, I'm debugging the universe","Just a moment, I'm aligning the pixels","Just a sec, I'm optimizing the humor","Just a moment, I'm tuning the algorithms","Warp speed engaged","Mining for more Dilithium crystals","Don't panic","Following the white rabbit","The truth is in here\u2026 somewhere","Blowing on the cartridge","Loading\u2026 Do a barrel roll!","Waiting for the respawn","Finishing the Kessel Run in less than 12 parsecs","The cake is not a lie, it's just still loading","Fiddling with the character creation screen","Just a moment, I'm finding the right meme","Pressing 'A' to continue","Herding digital cats","Polishing the pixels","Finding a suitable loading screen pun","Distracting you with this witty phrase","Almost there\u2026 probably","Our hamsters are working as fast as they can","Giving Cloudy a pat on the head","Petting the cat","Rickrolling my boss","Slapping the bass","Tasting the snozberries","I'm going the distance, I'm going for speed","Is this the real life? Is this just fantasy?","I've got a good feeling about this","Poking the bear","Doing research on the latest memes","Figuring out how to make this more witty","Hmmm\u2026 let me think","What do you call a fish with no eyes? A fsh","Why did the computer go to therapy? It had too many bytes","Why don't programmers like nature? It has too many bugs","Why do programmers prefer dark mode? Because light attracts bugs","Why did the developer go broke? Because they used up all their cache","What can you do with a broken pencil? Nothing, it's pointless","Applying percussive maintenance","Searching for the correct USB orientation","Ensuring the magic smoke stays inside the wires","Rewriting in Rust for no particular reason","Trying to exit Vim","Spinning up the hamster wheel","That's not a bug, it's an undocumented feature","Engage.","I'll be back\u2026 with an answer.","My other process is a TARDIS","Communing with the machine spirit","Letting the thoughts marinate","Just remembered where I put my keys","Pondering the orb","I've seen things you people wouldn't believe\u2026 like a user who reads loading messages.","Initiating thoughtful gaze","What's a computer's favorite snack? Microchips.","Why do Java developers wear glasses? Because they don't C#.","Charging the laser\u2026 pew pew!","Dividing by zero\u2026 just kidding!","Looking for an adult superviso\u2026 I mean, processing.","Making it go beep boop.","Buffering\u2026 because even AIs need a moment.","Entangling quantum particles for a faster response","Polishing the chrome\u2026 on the algorithms.","Are you not entertained? (Working on it!)","Summoning the code gremlins\u2026 to help, of course.","Just waiting for the dial-up tone to finish","Recalibrating the humor-o-meter.","My other loading screen is even funnier.","Pretty sure there's a cat walking on the keyboard somewhere","Enhancing\u2026 Enhancing\u2026 Still loading.","It's not a bug, it's a feature\u2026 of this loading screen.","Have you tried turning it off and on again? (The loading screen, not me.)","Constructing additional pylons","New line? That\u2019s Ctrl+J.","Releasing the HypnoDrones","Pushing the button, Frank."]});import Lt,{useState as _u}from"react";import{Box as zo,Text as fn,useInput as Nu}from"ink";function Ji({prompts:e,onSelect:o,onClose:t}){let[n,s]=_u(0);Nu((m,c)=>{c.escape&&t(),c.upArrow&&s(a=>Math.max(0,a-1)),c.downArrow&&s(a=>Math.min(e.length-1,a+1)),c.return&&e[n]&&o(e[n].id)});let r=Oe(2),l=10,u=0;if(e.length>l){let m=Math.floor(l/2);u=n-m,u<0?u=0:u+l>e.length&&(u=e.length-l)}let f=e.slice(u,u+l);return Lt.createElement(zo,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",padding:0,width:"100%"},Lt.createElement(zo,{paddingX:1,marginBottom:1},Lt.createElement(fn,{color:"cyan",bold:!0},"\u{1F504} CODEBASE TIME TRAVEL: SELECT UNDO POINT")),Lt.createElement(zo,{paddingX:2,marginBottom:1},Lt.createElement(fn,null,"Select a prompt to revert the codebase back to the state ",Lt.createElement(fn,{bold:!0,color:"blue"},"immediately before")," it was executed:")),e.length===0?Lt.createElement(zo,{paddingX:2,paddingY:1},Lt.createElement(fn,{italic:!0,color:"gray"},"No prompt checkpoints found for this session.")):Lt.createElement(zo,{flexDirection:"column",width:"100%"},u>0&&Lt.createElement(zo,{paddingX:2,marginBottom:1},Lt.createElement(fn,{color:"gray",dimColor:!0},"\u25B2 (+",u," more prompts above)")),f.map((m,c)=>{let d=u+c===n,p=Uu(m.timestamp),h=m.changes?m.changes.length:0;return Lt.createElement(zo,{key:m.id,paddingX:1,backgroundColor:d?"#1a2a3a":void 0,width:"100%"},Lt.createElement(zo,{flexGrow:1},Lt.createElement(fn,{color:d?"cyan":"white",bold:d},d?"\u276F ":" ",'"',Bu(m.prompt),'"',Lt.createElement(fn,{color:"gray",dimColor:!d}," [",p," \u2022 ",h," file(s) changed]"))))}),u+l<e.length&&Lt.createElement(zo,{paddingX:2,marginTop:1},Lt.createElement(fn,{color:"gray",dimColor:!0},"\u25BC (+",e.length-(u+l)," more prompts below)"))),Lt.createElement(zo,{marginTop:1,paddingX:1,borderStyle:"single",borderLeft:!1,borderRight:!1,borderBottom:!1,borderColor:"cyan"},Lt.createElement(fn,{dimColor:!0,italic:!0},"\u2191\u2193 navigate \u2022 Enter select undo point \u2022 Esc close")))}function Bu(e){if(!e)return"";let t=(e.split(`
537
537
  `)[0]||"").replace(/@\[(.*?)\]/g,(n,s)=>{let r=s.replace(/\\/g,"/").split("/");return`[${r[r.length-1]}]`});return t.length>69?t.slice(0,67)+"...":e.includes(`
538
- `)?t+"...":t}function Nu(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=l=>String(l).padStart(2,"0"),n=t(o.getHours()),s=t(o.getMinutes()),r=t(o.getSeconds());return`${n}:${s}:${r}`}var zl=re(()=>{rn()});import Bu from"puppeteer";import{exec as Uu}from"child_process";import{promisify as Ru}from"util";import Wu from"fs";var Jl,Ql,Zl,ec=re(()=>{Jl=Ru(Uu),Ql=()=>{try{let e=Bu.executablePath();if(e&&Wu.existsSync(e))return!0}catch{return!1}return!1},Zl=async e=>{e&&e("\u{1F4E5} Downloading Chromium engine (chrome@148)...");try{try{await Jl("pnpm exec puppeteer browsers install chrome@148")}catch{await Jl("npx -y puppeteer browsers install chrome@148")}return await new Promise(o=>setTimeout(o,1e3)),{success:!0}}catch(o){return console.error("[SETUP ERROR]",o),{success:!1,error:o.message}}}});var cc={};qr(cc,{default:()=>lc});import tc from"os";import i,{useState as V,useEffect as io,useRef as Zo,useMemo as Ur}from"react";import{Box as k,Text as y,useInput as Yu,useStdout as ju}from"ink";import ao from"fs-extra";import Kn from"path";import{exec as Ji}from"child_process";import{fileURLToPath as Gu}from"url";import oc from"ink-text-input";import sc from"gradient-string";function lc({args:e=[]}){let[o,t]=V(!1),[n,s]=V(10),{stdout:r}=ju(),[l,u]=V(""),[f,m]=V(0),[c,a]=V(!1),[d,p]=V("Flux"),[h,S]=V({columns:r?.columns||80,rows:r?.rows||24}),[T,w]=V(0),[I,L]=V(!1),[_,R]=V(!1),[v,b]=V(0),A=Zo(null);io(()=>{let x=Ms(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL,O=setTimeout(()=>{g&&!Vo()&&R(!0)},500),N=setInterval(()=>{Vo()&&R(!1)},1e3);return()=>{clearTimeout(O),clearInterval(N)}},[]);let F=Ur(()=>{let x={};for(let g=0;g<e.length;g++)if(e[g]==="--key"&&e[g+1]){let N=e[g+1];if(x.key=N,N.includes("@")){let M=N.split("@"),$=M[0],U=M[1].toLowerCase();if(["google","deepseek","openrouter"].includes(U)){let E="Google";U==="google"?E="Google":U==="deepseek"?E="DeepSeek":U==="openrouter"&&(E="OpenRouter"),x.key=$,x.provider=E}}}for(let g=0;g<e.length;g++){let O=e[g];if(O==="--key"){g++;continue}if(O==="--model"&&e[g+1])x.model=e[g+1],g++;else if(O==="--memory"&&e[g+1])x.memory=e[g+1].toLowerCase(),g++;else if(O==="--resume"&&e[g+1])x.resume=e[g+1],g++;else if(O==="--package"&&e[g+1]){let N=e[g+1].toLowerCase();["npm","pnpm","yarn","bun"].includes(N)&&(x.package=N),g++}else if(O==="--auto-del"&&e[g+1]){let N=e[g+1].toLowerCase();["1d","7d","30d"].includes(N)&&(x.autoDel=N),g++}else if(O==="--auto-exec"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(O==="--yolo"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(O==="--external-access"&&e[g+1])x.externalAccess=e[g+1].toLowerCase(),g++;else if(O==="--mode"&&e[g+1]){let M=e[g+1].toLowerCase();if(["flux","flow"].includes(M)){let $="Flux";M==="flux"?$="Flux":M==="flow"&&($="Flow"),x.mode=$}g++}else if(O==="--thinking"&&e[g+1]){let M=e[g+1].toLowerCase();if(["fast","low","medium","high","xhigh","standard"].includes(M)){let $="Medium";M==="fast"?$="Fast":M==="low"?$="Low":M==="standard"?$="Standard":M==="medium"?$="Medium":M==="high"?$="High":M==="xhigh"&&($="xHigh"),x.thinking=$}g++}else if(O==="--provider"&&e[g+1]){let N=e[g+1].toLowerCase();if(["google","deepseek","openrouter"].includes(N)){let M="Google";N==="google"?M="Google":N==="deepseek"?M="DeepSeek":N==="openrouter"&&(M="OpenRouter"),x.provider=M}g++}}return x},[e]),Q=async(x=!1,g=null)=>{let O=g||Yt;x&&W(N=>(ee(N.length+1),[...N,{id:"check-"+Date.now(),role:"system",text:"\u{1F50D} Checking for updates...",isMeta:!0}]));try{let M=await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json(),$=M["dist-tags"]?.latest,U=M["dist-tags"]?.stable;if($&&Je($),$&&$!==Pn){let E=$===U?`v${$}-stable`:`v${$}`;!x&&O.autoUpdate?H("update"):W(D=>{let P=[...D],G=x?P.length:Math.min(P.length,3);return P.splice(G,0,{id:"update-"+Date.now(),role:"system",text:`A new version (${E}) is here.
538
+ `)?t+"...":t}function Uu(e){if(!e)return"N/A";let o=new Date(e);if(isNaN(o.getTime()))return"N/A";let t=l=>String(l).padStart(2,"0"),n=t(o.getHours()),s=t(o.getMinutes()),r=t(o.getSeconds());return`${n}:${s}:${r}`}var Jl=re(()=>{rn()});import Ru from"puppeteer";import{exec as Wu}from"child_process";import{promisify as Yu}from"util";import ju from"fs";var Ql,Zl,ec,tc=re(()=>{Ql=Yu(Wu),Zl=()=>{try{let e=Ru.executablePath();if(e&&ju.existsSync(e))return!0}catch{return!1}return!1},ec=async e=>{e&&e("\u{1F4E5} Downloading Chromium engine (chrome@148)...");try{try{await Ql("pnpm exec puppeteer browsers install chrome@148")}catch{await Ql("npx -y puppeteer browsers install chrome@148")}return await new Promise(o=>setTimeout(o,1e3)),{success:!0}}catch(o){return console.error("[SETUP ERROR]",o),{success:!1,error:o.message}}}});var uc={};Xr(uc,{default:()=>cc});import oc from"os";import i,{useState as z,useEffect as io,useRef as Jo,useMemo as Ur}from"react";import{Box as k,Text as y,useInput as Gu,useStdout as Hu}from"ink";import ao from"fs-extra";import Xn from"path";import{exec as Qi}from"child_process";import{fileURLToPath as Xu}from"url";import nc from"ink-text-input";import ic from"gradient-string";function cc({args:e=[]}){let[o,t]=z(!1),[n,s]=z(10),{stdout:r}=Hu(),[l,u]=z(""),[f,m]=z(0),[c,a]=z(!1),[d,p]=z("Flux"),[h,E]=z({columns:r?.columns||80,rows:r?.rows||24}),[w,T]=z(0),[I,O]=z(!1),[P,U]=z(!1),[A,S]=z(0),v=Jo(null);io(()=>{let x=ks(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL,D=setTimeout(()=>{g&&!Ko()&&U(!0)},500),_=setInterval(()=>{Ko()&&U(!1)},1e3);return()=>{clearTimeout(D),clearInterval(_)}},[]);let F=Ur(()=>{let x={};for(let g=0;g<e.length;g++)if(e[g]==="--key"&&e[g+1]){let _=e[g+1];if(x.key=_,_.includes("@")){let M=_.split("@"),$=M[0],R=M[1].toLowerCase();if(["google","deepseek","openrouter","nvidia"].includes(R)){let C="Google";R==="google"?C="Google":R==="deepseek"?C="DeepSeek":R==="openrouter"?C="OpenRouter":R==="nvidia"&&(C="NVIDIA"),x.key=$,x.provider=C}}}for(let g=0;g<e.length;g++){let D=e[g];if(D==="--key"){g++;continue}if(D==="--model"&&e[g+1])x.model=e[g+1],g++;else if(D==="--memory"&&e[g+1])x.memory=e[g+1].toLowerCase(),g++;else if(D==="--resume"&&e[g+1])x.resume=e[g+1],g++;else if(D==="--package"&&e[g+1]){let _=e[g+1].toLowerCase();["npm","pnpm","yarn","bun"].includes(_)&&(x.package=_),g++}else if(D==="--auto-del"&&e[g+1]){let _=e[g+1].toLowerCase();["1d","7d","30d"].includes(_)&&(x.autoDel=_),g++}else if(D==="--auto-exec"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(D==="--yolo"&&e[g+1])x.autoExec=e[g+1].toLowerCase(),g++;else if(D==="--external-access"&&e[g+1])x.externalAccess=e[g+1].toLowerCase(),g++;else if(D==="--mode"&&e[g+1]){let M=e[g+1].toLowerCase();if(["flux","flow"].includes(M)){let $="Flux";M==="flux"?$="Flux":M==="flow"&&($="Flow"),x.mode=$}g++}else if(D==="--thinking"&&e[g+1]){let M=e[g+1].toLowerCase();if(["fast","low","medium","high","xhigh","standard"].includes(M)){let $="Medium";M==="fast"?$="Fast":M==="low"?$="Low":M==="standard"?$="Standard":M==="medium"?$="Medium":M==="high"?$="High":M==="xhigh"&&($="xHigh"),x.thinking=$}g++}else if(D==="--provider"&&e[g+1]){let _=e[g+1].toLowerCase();if(["google","deepseek","openrouter","nvidia"].includes(_)){let M="Google";_==="google"?M="Google":_==="deepseek"?M="DeepSeek":_==="openrouter"?M="OpenRouter":_==="nvidia"&&(M="NVIDIA"),x.provider=M}g++}}return x},[e]),V=async(x=!1,g=null)=>{let D=g||Ht;x&&W(_=>(te(_.length+1),[..._,{id:"check-"+Date.now(),role:"system",text:"\u{1F50D} Checking for updates...",isMeta:!0}]));try{let M=await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json(),$=M["dist-tags"]?.latest,R=M["dist-tags"]?.stable;if($&&qe($),$&&$!==Dn){let C=$===R?`v${$}-stable`:`v${$}`;!x&&D.autoUpdate?X("update"):W(L=>{let B=[...L],j=x?B.length:Math.min(B.length,3);return B.splice(j,0,{id:"update-"+Date.now(),role:"system",text:`A new version (${C}) is here.
539
539
 
540
540
  \u2022 Type \`/update latest\` to apply the update.
541
- \u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),P})}else x&&W(E=>{ee(E.length+1);let D=$&&$===U?`${Pn}-stable`:Pn;return[...E,{id:"uptodate-"+Date.now(),role:"system",text:`\u2705 [SYSTEM] Flux Flow is already up to date (${D}).`,isMeta:!0}]})}catch(N){x&&W(M=>(ee(M.length+1),[...M,{id:"check-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to check for updates: ${N.message}`,isMeta:!0}]))}};io(()=>{let x=()=>{r.write("\x1B[2J\x1B[3J\x1B[H"),S({columns:r.columns,rows:r.rows})};return r.on("resize",x),()=>{r.off("resize",x)}},[r]);let[j,Z]=V("Medium"),[B,z]=V("Google"),[mt,ce]=V(0),[Le,Je]=V(null),[ue,tt]=V(!1),[Ye,_e]=V("gemma-4-31b-it"),[Me,je]=V("gemma-4-26b-a4b-it"),[ye,ft]=V(!0),[pt,lo]=V(!0),Wt=Zo(0),[be,rt]=V(null),[Ao,co]=V(""),[Vt,H]=V("chat"),[Ge,Rr]=V("Free"),[zt,qn]=V({agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0}),[ht,Oo]=V(null),[Yt,te]=V({memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:""}),[ve,st]=V({name:null,nickname:null,instructions:null}),[de,he]=V({keyType:"Default",quality:"Low-High",apiKey:""}),[fe,it]=V({tokens:0}),[Bo,St]=V(0),[gt,Ne]=V(0),[ae,jt]=V(0),[at,go]=V(0),[xt,pn]=V(0),[ot,lt]=V(0),[Gt,Jt]=V(0),[en,vs]=V(0),[hr,gr]=V(0),[Vn,Zi]=V(0),[xr,As]=V(0),[_n,Os]=V(0),[se,Be]=V(null),[Ue,ct]=V(oi()),[Et,nt]=V(null),[Qt,xo]=V(""),[Zt,Lt]=V(!1),[uo,ko]=V(0),Nn=Zo(!0),Ds=Zo(!0),Wr=Zo(!0);io(()=>{if(!be)return;if(Nn.current){Nn.current=!1,setTimeout(()=>{Ds.current=!1,setTimeout(()=>{Wr.current=!1},1e3)},2e3);return}if(Ds.current||Wr.current)return;let x=Ie(2),g="",O="";Ge==="Free"?B==="Google"?(g="gemma-4-31b-it",O="Gemma 4 (Free default)"):B==="DeepSeek"?(g="deepseek-v4-flash",O="DeepSeek Flash (Free default)"):(g="google/gemma-4-31b-it:free",O="Gemma 4 (Free default)"):B==="Google"?(g="gemini-3-flash-preview",O="Gemini 3 Flash"):B==="DeepSeek"?(g="deepseek-v4-flash",O="DeepSeek Flash"):(g="deepseek/deepseek-v4-flash",O="DeepSeek Flash"),_e(g),Cn({apiTier:Ge,activeModel:g}),W(N=>(ee(N.length+1),[...N,{id:"tier-switch-"+Date.now(),role:"system",text:`\u26A0\uFE0F${x}**[TIER LIMIT]** Auto-switched to ${O}.`,isMeta:!0}]))},[Ge,B,be]);let Ls=Ur(()=>{let x=Ms(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL||!!process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS;return{isIDE:g,shortcut:g?"Shift + Enter":"Ctrl + Enter"}},[]),Se=Zo(null),Qe=Zo("");io(()=>{Se.current=Et},[Et]),io(()=>{Qe.current=Qt},[Qt]);let[yo,Re]=V(!1),[Ft,Uo]=V(null),[hn,yr]=V(null),tn=x=>{Uo(null),H("chat")},Yr=x=>{let g=Math.floor(x/3600),O=Math.floor(x%3600/60),N=x%60,M=[];return g>0&&M.push(`${g}h`),(O>0||g>0)&&M.push(`${O}m`),M.push(`${N}s`),M.join(" ")},Ro=x=>x<1e3?`${x}ms`:Yr(Math.floor(x/1e3)),[zn,Jn]=V(null),[wr,Tr]=V("");io(()=>{let x;if(zn){let g=()=>{let O=Vi[Math.floor(Math.random()*Vi.length)];Tr(O)};wr||g(),x=setInterval(g,5e3)}else Tr("");return()=>clearInterval(x)},[zn]);let[Sr,Qn]=V(!0),[gn,jr]=V(!1),[Wo,xn]=V(!1),[Zn,Gr]=V(null),[J,He]=V(0),[yt,K]=V([]),qe=Zo(null),[eo,Fe]=V(null),[Yo,on]=V(null),[Bn,bt]=V(null);io(()=>He(0),[l]);let[$t,W]=V(()=>{let x={id:"logo-"+Date.now(),role:"system",text:pr,isLogo:!0,isMeta:!0},g={id:"welcome",role:"system",text:"\u{1F30A}\u26A1 Welcome to Flux Flow! Type /help for commands.",isMeta:!0},O=process.cwd()===tc.homedir(),N=(()=>{let $=process.cwd().toLowerCase();if(process.platform==="win32"){let U=process.env.SystemRoot?.toLowerCase()||"c:\\windows",E=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",D=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return $.startsWith(U)||$.startsWith(E)||$.startsWith(D)}else return $==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(E=>$.startsWith(E))})(),M=[x,g];return N?M.push({id:"system-warning",role:"system",text:"\u{1F6D1} [CRITICAL SECURITY ALERT] SYSTEM DIRECTORY DETECTED",subText:`You are currently in a PROTECTED SYSTEM DIRECTORY (${process.cwd()}). Operating here is EXTREMELY dangerous as the agent could accidentally corrupt your OS or installed applications. PLEASE MOVE TO A PROJECT FOLDER FOR SAFETY.`,isHomeWarning:!0,isMeta:!0}):O&&M.push({id:"home-warning",role:"system",text:"[SECURITY ALERT] HOME DIRECTORY DETECTED",subText:`You are currently in ${tc.homedir()}. Working here is high-risk as the agent may modify system-sensitive configurations. Please move to a project folder for safety.`,isHomeWarning:!0,isMeta:!0}),M}),Do=Zo(null),[Fs,ee]=V($t.length),Hr=Ur(()=>{let g=h.columns||80,O=0,N=0;for(let M=$t.length-1;M>=0;M--){let $=$t[M];if(!$)continue;let U=$.text||"",E=U.split(/\r?\n/).length;if(U.split(/\r?\n/).forEach(D=>{E+=Math.floor(D.length/g)}),$.isHelpRecord&&(E=15),$.isUpdateNotification&&(E=8),$.isTerminalRecord&&(E=10),E+=$.role==="think"?3:2,O+E>2e3){N=M+1;break}O+=E}return{items:$t.slice(N,Fs),isTruncated:N>0}},[$t,h.columns,h.rows]),ie=Ur(()=>{if(!Et||!Qt)return!1;let x=Qt.trim();return x.endsWith("?")||x.endsWith(":")||/\[[yYnN/]+\]\s*$/.test(x)||/\([yYnN]\)\s*$/.test(x)},[Et,Qt]);Yu((x,g)=>{if(!(x==="\x1B[I"||x==="\x1B[O"||x==="[I"||x==="[O")){if(_){let O=Ms(),N=ic(O);if(g.upArrow)b(M=>M>0?M-1:N.length-1);else if(g.downArrow)b(M=>M<N.length-1?M+1:0);else if(g.return){let M=N[v];if(M.action==="dismiss")R(!1);else if(M.url){let $=process.platform==="win32"?`start ${M.url}`:process.platform==="darwin"?`open ${M.url}`:`xdg-open ${M.url}`;Ji($),R(!1)}}return}if(g.tab&&Et){Lt(O=>!O);return}if(Zt&&Et){if(g.return){let O=process.platform==="win32";Mo(O?`\r
541
+ \u2022 Type \`/changelog\` to view the release notes.`,isUpdateNotification:!0,isMeta:!0}),B})}else x&&W(C=>{te(C.length+1);let L=$&&$===R?`${Dn}-stable`:Dn;return[...C,{id:"uptodate-"+Date.now(),role:"system",text:`\u2705 [SYSTEM] Flux Flow is already up to date (${L}).`,isMeta:!0}]})}catch(_){x&&W(M=>(te(M.length+1),[...M,{id:"check-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to check for updates: ${_.message}`,isMeta:!0}]))}};io(()=>{let x=()=>{r.write("\x1B[2J\x1B[3J\x1B[H"),E({columns:r.columns,rows:r.rows})};return r.on("resize",x),()=>{r.off("resize",x)}},[r]);let[Y,Z]=z("Medium"),[N,J]=z("Google"),[ft,de]=z(0),[$e,qe]=z(null),[me,Ze]=z(!1),[je,Be]=z("gemma-4-31b-it"),[Le,Ge]=z("gemma-4-26b-a4b-it"),[Se,pt]=z(!0),[ht,lo]=z(!0),Nt=Jo(0),[be,ze]=z(null),[Mo,co]=z(""),[Qt,X]=z("chat"),[He,Rr]=z("Free"),[Zt,Kn]=z({agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0}),[gt,vo]=z(null),[Ht,ee]=z({memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:""}),[ve,nt]=z({name:null,nickname:null,instructions:null}),[fe,ge]=z({keyType:"Default",quality:"Low-High",apiKey:""}),[he,rt]=z({tokens:0}),[Bo,Et]=z(0),[xt,Ue]=z(0),[ae,Bt]=z(0),[st,go]=z(0),[yt,pn]=z(0),[et,it]=z(0),[Xt,Kt]=z(0),[Uo,Is]=z(0),[mr,fr]=z(0),[Vn,ea]=z(0),[pr,As]=z(0),[On,Ms]=z(0),[se,Re]=z(null),[We,at]=z(ti()),[wt,tt]=z(null),[eo,Ro]=z(""),[It,Ut]=z(!1),[uo,Wo]=z(0),Qo=Jo(!0),Wr=Jo(!0),vs=Jo(!0);io(()=>{if(!be)return;if(Qo.current){Qo.current=!1,setTimeout(()=>{Wr.current=!1,setTimeout(()=>{vs.current=!1},1e3)},2e3);return}if(Wr.current||vs.current)return;let x=Oe(2),g="",D="";He==="Free"?N==="Google"?(g="gemma-4-31b-it",D="Gemma 4 (Free default)"):N==="DeepSeek"?(g="deepseek-v4-flash",D="DeepSeek Flash (Free default)"):N==="NVIDIA"?(g="moonshotai/kimi-k2.6",D="Moonshot Kimi (NVIDIA)"):(g="google/gemma-4-31b-it:free",D="Gemma 4 (Free default)"):N==="Google"?(g="gemini-3-flash-preview",D="Gemini 3 Flash"):N==="DeepSeek"?(g="deepseek-v4-flash",D="DeepSeek Flash"):N==="NVIDIA"?(g="moonshotai/kimi-k2.6",D="Moonshot Kimi (NVIDIA)"):(g="deepseek/deepseek-v4-flash",D="DeepSeek Flash"),Be(g),wn({apiTier:He,activeModel:g}),W(_=>(te(_.length+1),[..._,{id:"tier-switch-"+Date.now(),role:"system",text:`\u26A0\uFE0F${x}**[TIER LIMIT]** Auto-switched to ${D}.`,isMeta:!0}]))},[He,N,be]);let Ds=Ur(()=>{let x=ks(),g=!["Terminal","Windows Terminal"].includes(x)||!!process.env.VSC_TERMINAL_URL||!!process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS;return{isIDE:g,shortcut:g?"Shift + Enter":"Ctrl + Enter"}},[]),hr=Jo(null),Ce=Jo("");io(()=>{hr.current=wt},[wt]),io(()=>{Ce.current=eo},[eo]);let[ot,xo]=z(!1),[Pe,Rt]=z(null),[Zo,qn]=z(null),Ln=x=>{Rt(null),X("chat")},Fn=x=>{let g=Math.floor(x/3600),D=Math.floor(x%3600/60),_=x%60,M=[];return g>0&&M.push(`${g}h`),(D>0||g>0)&&M.push(`${D}m`),M.push(`${_}s`),M.join(" ")},en=x=>x<1e3?`${x}ms`:Fn(Math.floor(x/1e3)),[$n,gr]=z(null),[zn,Yr]=z("");io(()=>{let x;if($n){let g=()=>{let D=zi[Math.floor(Math.random()*zi.length)];Yr(D)};zn||g(),x=setInterval(g,1e4)}else Yr("");return()=>clearInterval(x)},[$n]);let[Pn,ta]=z(!0),[Do,xr]=z(!1),[Os,Oo]=z(!1),[tn,Ls]=z(null),[yr,Q]=z(0),[lt,ct]=z([]),G=Jo(null),[bt,Ft]=z(null),[_e,bo]=z(null),[_n,Nn]=z(null);io(()=>Q(0),[l]);let[Fe,W]=z(()=>{let x={id:"logo-"+Date.now(),role:"system",text:dr,isLogo:!0,isMeta:!0},g={id:"welcome",role:"system",text:"\u{1F30A}\u26A1 Welcome to Flux Flow! Type /help for commands.",isMeta:!0},D=process.cwd()===oc.homedir(),_=(()=>{let $=process.cwd().toLowerCase();if(process.platform==="win32"){let R=process.env.SystemRoot?.toLowerCase()||"c:\\windows",C=process.env.ProgramFiles?.toLowerCase()||"c:\\program files",L=process.env["ProgramFiles(x86)"]?.toLowerCase()||"c:\\program files (x86)";return $.startsWith(R)||$.startsWith(C)||$.startsWith(L)}else return $==="/"||["/bin","/sbin","/etc","/usr","/var","/root"].some(C=>$.startsWith(C))})(),M=[x,g];return _?M.push({id:"system-warning",role:"system",text:"\u{1F6D1} [CRITICAL SECURITY ALERT] SYSTEM DIRECTORY DETECTED",subText:`You are currently in a PROTECTED SYSTEM DIRECTORY (${process.cwd()}). Operating here is EXTREMELY dangerous as the agent could accidentally corrupt your OS or installed applications. PLEASE MOVE TO A PROJECT FOLDER FOR SAFETY.`,isHomeWarning:!0,isMeta:!0}):D&&M.push({id:"home-warning",role:"system",text:"[SECURITY ALERT] HOME DIRECTORY DETECTED",subText:`You are currently in ${oc.homedir()}. Working here is high-risk as the agent may modify system-sensitive configurations. Please move to a project folder for safety.`,isHomeWarning:!0,isMeta:!0}),M}),Co=Jo(null),[wr,te]=z(Fe.length),jr=Ur(()=>{let g=h.columns||80,D=0,_=0;for(let M=Fe.length-1;M>=0;M--){let $=Fe[M];if(!$)continue;let R=$.text||"",C=R.split(/\r?\n/).length;if(R.split(/\r?\n/).forEach(L=>{C+=Math.floor(L.length/g)}),$.isHelpRecord&&(C=15),$.isUpdateNotification&&(C=8),$.isTerminalRecord&&(C=10),C+=$.role==="think"?3:2,D+C>2e3){_=M+1;break}D+=C}return{items:Fe.slice(_,wr),isTruncated:_>0}},[Fe,h.columns,h.rows]),Gr=Ur(()=>{if(!wt||!eo)return!1;let x=eo.trim();return x.endsWith("?")||x.endsWith(":")||/\[[yYnN/]+\]\s*$/.test(x)||/\([yYnN]\)\s*$/.test(x)},[wt,eo]);Gu((x,g)=>{if(!(x==="\x1B[I"||x==="\x1B[O"||x==="[I"||x==="[O")){if(P){let D=ks(),_=ac(D);if(g.upArrow)S(M=>M>0?M-1:_.length-1);else if(g.downArrow)S(M=>M<_.length-1?M+1:0);else if(g.return){let M=_[A];if(M.action==="dismiss")U(!1);else if(M.url){let $=process.platform==="win32"?`start ${M.url}`:process.platform==="darwin"?`open ${M.url}`:`xdg-open ${M.url}`;Qi($),U(!1)}}return}if(g.tab&&wt){Ut(D=>!D);return}if(It&&wt){if(g.return){let D=process.platform==="win32";Io(D?`\r
542
542
  `:`
543
- `),$o||xo(N=>N+`
544
- `)}else if(g.backspace||g.delete)$o?Mo("\x7F"):(Mo("\b \b"),xo(O=>O.slice(0,-1)));else if(g.upArrow)Mo(g.shift?"\x1B[1;2A":"\x1B[A");else if(g.downArrow)Mo(g.shift?"\x1B[1;2B":"\x1B[B");else if(g.rightArrow)Mo(g.shift?"\x1B[1;2C":"\x1B[C");else if(g.leftArrow)Mo(g.shift?"\x1B[1;2D":"\x1B[D");else if(g.escape)Mo("\x1B");else if(g.ctrl&&x){let O=x.toLowerCase().charCodeAt(0);O>=97&&O<=122?Mo(String.fromCharCode(O-96)):Mo(x)}else x&&(Mo(x),$o||xo(O=>O+x));return}if(g.escape){if(Ce.length>0&&Vt==="chat"){L(!0);return}if(o){t(!1);return}if(gn||Et)Wo?($l(),ba(),xn(!1),Zn&&clearTimeout(Zn)):(xn(!0),Zn&&clearTimeout(Zn),Gr(setTimeout(()=>xn(!1),3e3)));else if(Vt==="revert")H("chat"),He(0);else if(Vt!=="chat"&&Vt!=="settings")H("chat");else{if(!be&&mt===1){ce(0),co("");return}He(O=>{let N=O+1;return N===1?(qe.current&&clearTimeout(qe.current),qe.current=setTimeout(()=>He(0),2e3)):N===2&&(qe.current&&clearTimeout(qe.current),He(0),l.length>0?u(""):kt.getChatHistory(Ue).then(M=>{M.length>0?(K(M.reverse()),H("revert")):W($=>(ee($.length+1),[...$,{id:"revert-empty-"+Date.now(),role:"system",text:"\u{1F6C8} No revert checkpoints found for this session.",isMeta:!0}]))})),N})}}if(Ce.length>0&&Vt==="chat"){if(g.upArrow){w(O=>O>0?O-1:Ce.length-1);return}if(g.downArrow){w(O=>O<Ce.length-1?O+1:0);return}if(g.return)return}if(g.tab,g.ctrl&&x==="c"&&Vt!=="exit"){if(l.length>0){u("");return}if(g.shift){H("exit"),t(!1);return}o?(H("exit"),t(!1)):t(!0)}g.return&&(g.shift||g.ctrl||g.meta||g.leftAlt||g.rightAlt)&&u(O=>O.replace(/\\\r?$/,"").replace(/\r?$/,"")+`
545
- `)}}),io(()=>{process.stdout.write("\x1B[?1004h");let x=g=>{let O=g.toString();O.includes("\x1B[I")?(lo(!0),Wt.current=Date.now()):O.includes("\x1B[O")&&(lo(!1),Wt.current=Date.now())};return process.stdin.on("data",x),()=>{process.stdout.write("\x1B[?1004l"),process.stdin.off("data",x)}},[]),io(()=>{async function x(){try{let U=JSON.parse(ao.readFileSync(Kn.join(process.cwd(),"package.json"),"utf8"));Fi(Pn||U.version||"2.0.0")}catch{Fi("2.0.0")}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),Ql()||(W(U=>(ee(U.length+1),[...U,{id:"setup-"+Date.now(),role:"system",text:"\u{1F527} [SYSTEM] Installing Required dependencies... (One-time setup)",isMeta:!0}])),await Zl(),W(U=>(ee(U.length+1),[...U,{id:"setup-done-"+Date.now(),role:"system",text:"\u2705 [SYSTEM] All dependencies installed successfully.",isMeta:!0}])));let g=await or();F.mode?p(F.mode):p(g.mode),F.thinking?Z(F.thinking):Z(g.thinkingLevel);let O=F.provider||g.aiProvider||"Google";z(O);let N=g.apiTier||"Free";if(A.current=g.activeModel,F.model)_e(F.model);else if(F.provider){let U="";N==="Free"?O==="Google"?U="gemma-4-31b-it":O==="DeepSeek"?U="deepseek-v4-flash":U="google/gemma-4-31b-it:free":O==="Google"?U="gemini-3-flash-preview":O==="DeepSeek"?U="deepseek-v4-flash":U="deepseek/deepseek-v4-flash",_e(U)}else _e(g.activeModel);tt(g.showFullThinking),Rr(g.apiTier||"Free"),qn(g.quotas||{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0});let M={memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:"",...g.systemSettings||{}};F.memory==="on"?M.memory=!0:F.memory==="off"&&(M.memory=!1),F.package&&(M.updateManager=F.package),F.autoDel&&(M.autoDeleteHistory=F.autoDel),F.autoExec==="on"?M.autoExec=!0:F.autoExec==="off"&&(M.autoExec=!1),F.externalAccess==="on"?M.allowExternalAccess=!0:F.externalAccess==="off"&&(M.allowExternalAccess=!1),te(M),st(g.profileData),he(g.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""});let $=F.key;if($||($=await Zr(O)),$&&(rt($),Br($,{aiProvider:O,onIDEApproval:tn})),g.systemSettings?.autoDeleteHistory&&Ua(g.systemSettings.autoDeleteHistory),Ra(Io),Q(!1,M),await Ga(),F.resume){let U=await _o(),E=F.resume;if(U[E]){ct(E);let D=[...U[E].messages];D[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||D.unshift({id:"welcome-"+Date.now(),role:"system",text:pr+`
543
+ `),$o||Ro(_=>_+`
544
+ `)}else if(g.backspace||g.delete)$o?Io("\x7F"):(Io("\b \b"),Ro(D=>D.slice(0,-1)));else if(g.upArrow)Io(g.shift?"\x1B[1;2A":"\x1B[A");else if(g.downArrow)Io(g.shift?"\x1B[1;2B":"\x1B[B");else if(g.rightArrow)Io(g.shift?"\x1B[1;2C":"\x1B[C");else if(g.leftArrow)Io(g.shift?"\x1B[1;2D":"\x1B[D");else if(g.escape)Io("\x1B");else if(g.ctrl&&x){let D=x.toLowerCase().charCodeAt(0);D>=97&&D<=122?Io(String.fromCharCode(D-96)):Io(x)}else x&&(Io(x),$o||Ro(D=>D+x));return}if(g.escape){if(Ae.length>0&&Qt==="chat"){O(!0);return}if(o){t(!1);return}if(Do||wt)Os?(Pl(),ka(),Oo(!1),tn&&clearTimeout(tn)):(Oo(!0),tn&&clearTimeout(tn),Ls(setTimeout(()=>Oo(!1),3e3)));else if(Qt==="revert")X("chat"),Q(0);else if(Qt!=="chat"&&Qt!=="settings")X("chat");else{if(!be&&ft===1){de(0),co("");return}Q(D=>{let _=D+1;return _===1?(G.current&&clearTimeout(G.current),G.current=setTimeout(()=>Q(0),2e3)):_===2&&(G.current&&clearTimeout(G.current),Q(0),l.length>0?u(""):kt.getChatHistory(We).then(M=>{M.length>0?(ct(M.reverse()),X("revert")):W($=>(te($.length+1),[...$,{id:"revert-empty-"+Date.now(),role:"system",text:"\u{1F6C8} No revert checkpoints found for this session.",isMeta:!0}]))})),_})}}if(Ae.length>0&&Qt==="chat"){if(g.upArrow){T(D=>D>0?D-1:Ae.length-1);return}if(g.downArrow){T(D=>D<Ae.length-1?D+1:0);return}if(g.return)return}if(g.tab,g.ctrl&&x==="c"&&Qt!=="exit"){if(l.length>0){u("");return}if(g.shift){X("exit"),t(!1);return}o?(X("exit"),t(!1)):t(!0)}g.return&&(g.shift||g.ctrl||g.meta||g.leftAlt||g.rightAlt)&&u(D=>D.replace(/\\\r?$/,"").replace(/\r?$/,"")+`
545
+ `)}}),io(()=>{process.stdout.write("\x1B[?1004h");let x=g=>{let D=g.toString();D.includes("\x1B[I")?(lo(!0),Nt.current=Date.now()):D.includes("\x1B[O")&&(lo(!1),Nt.current=Date.now())};return process.stdin.on("data",x),()=>{process.stdout.write("\x1B[?1004l"),process.stdin.off("data",x)}},[]),io(()=>{async function x(){try{let R=JSON.parse(ao.readFileSync(Xn.join(process.cwd(),"package.json"),"utf8"));Li(Dn||R.version||"2.0.0")}catch{Li("2.0.0")}process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),Zl()||(W(R=>(te(R.length+1),[...R,{id:"setup-"+Date.now(),role:"system",text:"\u{1F527} [SYSTEM] Installing Required dependencies... (One-time setup)",isMeta:!0}])),await ec(),W(R=>(te(R.length+1),[...R,{id:"setup-done-"+Date.now(),role:"system",text:"\u2705 [SYSTEM] All dependencies installed successfully.",isMeta:!0}])));let g=await Zn();F.mode?p(F.mode):p(g.mode),F.thinking?Z(F.thinking):Z(g.thinkingLevel);let D=F.provider||g.aiProvider||"Google";J(D);let _=g.apiTier||"Free";if(v.current=g.activeModel,F.model)Be(F.model);else if(F.provider){let R="";_==="Free"?D==="Google"?R="gemma-4-31b-it":D==="DeepSeek"?R="deepseek-v4-flash":D==="OpenRouter"?R="google/gemma-4-31b-it:free":D==="NVIDIA"&&(R="moonshotai/kimi-k2.6"):D==="Google"?R="gemini-3-flash-preview":D==="DeepSeek"?R="deepseek-v4-flash":D==="OpenRouter"?R="deepseek/deepseek-v4-flash":D==="NVIDIA"&&(R="moonshotai/kimi-k2.6"),Be(R)}else Be(g.activeModel);Ze(g.showFullThinking),Rr(g.apiTier||"Free"),Kn(g.quotas||{agentLimit:999999,backgroundLimit:999999,searchLimit:100,customModelId:"",customLimit:0});let M={memory:!0,compression:0,autoExec:!1,autoDeleteHistory:"7d",autoUpdate:!1,updateManager:"npm",customUpdateCommand:"",...g.systemSettings||{}};F.memory==="on"?M.memory=!0:F.memory==="off"&&(M.memory=!1),F.package&&(M.updateManager=F.package),F.autoDel&&(M.autoDeleteHistory=F.autoDel),F.autoExec==="on"?M.autoExec=!0:F.autoExec==="off"&&(M.autoExec=!1),F.externalAccess==="on"?M.allowExternalAccess=!0:F.externalAccess==="off"&&(M.allowExternalAccess=!1),ee(M),nt(g.profileData),ge(g.imageSettings||{keyType:"Default",quality:"Low-High",apiKey:""});let $=F.key;if($||($=await Jr(D)),$&&(ze($),Br($,{aiProvider:D,onIDEApproval:Ln})),g.systemSettings?.autoDeleteHistory&&Wa(g.systemSettings.autoDeleteHistory),Ya(ko),V(!1,M),await Xa(),F.resume){let R=await _o(),C=F.resume;if(R[C]){at(C);let L=[...R[C].messages];L[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||L.unshift({id:"welcome-"+Date.now(),role:"system",text:dr+`
546
546
 
547
- \u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),W(D),H("chat"),W(G=>{let q=[...G,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED VIA CLI: [${E}]`,isMeta:!0}];return ee(q.length),q})}else W(D=>[...D,{id:"sys-err-"+Date.now(),role:"system",text:`\u274C ERROR: Chat session [${E}] not found. Started new session.`,isMeta:!0}])}ft(!1)}x()},[]),io(()=>{let x;return o&&(s(10),x=setInterval(()=>{s(g=>g<=1?(t(!1),0):g-1)},1e3)),()=>{x&&clearInterval(x)}},[o]),io(()=>{if(!ye){let x=F.model&&Ye===F.model?A.current:Ye;Cn({mode:d,thinkingLevel:j,aiProvider:B,activeModel:x||Ye,showFullThinking:ue,systemSettings:Yt,profileData:ve,imageSettings:de,apiTier:Ge})}},[d,j,B,Ye,ue,Yt,ve,de,ye,F,Ge]);let Ae=async x=>{let g=x.trim(),O=30;if(B==="OpenRouter"&&(O=10),B==="DeepSeek"&&(O=20),g.length>=O){await es(B,g),rt(g),Br(g,{aiProvider:B,onIDEApproval:tn});let N="gemma-4-31b-it";B==="OpenRouter"?N="google/gemma-4-31b-it:free":B==="DeepSeek"&&(N="deepseek-v4-flash"),_e(N),W(M=>[...M,{role:"system",text:`\u2705 ${B} API Key saved successfully! Model set to ${N}. Initialization complete.`,isMeta:!0}])}else W(N=>[...N,{role:"system",text:`\u274C INVALID KEY: ${B} API keys must be at least ${O} characters.`,isMeta:!0}]),co("")},Xe=Zo(Qi);io(()=>{if(Vt==="exit"){(async()=>{let O=Date.now(),N=Math.floor((O-Xe.current)/1e3);N>=1&&(await Co("duration",N),Xe.current+=N*1e3),await Ha()})();let g=setTimeout(()=>{process.exit(0)},1700);return()=>clearTimeout(g)}},[Vt]),io(()=>{let x=setInterval(async()=>{if(!ye){let g=Date.now(),O=Math.floor((g-Xe.current)/1e3);O>=1&&(await Co("duration",O),Xe.current+=O*1e3)}},1500);return()=>clearInterval(x)},[ye]);let Ve=[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase back to a checkpoint"},{cmd:"/gemini",desc:"Get a happy message from Gemini CLI"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat in a .txt file"},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/mode",desc:"Toggle Flux/Flow modes",subs:[{cmd:"flux",desc:"Enable Dev toolset"},{cmd:"flow",desc:"Enable Chat mode"}]},{cmd:"/thinking",desc:"Set AI reasoning depth",subs:B==="DeepSeek"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Standard",desc:"Standard Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:B==="OpenRouter"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:Ye&&Ye.toLowerCase().startsWith("gemini-3")?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"}]:[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]},{cmd:"/model",desc:"Switch Model for Agent",subs:B==="OpenRouter"?Ge==="Free"?[{cmd:"google/gemma-4-31b-it:free",desc:"Multimodal"},{cmd:"moonshotai/kimi-k2.6:free",desc:"Multimodal"},{cmd:"qwen/qwen3-coder:free",desc:""},{cmd:"z-ai/glm-4.5-air:free",desc:""}]:[{cmd:"google/gemini-3.5-flash",desc:"Multimodal"},{cmd:"qwen/qwen3.7-plus",desc:"Multimodal"},{cmd:"minimax/minimax-m3",desc:"Multimodal"},{cmd:"anthropic/claude-sonnet-4.5",desc:"Multimodal"},{cmd:"anthropic/claude-opus-4.6",desc:"Multimodal"},{cmd:"anthropic/claude-opus-4.8",desc:"Multimodal"},{cmd:"deepseek/deepseek-v4-pro",desc:""},{cmd:"deepseek/deepseek-v4-flash",desc:""},{cmd:"xiaomi/mimo-v2.5-pro",desc:""},{cmd:"z-ai/glm-5",desc:""},{cmd:"openai/gpt-5.2-codex",desc:"Multimodal"},{cmd:"openai/gpt-5.2-pro",desc:"Multimodal"},{cmd:"openai/gpt-5.5-pro",desc:"Multimodal"},{cmd:"moonshotai/kimi-k2.6",desc:"Multimodal"}]:B==="DeepSeek"?[{cmd:"deepseek-v4-flash",desc:"Fast & Efficient"},{cmd:"deepseek-v4-pro",desc:"High-Intelligence Reasoning"}]:Ge==="Free"?[{cmd:"gemma-4-26b-a4b-it",desc:"Standard & Faster"},{cmd:"gemma-4-31b-it",desc:"Standard Default"},{cmd:"gemini-2.5-flash",desc:"Fast & Reliable (Limited Free Quota)"},{cmd:"gemini-3-flash-preview",desc:"Fast & Lightweight (Limited Free Quota)"},{cmd:"gemini-3.5-flash",desc:"Flash Latest (Limited Free Quota) [Instability Issues]"}]:[{cmd:"gemini-2.5-flash",desc:"Fast & Reliable"},{cmd:"gemini-3.1-flash-lite",desc:"Ultra-Fast & Lite"},{cmd:"gemini-3-flash-preview",desc:"Default, Fast & Lightweight"},{cmd:"gemini-3.5-flash",desc:"Flash Latest [Instability Issues]"},{cmd:"gemini-3.1-pro-preview",desc:"Pro Reasoning"}]},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/reset",desc:"Wipe all project data"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/fluxflow",desc:"Project management",subs:[{cmd:"init",desc:"Create FluxFlow.md template"}]},{cmd:"/update",desc:"Check/Install updates",subs:[{cmd:"check",desc:"Check for new version"},{cmd:"latest",desc:"Install latest release"}]}],wt=async(x,g=!1)=>{if(!g&&Ce.length>0){let M=Ce[T]||Ce[0],$=x.split(" ");if($.length===1)u(M.cmd+" ");else{let U=$.slice(0,-1);u(U.join(" ")+" "+M.cmd+" ")}w(0),m(U=>U+1);return}let O=x.replace(/\r\n/g,`
547
+ \u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),W(L),X("chat"),W(j=>{let q=[...j,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED VIA CLI: [${C}]`,isMeta:!0}];return te(q.length),q})}else W(L=>[...L,{id:"sys-err-"+Date.now(),role:"system",text:`\u274C ERROR: Chat session [${C}] not found. Started new session.`,isMeta:!0}])}pt(!1)}x()},[]),io(()=>{let x;return o&&(s(10),x=setInterval(()=>{s(g=>g<=1?(t(!1),0):g-1)},1e3)),()=>{x&&clearInterval(x)}},[o]),io(()=>{if(!Se){let x=F.model&&je===F.model?v.current:je;wn({mode:d,thinkingLevel:Y,aiProvider:N,activeModel:x||je,showFullThinking:me,systemSettings:Ht,profileData:ve,imageSettings:fe,apiTier:He})}},[d,Y,N,je,me,Ht,ve,fe,Se,F,He]);let ie=async x=>{let g=x.trim(),D=39;if(N==="OpenRouter"&&(D=30),N==="DeepSeek"&&(D=30),N==="NVIDIA"&&(D=30),g.length>=D){await Qr(N,g),ze(g),Br(g,{aiProvider:N,onIDEApproval:Ln});let _="gemma-4-31b-it";N==="OpenRouter"?_="google/gemma-4-31b-it:free":N==="DeepSeek"?_="deepseek-v4-flash":N==="NVIDIA"&&(_="moonshotai/kimi-k2.6"),Be(_),W(M=>[...M,{role:"system",text:`\u2705 ${N} API Key saved successfully! Model set to ${_}. Initialization complete.`,isMeta:!0}])}else W(_=>[..._,{role:"system",text:`\u274C INVALID KEY: ${N} API keys must be at least ${D} characters.`,isMeta:!0}]),co("")},Ie=Jo(Zi);io(()=>{if(Qt==="exit"){(async()=>{let D=Date.now(),_=Math.floor((D-Ie.current)/1e3);_>=1&&(await Eo("duration",_),Ie.current+=_*1e3),await Ka()})();let g=setTimeout(()=>{process.exit(0)},1700);return()=>clearTimeout(g)}},[Qt]),io(()=>{let x=setInterval(async()=>{if(!Se){let g=Date.now(),D=Math.floor((g-Ie.current)/1e3);D>=1&&(await Eo("duration",D),Ie.current+=D*1e3)}},1500);return()=>clearInterval(x)},[Se]);let Je=[{cmd:"/quit",desc:"Exit and shutdown Flux"},{cmd:"/help",desc:"Show all available commands"},{cmd:"/clear",desc:"Clear terminal screen"},{cmd:"/resume",desc:"Load previous session"},{cmd:"/revert",desc:"Revert codebase back to a checkpoint"},{cmd:"/gemini",desc:"Get a happy message from Gemini CLI"},{cmd:"/save",desc:"Force save current chat"},{cmd:"/export",desc:"Export current chat in a .txt file"},{cmd:"/chats",desc:"List all chat sessions"},{cmd:"/mode",desc:"Toggle Flux/Flow modes",subs:[{cmd:"flux",desc:"Enable Dev toolset"},{cmd:"flow",desc:"Enable Chat mode"}]},{cmd:"/thinking",desc:"Set AI reasoning depth",subs:N==="DeepSeek"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Standard",desc:"Standard Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:N==="NVIDIA"?[{cmd:"Fast",desc:"Reasoning Disabled"},{cmd:"xHigh",desc:"Reasoning Enabled"}]:N==="OpenRouter"?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]:je&&je.toLowerCase().startsWith("gemini-3")?[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"}]:[{cmd:"Fast",desc:"Fastest"},{cmd:"Low",desc:"Quick Reasoning"},{cmd:"Medium",desc:"Balanced Reasoning"},{cmd:"High",desc:"Deep Reasoning"},{cmd:"xHigh",desc:"Extended Reasoning"}]},{cmd:"/model",desc:"Switch Model for Agent",subs:N==="OpenRouter"?He==="Free"?[{cmd:"google/gemma-4-31b-it:free",desc:"Multimodal"},{cmd:"moonshotai/kimi-k2.6:free",desc:"Multimodal"},{cmd:"qwen/qwen3-coder:free",desc:""},{cmd:"z-ai/glm-4.5-air:free",desc:""}]:[{cmd:"google/gemini-3.5-flash",desc:"Multimodal"},{cmd:"qwen/qwen3.7-plus",desc:"Multimodal"},{cmd:"minimax/minimax-m3",desc:"Multimodal"},{cmd:"anthropic/claude-sonnet-4.5",desc:"Multimodal"},{cmd:"anthropic/claude-opus-4.6",desc:"Multimodal"},{cmd:"anthropic/claude-opus-4.8",desc:"Multimodal"},{cmd:"deepseek/deepseek-v4-pro",desc:""},{cmd:"deepseek/deepseek-v4-flash",desc:""},{cmd:"xiaomi/mimo-v2.5-pro",desc:""},{cmd:"z-ai/glm-5",desc:""},{cmd:"openai/gpt-5.2-codex",desc:"Multimodal"},{cmd:"openai/gpt-5.2-pro",desc:"Multimodal"},{cmd:"openai/gpt-5.5-pro",desc:"Multimodal"},{cmd:"moonshotai/kimi-k2.6",desc:"Multimodal"}]:N==="DeepSeek"?[{cmd:"deepseek-v4-flash",desc:"Fast & Efficient"},{cmd:"deepseek-v4-pro",desc:"High-Intelligence Reasoning"}]:N==="NVIDIA"?[{cmd:"moonshotai/kimi-k2.6",desc:"Multimodal [STABLE]"},{cmd:"google/gemma-4-31b-it",desc:"[STABLE]"},{cmd:"stepfun-ai/step-3.7-flash",desc:"[STABLE]"},{cmd:"minimaxai/minimax-m2.7",desc:"[STABLE]"},{cmd:"deepseek-ai/deepseek-v4-flash",desc:""},{cmd:"deepseek-ai/deepseek-v4-pro"}]:He==="Free"?[{cmd:"gemma-4-26b-a4b-it",desc:"Standard & Faster"},{cmd:"gemma-4-31b-it",desc:"Standard Default"},{cmd:"gemini-2.5-flash",desc:"Fast & Reliable (Limited Free Quota)"},{cmd:"gemini-3-flash-preview",desc:"Fast & Lightweight (Limited Free Quota)"},{cmd:"gemini-3.5-flash",desc:"Flash Latest (Limited Free Quota) [Instability Issues]"}]:[{cmd:"gemini-2.5-flash",desc:"Fast & Reliable"},{cmd:"gemini-3.1-flash-lite",desc:"Ultra-Fast & Lite"},{cmd:"gemini-3-flash-preview",desc:"Default, Fast & Lightweight"},{cmd:"gemini-3.5-flash",desc:"Flash Latest [Instability Issues]"},{cmd:"gemini-3.1-pro-preview",desc:"Pro Reasoning"}]},{cmd:"/settings",desc:"Configure system prefs"},{cmd:"/key",desc:"Manage API keys"},{cmd:"/profile",desc:"Edit developer persona"},{cmd:"/memory",desc:"Manage agent memory"},{cmd:"/stats",desc:"Show session usage"},{cmd:"/reset",desc:"Wipe all project data"},{cmd:"/about",desc:"Project info & credits"},{cmd:"/changelog",desc:"View latest updates"},{cmd:"/fluxflow",desc:"Project management",subs:[{cmd:"init",desc:"Create FluxFlow.md template"}]},{cmd:"/update",desc:"Check/Install updates",subs:[{cmd:"check",desc:"Check for new version"},{cmd:"latest",desc:"Install latest release"}]}],Xe=async(x,g=!1)=>{if(!g&&Ae.length>0){let M=Ae[w]||Ae[0],$=x.split(" ");if($.length===1)u(M.cmd+" ");else{let R=$.slice(0,-1);u(R.join(" ")+" "+M.cmd+" ")}T(0),m(R=>R+1);return}let D=x.replace(/\r\n/g,`
548
548
  `).replace(/\r/g,`
549
- `).trimEnd();if(O.endsWith("\\")){u(O.slice(0,-1)+`
550
- `);return}let N=O.replace(/\\\s*\n/g,`
549
+ `).trimEnd();if(D.endsWith("\\")){u(D.slice(0,-1)+`
550
+ `);return}let _=D.replace(/\\\s*\n/g,`
551
551
  `).split(/\r?\n/).map(M=>M.replace(/\\$/,"")).join(`
552
- `);if(N.trim()){if(gn){let M=N.trim();if(M.startsWith("/")){W($=>(ee($.length+1),[...$,{id:"hint-err-"+Date.now(),role:"system",text:"\u274C [RESTRICTED] Steering Hints cannot start with /",isMeta:!0}])),u("");return}Fe(M),Do.current=M,W($=>(ee($.length+1),[...$,{id:"hint-"+Date.now(),role:"user",text:`[STEERING HINT: QUEUED]
553
- ${M}`,color:"magenta"}])),u("");return}if(!be){Ae(N),co("");return}if(N.startsWith("/")){let M=N.split(" "),$=M[0]?.toLowerCase();switch($){case"/quit":{H("exit");break}case"/resume":{if(M[1]){let E=M[1];(async()=>{let P=await _o(),G=P[E]||Object.values(P).find(q=>q.name.toLowerCase()===E.toLowerCase());if(G){r.write("\x1B[2J\x1B[3J\x1B[H"),ct(E);let q=[...G.messages];q[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||(q.unshift({id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Resuming Flux Flow Session...",isMeta:!0}),q.unshift({id:"logo-"+Date.now(),role:"system",text:pr,isLogo:!0,isMeta:!0})),W(q),W(ge=>[...ge,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${E}]`,isMeta:!0}]),ee(0)}else W(q=>[...q,{id:"err-"+Date.now(),role:"system",text:`\u274C ERROR: Session [${E}] not found.`}])})()}else H("resume");break}case"/clear":{W([{id:"logo-"+Date.now(),role:"system",text:pr,isLogo:!0,isMeta:!0},{id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Welcome back to Flux Flow! Context cleared.",isMeta:!0}]),ee(2),ct(oi()),it({tokens:0}),a(!1);break}case"/revert":{kt.getChatHistory(Ue).then(E=>{if(E.length>0)K(E.reverse()),H("revert");else{let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:"revert-empty-"+Date.now(),role:"system",text:"No revert checkpoints found for this session.",isMeta:!0}]))}});break}case"/mode":{if(M[1]){let E=M[1].toLowerCase()==="flow"?"Flow":"Flux";p(E),E==="Flow"?Z("Fast"):E==="Flux"&&Z("High");let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u{1F527}${D}[SYSTEM] Mode switched to ${E}`,isMeta:!0}]))}else H("mode");break}case"/image":{if(M[1]?.toLowerCase()==="stats"){let E=Ie(2);if(de.keyType==="Custom")W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:`\u{1F517}${E}[SYSTEM] Key strategy is Custom. Redirecting to Pollinations dashboard (https://enter.pollinations.ai/#pollen)...`,isMeta:!0}])),Ji("start https://enter.pollinations.ai/#pollen");else try{let D=await ps();W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",isImageStats:!0,text:`\u2022 Hourly Limit: ${Number((D.limit*1e3).toFixed(0))} credits
554
- \u2022 Spent (Last 1hr): ${Number((D.totalSpent*1e3).toFixed(0))} credits
555
- \u2022 Remaining: ${Number((D.remaining*1e3).toFixed(0))} credits
556
- \u2022 Requests (Last 1hr): ${D.activeCallsCount} requests
557
- `+(D.nextResetMin>0?`\u2022 Refreshes in: ${D.nextResetMin}m`:""),isMeta:!0}]))}catch{W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Failed to load image quota stats.",isMeta:!0}]))}}else if(M[1]?.toLowerCase()==="setup")if(M[2]?.toLowerCase()==="key")if(M[3]){let E=["default","custom"].find(D=>D===M[3].toLowerCase());if(E){let D=E==="default"?"Default":"Custom";he(G=>({...G,keyType:D}));let P=Ie(2);W(G=>(ee(G.length+1),[...G,{id:Date.now(),role:"system",text:`\u{1F527}${P}[SYSTEM] Image key strategy set to ${D}`,isMeta:!0}])),D==="Custom"&&(Oo({label:"Enter Pollinations API key (starting with sk_):",note:"Get a key from https://enter.pollinations.ai",key:"imageSettings",subKey:"apiKey",value:de.apiKey||"",returnView:"chat"}),H("input"))}else{let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid key option. Choose: Default or Custom.",isMeta:!0}]))}}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Key <Default|Custom>",isMeta:!0}]))}else if(M[2]?.toLowerCase()==="quality")if(M[3]){let E=["low","low-high","medium","medium-high","high","ultra","premium"].find(D=>D===M[3].toLowerCase());if(E){let P={low:"Low","low-high":"Low-High",medium:"Medium","medium-high":"Medium-High",high:"High",ultra:"Ultra",premium:"Premium"}[E];he(q=>({...q,quality:P}));let G=Ie(2);W(q=>(ee(q.length+1),[...q,{id:Date.now(),role:"system",text:`\u{1F527}${G}[SYSTEM] Image quality set to ${P}`,isMeta:!0}]))}else{let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid quality level. Choose from: Low, Low-High, Medium, Medium-High, High, Ultra, Premium.",isMeta:!0}]))}}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Quality <Low|Low-High|Medium|Medium-High|High|Ultra>",isMeta:!0}]))}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}else{let E=Ie(2);W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}break}case"/thinking":{let E;if(M[1]){let D=M[1].toLowerCase(),P=M.includes("--bypass");if(E=D.charAt(0).toUpperCase()+D.slice(1),D==="xhigh"&&(E="xHigh"),!P&&d==="Flow"&&(E==="Medium"||E==="High"||E==="xHigh"))W(G=>(ee(G.length+1),[...G,{id:Date.now(),role:"system",text:`\u274C [RESTRICTED] "${E}" is restricted in Flow mode. Switch to Flux to enable Higher Thinking Levels.`,isMeta:!0}]));else{Z(E);let G=Ie(1);W(q=>(ee(q.length+1),[...q,{id:Date.now(),role:"system",text:`\u{1F527} [SYSTEM] Thinking level set to ${E}${P?` (Bypass Activated \u{1F575}\uFE0F${G})`:""}`,isMeta:!0}]))}}else H("thinking");break}case"/model":{if(M[1]){let E=M.slice(1).join(" ");if(E==="gemma-4-31b-it"&&Ge!=="Free"&&B==="Google")W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u274C **[ACCESS DENIED]** Gemma is restricted to the Free API tier. Automatically switching you to **Gemini 3 Flash Preview** for optimal performance.",isMeta:!0}])),_e("gemini-3-flash-preview");else{_e(E);let D=Ie(2);W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u{1F527}${D}[SYSTEM] Model switched to ${E}`,isMeta:!0}]))}}else H("model");break}case"/settings":{H("settings");break}case"/key":{H("key");break}case"/profile":{H("profile");break}case"/stats":{(async()=>{let D=await An();Be(D),H("stats")})();break}case"/save":{let E=M.slice(1).join(" ")||`Session ${new Date().toLocaleTimeString()}`;ms(Ue,E,$t),W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:`\u{1F4BE} [MEMORY] Chat saved as "${E}" (ID: ${Ue})`,isMeta:!0}]));break}case"/export":{let E=`export-fluxflow-${Ue}.txt`,D=Kn.join(process.cwd(),E),P=[],G=!1;for(let $e=0;$e<$t.length;$e++){let ge=$t[$e];if(ge&&!(ge.role==="system"||ge.isMeta||ge.isLogo||String(ge.id).startsWith("welcome"))){if(ge.role==="user"){let Oe=ge.text||"";Oe=Oe.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),P.length>0&&P.push(""),P.push("[USER]"),P.push(Oe),G=!1}else if(ge.role==="think"){G||(P.push(""),P.push("[AGENT]"),G=!0);let Oe=(ge.text||"").replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();Oe&&(P.push("[thoughts]"),P.push(Oe))}else if(ge.role==="agent"){G||(P.push(""),P.push("[AGENT]"),G=!0);let Oe=zu(ge.text||"");for(let Pe of Oe)if(Pe.type==="output"){let Ke=Pe.content.replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();Ke&&(P.push("[output]"),P.push(Ke))}else Pe.type==="tool"&&(P.push("[tool]"),P.push(`${Pe.toolName} ${Pe.args}`))}}}let q=P.join(`
558
- `);try{ao.writeFileSync(D,q,"utf8"),W($e=>(ee($e.length+1),[...$e,{id:Date.now(),role:"system",text:`\u{1F4E4} [EXPORT] Chat exported successfully to "${E}"`,isMeta:!0}]))}catch($e){W(ge=>(ee(ge.length+1),[...ge,{id:Date.now(),role:"system",text:`\u274C [EXPORT ERROR] Failed to export chat: ${$e.message}`,isMeta:!0}]))}break}case"/chats":{(async()=>{let D=await _o(),P=Object.entries(D).map(([G,q])=>`\u2022 ${G}: ${q.name}`).join(`
559
- `);W(G=>(ee(G.length+1),[...G,{id:Date.now(),role:"system",text:`\u{1F5C3}\uFE0F [HISTORY] Saved Chats:
560
- ${P||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{H("memory");break}case"/reset":{(async()=>{try{W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u2622\uFE0F [NUCLEAR] Initiating reset...",isMeta:!0}])),ao.existsSync(Io)&&ao.removeSync(Io),ao.existsSync(ro)&&ao.removeSync(ro),ao.existsSync(no)&&ao.removeSync(no);try{ao.readdirSync(Un).length===0&&ao.removeSync(Un)}catch{}setTimeout(()=>{H("exit"),setTimeout(()=>process.exit(0),500)},500)}catch(D){W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u274C [RESET ERROR] Failed to purge data: ${D.message}`}]))}})();break}case"/about":{let E=Ie(2),D=`\u{1F539} FluxFlow Version: v${Pn}
561
- \u{1F539} Status: ${Le&&Le!==Pn?`Update Available [v${Le}]`:"Up to date"}
562
- \u{1F539} Released on: ${Ku}`;W(P=>(ee(P.length+1),[...P,{id:"about-"+Date.now(),role:"system",text:D,isAboutRecord:!0,isMeta:!0}]));break}case"/changelog":{let E=process.platform;Ji(`${E==="win32"?"start":E==="darwin"?"open":"xdg-open"} ${nc}`),W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u{1F310} [BROWSER] Opening changelog: ${nc}`,isMeta:!0}]));break}case"/fluxflow":{if(M.slice(1)[0]==="init"){let D=`# FluxFlow Configuration
552
+ `);if(_.trim()){if(Do){let M=_.trim();if(M.startsWith("/")){W($=>(te($.length+1),[...$,{id:"hint-err-"+Date.now(),role:"system",text:"\u274C [RESTRICTED] Steering Hints cannot start with /",isMeta:!0}])),u("");return}Ft(M),Co.current=M,W($=>(te($.length+1),[...$,{id:"hint-"+Date.now(),role:"user",text:`[STEERING HINT: QUEUED]
553
+ ${M}`,color:"magenta"}])),u("");return}if(!be){ie(_),co("");return}if(_.startsWith("/")){let M=_.split(" "),$=M[0]?.toLowerCase();switch($){case"/quit":{X("exit");break}case"/resume":{if(M[1]){let C=M[1];(async()=>{let B=await _o(),j=B[C]||Object.values(B).find(q=>q.name.toLowerCase()===C.toLowerCase());if(j){r.write("\x1B[2J\x1B[3J\x1B[H"),at(C);let q=[...j.messages];q[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||(q.unshift({id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Resuming Flux Flow Session...",isMeta:!0}),q.unshift({id:"logo-"+Date.now(),role:"system",text:dr,isLogo:!0,isMeta:!0})),W(q),W(le=>[...le,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${C}]`,isMeta:!0}]),te(0)}else W(q=>[...q,{id:"err-"+Date.now(),role:"system",text:`\u274C ERROR: Session [${C}] not found.`}])})()}else X("resume");break}case"/clear":{W([{id:"logo-"+Date.now(),role:"system",text:dr,isLogo:!0,isMeta:!0},{id:"welcome-"+Date.now(),role:"system",text:"\u{1F30A}\u26A1 Welcome back to Flux Flow! Context cleared.",isMeta:!0}]),te(2),at(ti()),rt({tokens:0}),a(!1);break}case"/revert":{kt.getChatHistory(We).then(C=>{if(C.length>0)ct(C.reverse()),X("revert");else{let L=Oe(2);W(B=>(te(B.length+1),[...B,{id:"revert-empty-"+Date.now(),role:"system",text:"No revert checkpoints found for this session.",isMeta:!0}]))}});break}case"/mode":{if(M[1]){let C=M[1].toLowerCase()==="flow"?"Flow":"Flux";p(C),C==="Flow"?Z("Fast"):C==="Flux"&&Z("High");let L=Oe(2);W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u{1F527}${L}[SYSTEM] Mode switched to ${C}`,isMeta:!0}]))}else X("mode");break}case"/image":{if(M[1]?.toLowerCase()==="stats"){let C=Oe(2);if(fe.keyType==="Custom")W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:`\u{1F517}${C}[SYSTEM] Key strategy is Custom. Redirecting to Pollinations dashboard (https://enter.pollinations.ai/#pollen)...`,isMeta:!0}])),Qi("start https://enter.pollinations.ai/#pollen");else try{let L=await ms();W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",isImageStats:!0,text:`\u2022 Hourly Limit: ${Number((L.limit*1e3).toFixed(0))} credits
554
+ \u2022 Spent (Last 1hr): ${Number((L.totalSpent*1e3).toFixed(0))} credits
555
+ \u2022 Remaining: ${Number((L.remaining*1e3).toFixed(0))} credits
556
+ \u2022 Requests (Last 1hr): ${L.activeCallsCount} requests
557
+ `+(L.nextResetMin>0?`\u2022 Refreshes in: ${L.nextResetMin}m`:""),isMeta:!0}]))}catch{W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Failed to load image quota stats.",isMeta:!0}]))}}else if(M[1]?.toLowerCase()==="setup")if(M[2]?.toLowerCase()==="key")if(M[3]){let C=["default","custom"].find(L=>L===M[3].toLowerCase());if(C){let L=C==="default"?"Default":"Custom";ge(j=>({...j,keyType:L}));let B=Oe(2);W(j=>(te(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u{1F527}${B}[SYSTEM] Image key strategy set to ${L}`,isMeta:!0}])),L==="Custom"&&(vo({label:"Enter Pollinations API key (starting with sk_):",note:"Get a key from https://enter.pollinations.ai",key:"imageSettings",subKey:"apiKey",value:fe.apiKey||"",returnView:"chat"}),X("input"))}else{let L=Oe(2);W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid key option. Choose: Default or Custom.",isMeta:!0}]))}}else{let C=Oe(2);W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Key <Default|Custom>",isMeta:!0}]))}else if(M[2]?.toLowerCase()==="quality")if(M[3]){let C=["low","low-high","medium","medium-high","high","ultra","premium"].find(L=>L===M[3].toLowerCase());if(C){let B={low:"Low","low-high":"Low-High",medium:"Medium","medium-high":"Medium-High",high:"High",ultra:"Ultra",premium:"Premium"}[C];ge(q=>({...q,quality:B}));let j=Oe(2);W(q=>(te(q.length+1),[...q,{id:Date.now(),role:"system",text:`\u{1F527}${j}[SYSTEM] Image quality set to ${B}`,isMeta:!0}]))}else{let L=Oe(2);W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Invalid quality level. Choose from: Low, Low-High, Medium, Medium-High, High, Ultra, Premium.",isMeta:!0}]))}}else{let C=Oe(2);W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup Quality <Low|Low-High|Medium|Medium-High|High|Ultra>",isMeta:!0}]))}else{let C=Oe(2);W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}else{let C=Oe(2);W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u274C [SYSTEM] Usage: /image setup <Key|Quality> ...",isMeta:!0}]))}break}case"/thinking":{let C;if(M[1]){let L=M[1].toLowerCase(),B=M.includes("--bypass");if(C=L.charAt(0).toUpperCase()+L.slice(1),L==="xhigh"&&(C="xHigh"),!B&&d==="Flow"&&(C==="Medium"||C==="High"||C==="xHigh"))W(j=>(te(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u274C [RESTRICTED] "${C}" is restricted in Flow mode. Switch to Flux to enable Higher Thinking Levels.`,isMeta:!0}]));else{Z(C);let j=Oe(1);W(q=>(te(q.length+1),[...q,{id:Date.now(),role:"system",text:`\u{1F527} [SYSTEM] Thinking level set to ${C}${B?` (Bypass Activated \u{1F575}\uFE0F${j})`:""}`,isMeta:!0}]))}}else X("thinking");break}case"/model":{if(M[1]){let C=M.slice(1).join(" ");if(C==="gemma-4-31b-it"&&He!=="Free"&&N==="Google")W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u274C **[ACCESS DENIED]** Gemma is restricted to the Free API tier. Automatically switching you to **Gemini 3 Flash Preview** for optimal performance.",isMeta:!0}])),Be("gemini-3-flash-preview");else{Be(C);let L=Oe(2);W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u{1F527}${L}[SYSTEM] Model switched to ${C}`,isMeta:!0}]))}}else X("model");break}case"/settings":{X("settings");break}case"/key":{X("key");break}case"/profile":{X("profile");break}case"/stats":{(async()=>{let L=await Cn();Re(L),X("stats")})();break}case"/save":{let C=M.slice(1).join(" ")||`Session ${new Date().toLocaleTimeString()}`;us(We,C,Fe),W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:`\u{1F4BE} [MEMORY] Chat saved as "${C}" (ID: ${We})`,isMeta:!0}]));break}case"/export":{let C=`export-fluxflow-${We}.txt`,L=Xn.join(process.cwd(),C),B=[],j=!1;for(let ce=0;ce<Fe.length;ce++){let le=Fe[ce];if(le&&!(le.role==="system"||le.isMeta||le.isLogo||String(le.id).startsWith("welcome"))){if(le.role==="user"){let Ne=le.text||"";Ne=Ne.replace(/\s*\[Prompted on:.*?\]/g,"").trim(),B.length>0&&B.push(""),B.push("[USER]"),B.push(Ne),j=!1}else if(le.role==="think"){j||(B.push(""),B.push("[AGENT]"),j=!0);let Ne=(le.text||"").replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();Ne&&(B.push("[thoughts]"),B.push(Ne))}else if(le.role==="agent"){j||(B.push(""),B.push("[AGENT]"),j=!0);let Ne=Qu(le.text||"");for(let Me of Ne)if(Me.type==="output"){let Tt=Me.content.replace(/\[turn:\s*continue\]/gi,"").replace(/\[turn:\s*finish\]/gi,"").replace(/\[\[END\]\]/gi,"").replace(/\[TOOL RESULTS\]/gi,"").trim();Tt&&(B.push("[output]"),B.push(Tt))}else Me.type==="tool"&&(B.push("[tool]"),B.push(`${Me.toolName} ${Me.args}`))}}}let q=B.join(`
558
+ `);try{ao.writeFileSync(L,q,"utf8"),W(ce=>(te(ce.length+1),[...ce,{id:Date.now(),role:"system",text:`\u{1F4E4} [EXPORT] Chat exported successfully to "${C}"`,isMeta:!0}]))}catch(ce){W(le=>(te(le.length+1),[...le,{id:Date.now(),role:"system",text:`\u274C [EXPORT ERROR] Failed to export chat: ${ce.message}`,isMeta:!0}]))}break}case"/chats":{(async()=>{let L=await _o(),B=Object.entries(L).map(([j,q])=>`\u2022 ${j}: ${q.name}`).join(`
559
+ `);W(j=>(te(j.length+1),[...j,{id:Date.now(),role:"system",text:`\u{1F5C3}\uFE0F [HISTORY] Saved Chats:
560
+ ${B||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{X("memory");break}case"/reset":{(async()=>{try{W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u2622\uFE0F [NUCLEAR] Initiating reset...",isMeta:!0}])),ao.existsSync(ko)&&ao.removeSync(ko),ao.existsSync(ro)&&ao.removeSync(ro),ao.existsSync(no)&&ao.removeSync(no);try{ao.readdirSync(Bn).length===0&&ao.removeSync(Bn)}catch{}setTimeout(()=>{X("exit"),setTimeout(()=>process.exit(0),500)},500)}catch(L){W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u274C [RESET ERROR] Failed to purge data: ${L.message}`}]))}})();break}case"/about":{let C=Oe(2),L=`\u{1F539} FluxFlow Version: v${Dn}
561
+ \u{1F539} Status: ${$e&&$e!==Dn?`Update Available [v${$e}]`:"Up to date"}
562
+ \u{1F539} Released on: ${qu}`;W(B=>(te(B.length+1),[...B,{id:"about-"+Date.now(),role:"system",text:L,isAboutRecord:!0,isMeta:!0}]));break}case"/changelog":{let C=process.platform;Qi(`${C==="win32"?"start":C==="darwin"?"open":"xdg-open"} ${rc}`),W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u{1F310} [BROWSER] Opening changelog: ${rc}`,isMeta:!0}]));break}case"/fluxflow":{if(M.slice(1)[0]==="init"){let L=`# FluxFlow Configuration
563
563
  # This file defines project-specific instructions for the Flux Flow Agent.
564
564
 
565
565
  # IDENTITY & TONE
@@ -574,31 +574,31 @@ ${P||"No saved chats found."}`,isMeta:!0}]))})();break}case"/memory":{H("memory"
574
574
 
575
575
  # SKILLS & WORKFLOWS
576
576
  - [Define custom step-by-step recipes for this project here]
577
- `,P=Kn.join(process.cwd(),"FluxFlow.md");if(ao.pathExistsSync(P))W(G=>(ee(G.length+1),[...G,{id:"init-err-"+Date.now(),role:"system",text:"\u274C ERROR: FluxFlow.md already exists in this directory.",isMeta:!0}]));else try{ao.writeFileSync(P,D),W(G=>(ee(G.length+1),[...G,{id:"init-ok-"+Date.now(),role:"system",text:"\u2705 [SUCCESS] FluxFlow.md has been initialized. You can now customize it for this project.",isMeta:!0}]))}catch(G){W(q=>(ee(q.length+1),[...q,{id:"init-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to initialize FluxFlow.md: ${G.message}`,isMeta:!0}]))}}else W(D=>(ee(D.length+1),[...D,{id:"ff-err-"+Date.now(),role:"system",text:"\u2753 Usage: /fluxflow init",isMeta:!0}]));break}case"/update":{if(M[1]?.toLowerCase()==="check"){Q(!0);break}let D=M.includes("--latest");H("update");break}case"/gemini":{let E=qi[Math.floor(Math.random()*qi.length)];W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:`\u2728 [GEMINI CLI] ${E}`}])),u("");break}case"/help":{W(E=>(ee(E.length+1),[...E,{id:Date.now(),role:"system",isHelpRecord:!0,isMeta:!0}]));break}default:let U=Ie(2);W(E=>(ee(E.length+1),[...E,{id:Date.now(),role:"system",text:`\u{1F527}${U}[SYSTEM] Unknown command: ${$}`,isMeta:!0}]))}}else{let M=`[Prompted on: ${new Date().toLocaleString(void 0,{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"})}]`,$={id:"user-"+Date.now(),role:"user",text:`${N}
577
+ `,B=Xn.join(process.cwd(),"FluxFlow.md");if(ao.pathExistsSync(B))W(j=>(te(j.length+1),[...j,{id:"init-err-"+Date.now(),role:"system",text:"\u274C ERROR: FluxFlow.md already exists in this directory.",isMeta:!0}]));else try{ao.writeFileSync(B,L),W(j=>(te(j.length+1),[...j,{id:"init-ok-"+Date.now(),role:"system",text:"\u2705 [SUCCESS] FluxFlow.md has been initialized. You can now customize it for this project.",isMeta:!0}]))}catch(j){W(q=>(te(q.length+1),[...q,{id:"init-err-"+Date.now(),role:"system",text:`\u274C ERROR: Failed to initialize FluxFlow.md: ${j.message}`,isMeta:!0}]))}}else W(L=>(te(L.length+1),[...L,{id:"ff-err-"+Date.now(),role:"system",text:"\u2753 Usage: /fluxflow init",isMeta:!0}]));break}case"/update":{if(M[1]?.toLowerCase()==="check"){V(!0);break}let L=M.includes("--latest");X("update");break}case"/gemini":{let C=qi[Math.floor(Math.random()*qi.length)];W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:`\u2728 [GEMINI CLI] ${C}`}])),u("");break}case"/help":{W(C=>(te(C.length+1),[...C,{id:Date.now(),role:"system",isHelpRecord:!0,isMeta:!0}]));break}default:let R=Oe(2);W(C=>(te(C.length+1),[...C,{id:Date.now(),role:"system",text:`\u{1F527}${R}[SYSTEM] Unknown command: ${$}`,isMeta:!0}]))}}else{let M=`[Prompted on: ${new Date().toLocaleString(void 0,{year:"numeric",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"})}]`,$={id:"user-"+Date.now(),role:"user",text:`${_}
578
578
 
579
- ${M}`};W(E=>(ee(E.length+1),[...E,$])),(async()=>{let E=!1;jr(!0),a(!1);let D=Date.now(),P=!0;try{let G=[...$t,$].filter(Y=>Y.role!=="think"&&!Y.isVisualFeedback&&!Y.isMeta&&!String(Y.id).startsWith("welcome")),q=[];G.forEach((Y,le)=>{let me=Y.fullText||Y.text;if(Y.role==="user"&&le<G.length-1){let De=me.lastIndexOf("[USER]");De!==-1&&(me=me.substring(De+6).trim())}if(Y.role==="system"&&me?.startsWith("[TOOL RESULT]")){let De=q[q.length-1];if(De&&De.role==="system"&&De.text?.startsWith("[TOOL RESULT]")){De.text+=`
579
+ ${M}`};W(C=>(te(C.length+1),[...C,$])),(async()=>{let C=!1;xr(!0),a(!1);let L=Date.now(),B=!0;try{let j=[...Fe,$].filter(H=>H.role!=="think"&&!H.isVisualFeedback&&!H.isMeta&&!String(H.id).startsWith("welcome")),q=[];j.forEach((H,ue)=>{let pe=H.fullText||H.text;if(H.role==="user"&&ue<j.length-1){let ye=pe.lastIndexOf("[USER]");ye!==-1&&(pe=pe.substring(ye+6).trim())}if(H.role==="system"&&pe?.startsWith("[TOOL RESULT]")){let ye=q[q.length-1];if(ye&&ye.role==="system"&&ye.text?.startsWith("[TOOL RESULT]")){ye.text+=`
580
580
 
581
- `+me;return}}q.push({...Y,text:me})});let $e=Nl(Ye,q,{profile:ve,thinkingLevel:j,mode:d,systemSettings:Yt,janitorModel:Me,sessionStats:fe,chatId:Ue,aiProvider:B,apiKey:be,apiTier:Ge,cols:h.columns-6,rows:30,onExecStart:Y=>{nt(Y),xo("")},onExecChunk:Y=>{xo(le=>le+Y)},onExecEnd:()=>{W(Y=>{if(!Se.current)return Y;let le=Qe.current||"",me=Lr(le),De=`[TERMINAL_RECORD]
582
- COMMAND: ${Se.current}
581
+ `+pe;return}}q.push({...H,text:pe})});let ce=Bl(je,q,{profile:ve,thinkingLevel:Y,mode:d,systemSettings:Ht,janitorModel:Le,sessionStats:he,chatId:We,aiProvider:N,apiKey:be,apiTier:He,cols:h.columns-6,rows:30,onExecStart:H=>{tt(H),Ro("")},onExecChunk:H=>{Ro(ue=>ue+H)},onExecEnd:()=>{W(H=>{if(!hr.current)return H;let ue=Ce.current||"",pe=Lr(ue),ye=`[TERMINAL_RECORD]
582
+ COMMAND: ${hr.current}
583
583
  PTY: ${$o}
584
- OUTPUT: ${me.replace(/\n{3,}/g,`
584
+ OUTPUT: ${pe.replace(/\n{3,}/g,`
585
585
 
586
- `)}`;return[...Y,{id:"term-"+Date.now(),role:"system",text:De,isTerminalRecord:!0}]}),nt(null),Lt(!1),xo("")},onToolResult:(Y,le)=>{if(Y==="success"){if(lt(me=>me+1),le==="generate_image"){As(_t=>_t+1);let De={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[de.quality]||.002;Os(_t=>_t+De)}}else Y==="denied"?vs(me=>me+1):Jt(me=>me+1)},onToolApproval:async(Y,le)=>{let me=yo||Yt.autoExec;if(Y==="exec_command"){let{command:De}=ne(le||"{}");return me||De&&/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i.test(De.trim())?"allow":new Promise(pe=>{Uo({tool:Y,args:le,resolve:pe}),H("terminalApproval")})}return me?"allow":new Promise(De=>{Uo({tool:Y,args:le,resolve:De}),H("approval")})},onAskUser:async(Y,le)=>new Promise(me=>{yr({question:Y,options:le,resolve:De=>{W(_t=>[..._t,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
587
- Selection: ${De}`,isAskRecord:!0}]),me(De)}}),H("ask")})},async()=>{if(Do.current){let Y=Do.current;return Fe(null),Do.current=null,W(le=>{let me=[...le].reverse().findIndex(De=>De.text?.includes("[STEERING HINT: QUEUED]"));if(me!==-1){let De=le.length-1-me,_t=[...le];return _t[De]={..._t[De],text:_t[De].text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: INJECTED]"),color:"cyan"},_t}return le}),Y}return null},Pn),ge=!1,Oe=null,Pe=null,Ke=!1,yn=!1,to=!1,Pt=!1,jo=0,To=null,Xr=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let Y of $e){if(P&&Y.type==="text"&&(D=Date.now(),P=!1),Y.type==="status"){Jn(Y.content),Vo()&&Ss(Y.content);continue}if(Y.type==="status_history"){Jn(Y.content),Vo()&&Ss(Y.content),W(pe=>[...pe,{id:"condense-"+Date.now(),role:"system",text:`\u2699\uFE0F [SYSTEM] ${Y.content}`,isMeta:!0}]);continue}if(Y.type==="spinner"){Qn(Y.content);continue}if(Y.type==="model_update"){bt(Y.content);continue}if(Y.type==="turn_reset"){Oe=null,Pe=null,ge=!1,Ke=!1,yn=!1,Pt=!1,to=!1;continue}if(Y.type==="interactive_turn_finished"){jr(!1),Vo()&&Ss(null),E=!0,Pl({profile:ve,thinkingLevel:j,mode:d,janitorModel:Me,chatId:Ue,systemSettings:Yt,sessionStats:fe,aiProvider:B,apiKey:be},Y.data.agentText,Y.data.fullAgentTextRaw,Y.data.history,{onMemoryUpdated:()=>W(pe=>{let we=[...pe];return we.length>0&&(we[we.length-1].memoryUpdated=!0),we}),onBackgroundIncrement:()=>Ne(pe=>pe+1)});continue}if(Y.type==="visual_feedback"){W(pe=>[...pe,{id:"feedback-"+Date.now(),role:"system",text:Y.content,isVisualFeedback:!0}]);continue}if(Y.type==="exec_start")continue;if(Y.type==="liveTokens"){it({tokens:Y.content});continue}if(Y.type==="usage"){let pe=Y.content.totalTokenCount||0,we=Y.content.cachedContentTokenCount||0,Ze=Y.content.candidatesTokenCount||0;it({tokens:pe}),jt(Ct=>Ct+pe),we>0&&go(Ct=>Ct+we),Ze>0&&pn(Ct=>Ct+Ze),St(Ct=>Ct+1);continue}if(Y.type==="tool_time"){Zi(pe=>pe+Y.content);continue}if(Y.type==="tool_result"){if(W(pe=>[...pe,{id:"tool-"+Date.now(),role:"system",text:Y.content,fullText:Y.aiContent,binaryPart:Y.binaryPart,toolName:Y.toolName}]),Y.toolName==="update_file"&&Y.aiContent){let pe=Y.aiContent.split(`
588
- `),we=0,Ze=0,Ct=!1;for(let At of pe){if(At.includes("[DIFF_START]")){Ct=!0;continue}if(At.includes("[DIFF_END]")){Ct=!1;continue}Ct&&(/^\+\d+/.test(At)?we++:/^\-\d+/.test(At)&&Ze++)}ks+=we,Is+=Ze,Co("linesAdded",we),Co("linesRemoved",Ze)}else if(Y.toolName==="write_file"&&Y.aiContent){let pe=Y.aiContent.match(/- Stats: \[(\d+) lines/),we=pe?parseInt(pe[1]):0,Ze=0;if(Y.aiContent.includes("Old File contents:")){let Ct=Y.aiContent.split(`
589
- `),At=!1;for(let oo of Ct){if(oo.includes("Old File contents:")){At=!0;continue}At&&(oo.trim()===""?At=!1:/^\d+ \|/.test(oo)&&Ze++)}}ks+=we,Is+=Ze,Co("linesAdded",we),Co("linesRemoved",Ze)}continue}let le=Y.content,me=le.toLowerCase();if(le.includes("```")&&(Ke=!Ke),me.includes("tool:functions.")&&(yn=!0,jo=0,To=null,le.includes("[tool:functions.")&&(jo=0)),yn){for(let pe=0;pe<le.length;pe++){let we=le[pe];!To&&(we==="'"||we==='"'||we==="`")?To=we:To&&we===To&&le[pe-1]!=="\\"&&(To=null),To||(we==="("||we==="["?jo++:(we===")"||we==="]")&&jo--)}jo<=0&&!To&&(yn=!1)}if((me.includes("<think")||me.includes("<thought"))&&(!ge&&!Ke&&!yn&&!to)&&(ge=!0,to=!0,le=le.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),Oe="think-"+Date.now(),W(pe=>[...pe,{id:Oe,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(me.includes("</think>")||me.includes("</thought>"))&&Oe){let pe=le.split(/<\/(think|thought)>/gi),we=pe[0]||"",Ze=pe.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");W(Ct=>{let At=Ct.map(oo=>{if(oo.id===Oe&&typeof oo.id=="string"){let Kr=oo.startTime||parseInt(oo.id.split("-")[1])||Date.now(),$s=Date.now()-Kr;return{...oo,text:oo.text+we,isStreaming:!1,duration:$s}}return oo});return ge=!1,Pe="agent-"+Date.now(),[...At,{id:Pe,role:"agent",text:Ze,isStreaming:!0}]});continue}if(ge&&Oe)W(pe=>{let we=!1,Ze="",Ct=pe.map(At=>{if(At.id===Oe){let oo=At.text+le;if(oo.toLowerCase().includes("</think>")){we=!0;let Kr=oo.split(/<\/think>/gi);Ze=Kr.slice(1).join("</think>")||"";let $s=At.startTime||parseInt(At.id.split("-")[1])||Date.now(),mc=Date.now()-$s;return{...At,text:Kr[0],isStreaming:!1,duration:mc}}return{...At,text:oo,isStreaming:!0}}return At});return we?(ge=!1,Pe="agent-"+Date.now(),[...Ct,{id:Pe,role:"agent",text:Ze.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):Ct});else if(!ge){let pe=le.toLowerCase();!Pt&&pe.includes("tool:functions.")&&(Pt=!0),Pe?W(we=>we.map(Ze=>Ze.id===Pe?{...Ze,text:Ze.text+le,isStreaming:!0}:Ze)):(Pe="agent-"+Date.now(),W(we=>[...we,{id:Pe,role:"agent",text:le,isStreaming:!0}]))}}let er=Date.now();gr(Y=>Y+(er-D))}catch(G){W(q=>(ee(q.length+1),[...q,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${G.message}`}]))}finally{if(jr(!1),Jn(null),E||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),Do.current){on(Do.current),Fe(null);let G=Do.current;Do.current=null,W(q=>{let $e=[...q],ge=$e.reverse().find(Oe=>Oe.text?.includes("[STEERING HINT: QUEUED]"));return ge&&(ge.text=ge.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),$e.reverse()}),H("resolution")}W(G=>{let q=Date.now()-D,$e=!1,ge=[...G].reverse().map(Pe=>{let Ke=Pe.isStreaming?{...Pe,isStreaming:!1}:Pe;return!$e&&Ke.role==="agent"&&($e=!0,Ke={...Ke,workedDuration:q}),Ke}).reverse(),Oe=ge.filter(Pe=>!String(Pe.id).startsWith("welcome")&&!Pe.isMeta);return ms(Ue,null,Oe),ee(ge.length),ge})}})()}u(""),a(!1)}},Ce=Ur(()=>{if(l.startsWith("/")&&!I){let O=l.split(" "),N=O[O.length-1].toLowerCase();if(O.length===1){let $=N.startsWith("/")?N.slice(1):N;return Ve.filter(U=>(U.cmd.startsWith("/")?U.cmd.slice(1):U.cmd).toLowerCase().includes($))}let M=Ve;for(let $=0;$<O.length-1;$++){let U=O[$].toLowerCase(),E=M.find(D=>D.cmd.toLowerCase()===U);if(E&&E.subs)M=E.subs;else return[]}return M.filter($=>$.cmd.toLowerCase().includes(N))}let x=l.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!I){let O=g.indexOf("#"),N=O!==-1,M=N?g.substring(1,O).toLowerCase():g.slice(1).toLowerCase(),$=N?g.substring(O):"";return Ju(process.cwd()).filter(D=>D.name.toLowerCase().includes(M)).map(D=>{let P=D.relativePath.replace(/\\/g,"/");return{cmd:"@["+(P.startsWith(".")?P:"./"+P)+$+"]",desc:D.relativePath}})}return[]},[l,I]);io(()=>{w(0)},[Ce]);let wo=()=>{switch(Vt){case"settings":return i.createElement(qs,{systemSettings:Yt,setSystemSettings:te,apiTier:Ge,setActiveView:H,setInputConfig:Oo,saveSettings:Cn,quotas:zt,setMessages:W,aiProvider:B});case"selectProvider":return i.createElement(fo,{title:"SELECT AI PROVIDER",items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){H("settings");return}let g=x.value,O=await Zr(g);if(O){z(g),rt(O),Br(O,{aiProvider:g,onIDEApproval:tn});let N="gemma-4-31b-it";g==="OpenRouter"?N="google/gemma-4-31b-it:free":g==="DeepSeek"&&(N="deepseek-v4-flash"),_e(N),Cn({aiProvider:g,activeModel:N,apiTier:Ge,quotas:zt}),W(M=>[...M,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${N}.`,isMeta:!0}]),H("settings")}else Oo({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),H("input")},onClose:()=>H("settings")});case"apiTier":return i.createElement(fo,{title:i.createElement(y,null,"SELECT YOUR CURRENT API TIER BASED ON ",i.createElement(y,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",Ge.toUpperCase(),")"),items:[{label:"Free Tier (Gemini API Free Tier)",value:"Free"},{label:"Paid Tier (API with Billing Account)",value:"Paid"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){H("settings");return}let g=x.value;Rr(g),g==="Paid"?(Oo({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(zt.agentLimit)}),H("input")):(Cn({apiTier:g,quotas:zt}),H("settings"))},onClose:()=>H("settings")});case"input":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0},"\u{1F527} DATA CONFIGURATION")),ht?.note&&i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",dimColor:!0,italic:!0},ht.note)),i.createElement(k,{paddingX:1,flexDirection:"row"},i.createElement(y,{color:"cyan",bold:!0},ht?.label," "),i.createElement(oc,{value:ht?.value||"",onChange:x=>Oo(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:O,next:N}=ht,M={...zt},$={};if(g==="quotas"){let U=O.toLowerCase().includes("limit")?parseInt(x)||0:x;M[O]=U,qn(M),$.quotas=M}else if(g==="activeModel")_e(x),$.activeModel=x;else if(g==="janitorModel")je(x),$.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let U={...Yt,[g]:x.trim(),sandboxPreset:"Custom"};te(U),$.systemSettings=U}else if(g==="externalDataPath"){let U={...Yt,useExternalData:!0,externalDataPath:x.trim()};te(U),$.systemSettings=U,W(E=>[...E,{id:Date.now(),role:"system",text:"\u{1F4C1} [EXTERNAL STORAGE] Flux Flow will use "+x.trim()+" for data after restart."}])}else if(g==="imageSettings"){let U=x.trim();if(U.startsWith("sk_")){let E={...de,apiKey:U};he(E),$.imageSettings=E,W(D=>(ee(D.length+1),[...D,{id:Date.now(),role:"system",text:"\u{1F511} [IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else he(E=>({...E,keyType:"Default"})),$.imageSettings={...de,keyType:"Default"},W(E=>(ee(E.length+1),[...E,{id:Date.now(),role:"system",text:"\u274C [IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let U=x.trim(),E=ht.provider;await es(E,U),z(E),rt(U),Br(U,{aiProvider:E,onIDEApproval:tn});let D="gemma-4-31b-it";E==="OpenRouter"?D="google/gemma-4-31b-it:free":E==="DeepSeek"&&(D="deepseek-v4-flash"),_e(D),$.aiProvider=E,$.activeModel=D,W(P=>(ee(P.length+1),[...P,{id:Date.now(),role:"system",text:`\u2705 ${E} API Key saved successfully! Model set to ${D}.`,isMeta:!0}]))}N?Oo(N(g==="quotas"?M:x)):(Cn({...$,apiTier:Ge,quotas:M,imageSettings:$.imageSettings||de}),Oo(null),H(ht?.returnView||"settings"))}})),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,width:Math.min(100,(r?.columns||100)-2)},i.createElement(k,{marginBottom:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),i.createElement(k,{flexDirection:"column"},i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Session Duration:")),i.createElement(y,{color:"white"},Ro(Date.now()-Qi))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},Bo)),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},Ro(hr))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},Ro(Vn))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},gt)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-xt))),at>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(at))),xt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(xt)))),xr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},xr)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((_n||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes (Sess):")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",ks)," ",i.createElement(y,{color:"red"},"-",Is))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls (Sess):")),i.createElement(y,{color:"white"},ot+Gt+en," ( "),i.createElement(y,{color:"green"},"\u2713 ",ot),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",en),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",Gt),i.createElement(y,{color:"white"}," )"))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),i.createElement(k,{marginTop:1},i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Wall Time Today:")),i.createElement(y,{color:"white"},Yr(se?.duration||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},se?.agent||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},se?.background||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Used Today:")),i.createElement(y,{color:"white"},so(se?.tokens||0))),(se?.tokens||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so((se?.tokens||0)-(se?.candidateTokens||0)))),(se?.cachedTokens||0)>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(se.cachedTokens))),(se?.candidateTokens||0)>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(se.candidateTokens)))),(se?.imageCalls?.length||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made Today:")),i.createElement(y,{color:"white"},se.imageCalls.length)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits Today:")),i.createElement(y,{color:"white"},Number(((se.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes Today:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",se?.linesAdded||0)," ",i.createElement(y,{color:"red"},"-",se?.linesRemoved||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls Today:")),i.createElement(y,{color:"white"},(se?.toolSuccess||0)+(se?.toolFailure||0)+(se?.toolDenied||0)," ( "),i.createElement(y,{color:"green"},"\u2713 ",se?.toolSuccess||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",se?.toolDenied||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",se?.toolFailure||0),i.createElement(y,{color:"white"}," )"))),i.createElement(y,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: YOLO MODE"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake."),i.createElement(y,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),i.createElement(y,null,"\u2022 Reduced control over the agent's step-by-step decision making."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&te(g=>({...g,autoExec:!0})),H("settings")}})));case"externalDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),i.createElement(y,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),i.createElement(y,null,"\u2022 Unauthorized script execution across your entire file system."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&te(g=>({...g,allowExternalAccess:!0})),H("settings")}})));case"doubleDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26D4 CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),i.createElement(y,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),i.createElement(y,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),i.createElement(y,{marginTop:1,color:"yellow"},"THE CRITICAL RISK:"),i.createElement(y,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),i.createElement(y,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&&te(g=>({...g,autoExec:!0,allowExternalAccess:!0})),H("settings")}})));case"key":return i.createElement(fo,{title:"\u{1F511} API KEY MANAGEMENT",items:[{label:"Edit Current Key (Update)",value:"edit"},{label:"Remove Current Key (Purge)",value:"remove"},{label:"Cancel",value:"Cancel"}],onSelect:x=>{if(x.value==="edit"){rt(null),H("chat");let g=Ie(2);W(O=>[...O,{id:Date.now(),role:"system",text:`\u{1F511}${g}[ACTION] Flux waiting for new API Key...`}])}else x.value==="remove"?H("deleteKey"):H("chat")}});case"deleteKey":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},(()=>{let x=Ie(2);return i.createElement(y,{color:"red",bold:!0},"\u26D4",x,"DANGER: PURGE API KEY")})(),i.createElement(y,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Are you absolutely sure?",items:[{label:"YES, PURGE KEY",value:"yes"},{label:"NO, GO BACK",value:"no"}],onSelect:async x=>{if(x.value==="yes"){await _s(),rt(null),H("chat");let g=Ie(2);W(O=>[...O,{id:Date.now(),role:"system",text:`\u2728${g}[VAULT PURGED] API Key removed successfully.`}])}else H("key")}})));case"exit":return null;case"ask":return i.createElement(k,{width:"100%"},i.createElement(va,{question:hn?.question,options:hn?.options,onResolve:x=>{hn?.resolve&&hn.resolve(x),yr(null),H("chat")}}));case"revert":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(zi,{prompts:yt,onSelect:async x=>{try{let g=await kt.rollbackToBefore(x);if(g.success){let{targetPrompt:O}=g,N=$t.findIndex(E=>E.role==="user"&&E.text&&(E.text.startsWith(O)||E.text.includes(O))),M=[...$t];N!==-1&&(M=$t.slice(0,N)),W(M),ee(M.length),u(O),a(O.split(`
590
- `).length>2);let $=M.filter(E=>!String(E.id).startsWith("welcome")&&!E.isMeta);await ms(Ue,null,$);let U=Ie(2);W(E=>{let D=[...E,{id:"revert-ok-"+Date.now(),role:"system",text:`\u{1F504}${U}[TIME TRAVEL] Codebase rolled back successfully! Reverted prompt loaded to input box.`,isMeta:!0}];return ee(D.length),D}),H("chat")}}catch(g){let O=Ie(2);W(N=>{let M=[...N,{id:"revert-err-"+Date.now(),role:"system",text:`\u274C${O}[TIME TRAVEL ERROR] Failed to rollback: ${g.message}`,isMeta:!0}];return ee(M.length),M}),H("chat")}},onClose:()=>H("chat")}));case"resume":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Gi,{onSelect:async x=>{let g=await _o();if(g[x]){r.write("\x1B[2J\x1B[3J\x1B[H"),ct(x);let O=[...g[x].messages];O[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||O.unshift({id:"welcome-"+Date.now(),role:"system",text:pr+`
586
+ `)}`;return[...H,{id:"term-"+Date.now(),role:"system",text:ye,isTerminalRecord:!0}]}),tt(null),Ut(!1),Ro("")},onToolResult:(H,ue)=>{if(H==="success"){if(it(pe=>pe+1),ue==="generate_image"){As($t=>$t+1);let ye={Low:.001,"Low-High":.002,Medium:.008,"Medium-High":.01,High:.045,Ultra:.0488,Premium:.1}[fe.quality]||.002;Ms($t=>$t+ye)}}else H==="denied"?Is(pe=>pe+1):Kt(pe=>pe+1)},onToolApproval:async(H,ue)=>{let pe=ot||Ht.autoExec;if(H==="exec_command"){let{command:ye}=ne(ue||"{}");return pe||ye&&/^(echo|ls|dir|pwd|cd|git status|git log|git diff|type|cat|help)\b/i.test(ye.trim())?"allow":new Promise(xe=>{Rt({tool:H,args:ue,resolve:xe}),X("terminalApproval")})}return pe?"allow":new Promise(ye=>{Rt({tool:H,args:ue,resolve:ye}),X("approval")})},onAskUser:async(H,ue)=>new Promise(pe=>{qn({question:H,options:ue,resolve:ye=>{W($t=>[...$t,{id:"ask-"+Date.now(),role:"system",text:`\u{1F4AC} **Ask User**
587
+ Selection: ${ye}`,isAskRecord:!0}]),pe(ye)}}),X("ask")})},async()=>{if(Co.current){let H=Co.current;return Ft(null),Co.current=null,W(ue=>{let pe=[...ue].reverse().findIndex(ye=>ye.text?.includes("[STEERING HINT: QUEUED]"));if(pe!==-1){let ye=ue.length-1-pe,$t=[...ue];return $t[ye]={...$t[ye],text:$t[ye].text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: INJECTED]"),color:"cyan"},$t}return ue}),H}return null},Dn),le=!1,Ne=null,Me=null,Tt=!1,Mt=!1,Jn=!1,to=!1,vt=0,yo=null,Tr=/\[?\s*turn\s*:\s*.*?\s*\]?/gi;for await(let H of ce){if(B&&H.type==="text"&&(L=Date.now(),B=!1),H.type==="status"){gr(H.content),Ko()&&ws(H.content);continue}if(H.type==="status_history"){gr(H.content),Ko()&&ws(H.content),W(xe=>[...xe,{id:"condense-"+Date.now(),role:"system",text:`\u2699\uFE0F [SYSTEM] ${H.content}`,isMeta:!0}]);continue}if(H.type==="spinner"){ta(H.content);continue}if(H.type==="model_update"){Nn(H.content);continue}if(H.type==="turn_reset"){Ne=null,Me=null,le=!1,Tt=!1,Mt=!1,to=!1,Jn=!1;continue}if(H.type==="interactive_turn_finished"){xr(!1),Ko()&&ws(null),C=!0,_l({profile:ve,thinkingLevel:Y,mode:d,janitorModel:Le,chatId:We,systemSettings:Ht,sessionStats:he,aiProvider:N,apiKey:be},H.data.agentText,H.data.fullAgentTextRaw,H.data.history,{onMemoryUpdated:()=>W(xe=>{let we=[...xe];return we.length>0&&(we[we.length-1].memoryUpdated=!0),we}),onBackgroundIncrement:()=>Ue(xe=>xe+1)});continue}if(H.type==="visual_feedback"){W(xe=>[...xe,{id:"feedback-"+Date.now(),role:"system",text:H.content,isVisualFeedback:!0}]);continue}if(H.type==="exec_start")continue;if(H.type==="liveTokens"){rt({tokens:H.content});continue}if(H.type==="usage"){let xe=H.content.totalTokenCount||0,we=H.content.cachedContentTokenCount||0,Ke=H.content.candidatesTokenCount||0;rt({tokens:xe}),Bt(ut=>ut+xe),we>0&&go(ut=>ut+we),Ke>0&&pn(ut=>ut+Ke),Et(ut=>ut+1);continue}if(H.type==="tool_time"){ea(xe=>xe+H.content);continue}if(H.type==="tool_result"){if(W(xe=>[...xe,{id:"tool-"+Date.now(),role:"system",text:H.content,fullText:H.aiContent,binaryPart:H.binaryPart,toolName:H.toolName}]),H.toolName==="update_file"&&H.aiContent){let xe=H.aiContent.split(`
588
+ `),we=0,Ke=0,ut=!1;for(let Ct of xe){if(Ct.includes("[DIFF_START]")){ut=!0;continue}if(Ct.includes("[DIFF_END]")){ut=!1;continue}ut&&(/^\+\d+/.test(Ct)?we++:/^\-\d+/.test(Ct)&&Ke++)}bs+=we,Cs+=Ke,Eo("linesAdded",we),Eo("linesRemoved",Ke)}else if(H.toolName==="write_file"&&H.aiContent){let xe=H.aiContent.match(/- Stats: \[(\d+) lines/),we=xe?parseInt(xe[1]):0,Ke=0;if(H.aiContent.includes("Old File contents:")){let ut=H.aiContent.split(`
589
+ `),Ct=!1;for(let oo of ut){if(oo.includes("Old File contents:")){Ct=!0;continue}Ct&&(oo.trim()===""?Ct=!1:/^\d+ \|/.test(oo)&&Ke++)}}bs+=we,Cs+=Ke,Eo("linesAdded",we),Eo("linesRemoved",Ke)}continue}let ue=H.content,pe=ue.toLowerCase();if(ue.includes("```")&&(Tt=!Tt),pe.includes("tool:functions.")&&(Mt=!0,vt=0,yo=null,ue.includes("[tool:functions.")&&(vt=0)),Mt){for(let xe=0;xe<ue.length;xe++){let we=ue[xe];!yo&&(we==="'"||we==='"'||we==="`")?yo=we:yo&&we===yo&&ue[xe-1]!=="\\"&&(yo=null),yo||(we==="("||we==="["?vt++:(we===")"||we==="]")&&vt--)}vt<=0&&!yo&&(Mt=!1)}if((pe.includes("<think")||pe.includes("<thought"))&&(!le&&!Tt&&!Mt&&!Jn)&&(le=!0,Jn=!0,ue=ue.replace(/<(think|thought)>[\s\S]*?<\/(think|thought)>/gi,"").replace(/<(think|thought)>/gi,""),Ne="think-"+Date.now(),W(xe=>[...xe,{id:Ne,role:"think",text:"",isStreaming:!0,startTime:Date.now()}])),(pe.includes("</think>")||pe.includes("</thought>"))&&Ne){let xe=ue.split(/<\/(think|thought)>/gi),we=xe[0]||"",Ke=xe.slice(2).join("").replace(/<\/?(think|thought)>/gi,"");W(ut=>{let Ct=ut.map(oo=>{if(oo.id===Ne&&typeof oo.id=="string"){let Hr=oo.startTime||parseInt(oo.id.split("-")[1])||Date.now(),Fs=Date.now()-Hr;return{...oo,text:oo.text+we,isStreaming:!1,duration:Fs}}return oo});return le=!1,Me="agent-"+Date.now(),[...Ct,{id:Me,role:"agent",text:Ke,isStreaming:!0}]});continue}if(le&&Ne)W(xe=>{let we=!1,Ke="",ut=xe.map(Ct=>{if(Ct.id===Ne){let oo=Ct.text+ue;if(oo.toLowerCase().includes("</think>")){we=!0;let Hr=oo.split(/<\/think>/gi);Ke=Hr.slice(1).join("</think>")||"";let Fs=Ct.startTime||parseInt(Ct.id.split("-")[1])||Date.now(),fc=Date.now()-Fs;return{...Ct,text:Hr[0],isStreaming:!1,duration:fc}}return{...Ct,text:oo,isStreaming:!0}}return Ct});return we?(le=!1,Me="agent-"+Date.now(),[...ut,{id:Me,role:"agent",text:Ke.replace(/<\/?(think|thought)>/gi,""),isStreaming:!0}]):ut});else if(!le){let xe=ue.toLowerCase();!to&&xe.includes("tool:functions.")&&(to=!0),Me?W(we=>we.map(Ke=>Ke.id===Me?{...Ke,text:Ke.text+ue,isStreaming:!0}:Ke)):(Me="agent-"+Date.now(),W(we=>[...we,{id:Me,role:"agent",text:ue,isStreaming:!0}]))}}let Sr=Date.now();fr(H=>H+(Sr-L))}catch(j){W(q=>(te(q.length+1),[...q,{id:"error-"+Date.now(),role:"system",text:`\u274C ERROR: ${j.message}`}]))}finally{if(xr(!1),gr(null),C||process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow | Idle\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow | Idle\x07")),Co.current){bo(Co.current),Ft(null);let j=Co.current;Co.current=null,W(q=>{let ce=[...q],le=ce.reverse().find(Ne=>Ne.text?.includes("[STEERING HINT: QUEUED]"));return le&&(le.text=le.text.replace("[STEERING HINT: QUEUED]","[STEERING HINT: FINISHED_TURN]")),ce.reverse()}),X("resolution")}W(j=>{let q=Date.now()-L,ce=!1,le=[...j].reverse().map(Me=>{let Tt=Me.isStreaming?{...Me,isStreaming:!1}:Me;return!ce&&Tt.role==="agent"&&(ce=!0,Tt={...Tt,workedDuration:q}),Tt}).reverse(),Ne=le.filter(Me=>!String(Me.id).startsWith("welcome")&&!Me.isMeta);return us(We,null,Ne),te(le.length),le})}})()}u(""),a(!1)}},Ae=Ur(()=>{if(l.startsWith("/")&&!I){let D=l.split(" "),_=D[D.length-1].toLowerCase();if(D.length===1){let $=_.startsWith("/")?_.slice(1):_;return Je.filter(R=>(R.cmd.startsWith("/")?R.cmd.slice(1):R.cmd).toLowerCase().includes($))}let M=Je;for(let $=0;$<D.length-1;$++){let R=D[$].toLowerCase(),C=M.find(L=>L.cmd.toLowerCase()===R);if(C&&C.subs)M=C.subs;else return[]}return M.filter($=>$.cmd.toLowerCase().includes(_))}let x=l.split(" "),g=x[x.length-1];if(g&&g.startsWith("@")&&!I){let D=g.indexOf("#"),_=D!==-1,M=_?g.substring(1,D).toLowerCase():g.slice(1).toLowerCase(),$=_?g.substring(D):"";return Zu(process.cwd()).filter(L=>L.name.toLowerCase().includes(M)).map(L=>{let B=L.relativePath.replace(/\\/g,"/");return{cmd:"@["+(B.startsWith(".")?B:"./"+B)+$+"]",desc:L.relativePath}})}return[]},[l,I]);io(()=>{T(0)},[Ae]);let At=()=>{switch(Qt){case"settings":return i.createElement(Ks,{systemSettings:Ht,setSystemSettings:ee,apiTier:He,setActiveView:X,setInputConfig:vo,saveSettings:wn,quotas:Zt,setMessages:W,aiProvider:N});case"selectProvider":return i.createElement(fo,{title:"SELECT AI PROVIDER",items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA [EXPERIMENTAL]",value:"NVIDIA"},{label:"Back",value:"settings"}],onSelect:async x=>{if(x.value==="settings"||x.value==="Back"){X("settings");return}let g=x.value,D=await Jr(g);if(D){J(g),ze(D),Br(D,{aiProvider:g,onIDEApproval:Ln});let _="gemma-4-31b-it";g==="OpenRouter"?_="google/gemma-4-31b-it:free":g==="DeepSeek"?_="deepseek-v4-flash":g==="NVIDIA"&&(_="moonshotai/kimi-k2.6"),Be(_),wn({aiProvider:g,activeModel:_,apiTier:He,quotas:Zt}),W(M=>[...M,{role:"system",text:`\u2705 Switched to ${g}! Key loaded from Vault. Model set to ${_}.`,isMeta:!0}]),X("settings")}else vo({label:`Enter ${g} API Key:`,key:"providerKey",provider:g,value:"",returnView:"settings"}),X("input")},onClose:()=>X("settings")});case"apiTier":return i.createElement(fo,{title:i.createElement(y,null,"SELECT YOUR CURRENT API TIER BASED ON ",i.createElement(y,{color:"cyan",underline:!0,bold:!0},"\x1B]8;;https://aistudio.google.com/projects\x07AI STUDIO\x1B]8;;\x07"),". (CURRENT: ",He.toUpperCase(),")"),items:[{label:"Free Tier (Gemini API Free Tier)",value:"Free"},{label:"Paid Tier (API with Billing Account)",value:"Paid"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){X("settings");return}let g=x.value;Rr(g),g==="Paid"?(vo({label:"Enter Agent daily budget (requests made):",key:"quotas",subKey:"agentLimit",value:String(Zt.agentLimit)}),X("input")):(wn({apiTier:g,quotas:Zt}),X("settings"))},onClose:()=>X("settings")});case"input":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0},"\u{1F527} DATA CONFIGURATION")),gt?.note&&i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",dimColor:!0,italic:!0},gt.note)),i.createElement(k,{paddingX:1,flexDirection:"row"},i.createElement(y,{color:"cyan",bold:!0},gt?.label," "),i.createElement(nc,{value:gt?.value||"",onChange:x=>vo(g=>({...g,value:x})),onSubmit:async x=>{let{key:g,subKey:D,next:_}=gt,M={...Zt},$={};if(g==="quotas"){let R=D.toLowerCase().includes("limit")?parseInt(x)||0:x;M[D]=R,Kn(M),$.quotas=M}else if(g==="activeModel")Be(x),$.activeModel=x;else if(g==="janitorModel")Ge(x),$.janitorModel=x;else if(g==="autoApproveCommands"||g==="autoDisallowCommands"||g==="alwaysAskCommands"){let R={...Ht,[g]:x.trim(),sandboxPreset:"Custom"};ee(R),$.systemSettings=R}else if(g==="externalDataPath"){let R={...Ht,useExternalData:!0,externalDataPath:x.trim()};ee(R),$.systemSettings=R,W(C=>[...C,{id:Date.now(),role:"system",text:"\u{1F4C1} [EXTERNAL STORAGE] Flux Flow will use "+x.trim()+" for data after restart."}])}else if(g==="imageSettings"){let R=x.trim();if(R.startsWith("sk_")){let C={...fe,apiKey:R};ge(C),$.imageSettings=C,W(L=>(te(L.length+1),[...L,{id:Date.now(),role:"system",text:"\u{1F511} [IMAGE KEY] Custom API key saved successfully.",isMeta:!0}]))}else ge(C=>({...C,keyType:"Default"})),$.imageSettings={...fe,keyType:"Default"},W(C=>(te(C.length+1),[...C,{id:Date.now(),role:"system",text:"\u274C [IMAGE KEY ERROR] API key must start with sk_. Key strategy reset to Default.",isMeta:!0}]))}else if(g==="providerKey"){let R=x.trim(),C=gt.provider;await Qr(C,R),J(C),ze(R),Br(R,{aiProvider:C,onIDEApproval:Ln});let L="gemma-4-31b-it";C==="OpenRouter"?L="google/gemma-4-31b-it:free":C==="DeepSeek"?L="deepseek-v4-flash":C==="NVIDIA"&&(L="moonshotai/kimi-k2.6"),Be(L),$.aiProvider=C,$.activeModel=L,W(B=>(te(B.length+1),[...B,{id:Date.now(),role:"system",text:`\u2705 ${C} API Key saved successfully! Model set to ${L}.`,isMeta:!0}]))}_?vo(_(g==="quotas"?M:x)):(wn({...$,apiTier:He,quotas:M,imageSettings:$.imageSettings||fe}),vo(null),X(gt?.returnView||"settings"))}})),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Press Enter to confirm selection)")));case"stats":return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,width:Math.min(100,(r?.columns||100)-2)},i.createElement(k,{marginBottom:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"SESSION TELEMETRY")),i.createElement(k,{flexDirection:"column"},i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Session Duration:")),i.createElement(y,{color:"white"},en(Date.now()-Zi))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},Bo)),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},en(mr))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},en(Vn))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},xt)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-yt))),st>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(st))),yt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(yt)))),pr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},pr)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((On||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes (Sess):")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",bs)," ",i.createElement(y,{color:"red"},"-",Cs))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls (Sess):")),i.createElement(y,{color:"white"},et+Xt+Uo," ( "),i.createElement(y,{color:"green"},"\u2713 ",et),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",Uo),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",Xt),i.createElement(y,{color:"white"}," )"))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"DAILY USAGE TRACKER"),i.createElement(k,{marginTop:1},i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Wall Time Today:")),i.createElement(y,{color:"white"},Fn(se?.duration||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Agent Interactions:")),i.createElement(y,{color:"white"},se?.agent||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Background Tasks:")),i.createElement(y,{color:"white"},se?.background||0)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tokens Used Today:")),i.createElement(y,{color:"white"},so(se?.tokens||0))),(se?.tokens||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so((se?.tokens||0)-(se?.candidateTokens||0)))),(se?.cachedTokens||0)>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:21},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(se.cachedTokens))),(se?.candidateTokens||0)>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:23},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(se.candidateTokens)))),(se?.imageCalls?.length||0)>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Images Made Today:")),i.createElement(y,{color:"white"},se.imageCalls.length)),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Image Credits Today:")),i.createElement(y,{color:"white"},Number(((se.imageCalls.reduce((x,g)=>x+g.cost,0)||0)*1e3).toFixed(0))," credits"))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Code Changes Today:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",se?.linesAdded||0)," ",i.createElement(y,{color:"red"},"-",se?.linesRemoved||0))),i.createElement(k,null,i.createElement(k,{width:25},i.createElement(y,{color:"blue"},"Tool Calls Today:")),i.createElement(y,{color:"white"},(se?.toolSuccess||0)+(se?.toolFailure||0)+(se?.toolDenied||0)," ( "),i.createElement(y,{color:"green"},"\u2713 ",se?.toolSuccess||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"yellow"},"\u2298 ",se?.toolDenied||0),i.createElement(y,{color:"white"}," "),i.createElement(y,{color:"red"},"\u2715 ",se?.toolFailure||0),i.createElement(y,{color:"white"}," )"))),i.createElement(y,{dimColor:!0,marginTop:1,italic:!0},"(Press ESC to return to chat)"));case"autoExecDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: YOLO MODE"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute terminal commands automatically without requiring your approval for each step."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 The agent may execute destructive commands (rm -rf, etc.) by mistake."),i.createElement(y,null,"\u2022 Unintended system changes if the agent hallucinates a path or command."),i.createElement(y,null,"\u2022 Reduced control over the agent's step-by-step decision making."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&ee(g=>({...g,autoExec:!0})),X("settings")}})));case"externalDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26A0\uFE0F SECURITY WARNING: EXTERNAL WORKSPACE ACCESS"),i.createElement(y,{marginTop:1},"Turning this ON allows the agent to execute tools (Read/Write/Exec) outside of the current active workspace directory."),i.createElement(y,{marginTop:1,color:"yellow"},"RISKS INVOLVED:"),i.createElement(y,null,"\u2022 Access to sensitive system files (SSH keys, Browser data, etc.)"),i.createElement(y,null,"\u2022 Potential for accidental or malicious deletion of OS-critical files."),i.createElement(y,null,"\u2022 Unauthorized script execution across your entire file system."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Confirm Intent",items:[{label:"I know the risk and turning on intentionally",value:"on"},{label:"Keep Off (Recommended)",value:"off"}],onSelect:x=>{x.value==="on"&&ee(g=>({...g,allowExternalAccess:!0})),X("settings")}})));case"doubleDanger":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u26D4 CRITICAL SECURITY WARNING: COMBINED SYSTEM RISK"),i.createElement(y,{marginTop:1},"You are attempting to enable BOTH [YOLO Mode] and [External Workspace Access] simultaneously."),i.createElement(y,{marginTop:1,color:"red",bold:!0},"THIS IS NOT RECOMMENDED."),i.createElement(y,{marginTop:1,color:"yellow"},"THE CRITICAL RISK:"),i.createElement(y,null,"The agent will have the power to execute any command across your entire system WITHOUT your approval or supervision."),i.createElement(y,{color:"red",italic:!0,marginTop:1},"A single hallucination or error could result in full system wipe or data theft."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Final Confirmation",items:[{label:"I agree knowing the consequences",value:"on"},{label:"Keep Off",value:"off"}],onSelect:x=>{x.value==="on"&&ee(g=>({...g,autoExec:!0,allowExternalAccess:!0})),X("settings")}})));case"key":return i.createElement(fo,{title:"\u{1F511} API KEY MANAGEMENT",items:[{label:"Edit Current Key (Update)",value:"edit"},{label:"Remove Current Key (Purge)",value:"remove"},{label:"Cancel",value:"Cancel"}],onSelect:x=>{if(x.value==="edit"){ze(null),X("chat");let g=Oe(2);W(D=>[...D,{id:Date.now(),role:"system",text:`\u{1F511}${g}[ACTION] Flux waiting for new API Key...`}])}else x.value==="remove"?X("deleteKey"):X("chat")}});case"deleteKey":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1},(()=>{let x=Oe(2);return i.createElement(y,{color:"red",bold:!0},"\u26D4",x,"DANGER: PURGE API KEY")})(),i.createElement(y,{marginTop:1},"This will permanently delete the saved API key from the project vault. You will need to enter it again to use Flux."),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Are you absolutely sure?",items:[{label:"YES, PURGE KEY",value:"yes"},{label:"NO, GO BACK",value:"no"}],onSelect:async x=>{if(x.value==="yes"){await Ps(),ze(null),X("chat");let g=Oe(2);W(D=>[...D,{id:Date.now(),role:"system",text:`\u2728${g}[VAULT PURGED] API Key removed successfully.`}])}else X("key")}})));case"exit":return null;case"ask":return i.createElement(k,{width:"100%"},i.createElement(Da,{question:Zo?.question,options:Zo?.options,onResolve:x=>{Zo?.resolve&&Zo.resolve(x),qn(null),X("chat")}}));case"revert":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Ji,{prompts:lt,onSelect:async x=>{try{let g=await kt.rollbackToBefore(x);if(g.success){let{targetPrompt:D}=g,_=Fe.findIndex(C=>C.role==="user"&&C.text&&(C.text.startsWith(D)||C.text.includes(D))),M=[...Fe];_!==-1&&(M=Fe.slice(0,_)),W(M),te(M.length),u(D),a(D.split(`
590
+ `).length>2);let $=M.filter(C=>!String(C.id).startsWith("welcome")&&!C.isMeta);await us(We,null,$);let R=Oe(2);W(C=>{let L=[...C,{id:"revert-ok-"+Date.now(),role:"system",text:`\u{1F504}${R}[TIME TRAVEL] Codebase rolled back successfully! Reverted prompt loaded to input box.`,isMeta:!0}];return te(L.length),L}),X("chat")}}catch(g){let D=Oe(2);W(_=>{let M=[..._,{id:"revert-err-"+Date.now(),role:"system",text:`\u274C${D}[TIME TRAVEL ERROR] Failed to rollback: ${g.message}`,isMeta:!0}];return te(M.length),M}),X("chat")}},onClose:()=>X("chat")}));case"resume":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Hi,{onSelect:async x=>{let g=await _o();if(g[x]){r.write("\x1B[2J\x1B[3J\x1B[H"),at(x);let D=[...g[x].messages];D[0]?.text?.includes("\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")||D.unshift({id:"welcome-"+Date.now(),role:"system",text:dr+`
591
591
 
592
- \u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),W(O),H("chat"),W(M=>{let $=[...M,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${x}]`,isMeta:!0}];return ee($.length),$})}},onDelete:async x=>await ti(x),onClose:()=>H("chat")}));case"memory":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Xi,{onClose:()=>H("chat")}));case"parserDownload":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Ki,{onClose:()=>H("settings")}));case"profile":return i.createElement(zs,{initialData:ve,onSave:x=>{st(x),W(g=>[...g,{id:Date.now(),role:"system",text:`\u2705 Profile updated: ${x.name} (${x.nickname})`}]),H("chat")},onCancel:()=>H("chat")});case"resolution":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Vu,{data:Yo,onResolve:x=>{on(null),H("chat"),setTimeout(()=>{wt(x,!0)},500)},onEdit:x=>{on(null),H("chat"),u(x)}}));case"approval":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: FILE WRITE PERMISSION"),i.createElement(y,{marginTop:1},"The agent is attempting to modify: ",i.createElement(y,{color:"cyan"},ne(Ft?.args||"{}").path||"Unknown File")),Vo()?i.createElement(k,{marginTop:1,paddingX:1},i.createElement(y,{color:"cyan",italic:!0},"\u26A1\uFE0F FluxFlow Companion is active. Review the changes in your editor.")):i.createElement(k,{marginTop:1,borderStyle:"single",borderColor:"#333",paddingX:1,flexDirection:"column"},i.createElement(y,{color:"gray"},"--- PROPOSED CONTENT / DIFF ---"),(()=>{let x=ne(Ft?.args||"{}"),g=[],O=new Set;if(Object.keys(x).forEach($=>{let U=$.match(/^(replaceContent|newContent|content_to_replace|content_to_add|TargetContent|ReplacementContent|replacementContent)(\d+)?$/);if(U){let E=U[2]?parseInt(U[2]):1;O.add(E)}}),Array.from(O).sort(($,U)=>$-U).forEach($=>{let U,E;$===1?(U=x.replaceContent1??x.content_to_replace1??x.replaceContent??x.content_to_replace??x.TargetContent??null,E=x.newContent1??x.content_to_add1??x.newContent??x.content_to_add??x.ReplacementContent??x.replacementContent??null):(U=x[`replaceContent${$}`]??x[`content_to_replace${$}`]??null,E=x[`newContent${$}`]??x[`content_to_add${$}`]??null),(U!==null||E!==null)&&g.push({replace:U,new:E})}),g.length>0)return i.createElement(k,{flexDirection:"column",marginTop:1},g.map(($,U)=>{let E=$.replace!==null,D=$.new!==null;return i.createElement(k,{key:U,flexDirection:"column",marginTop:U>0?1:0},g.length>1&&i.createElement(y,{color:"gray"},"Block ",U+1,":"),E&&i.createElement(k,null,i.createElement(y,{color:"red",wrap:"anywhere",bold:!0},"- ",$.replace)),D&&i.createElement(k,{marginTop:E?1:0},i.createElement(y,{color:"green",wrap:"anywhere",bold:!0},"+ ",$.new.replace(/\[\/n\]?/g,"\\n"))))}));let M=x.content||x.ReplacementContent||x.content_to_add||x.replacementContent||x.newContent||null;return i.createElement(y,{color:"white",wrap:"anywhere"},(M?M.replace(/\[\/n\]?/g,"\\n"):null)||"Updating file content...")})()),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Action Required",items:[{label:"\u2705 Accept this time",value:"allow"},{label:"\u{1F510} Accept for this session",value:"always"},{label:"\u274C Don't accept",value:"deny"}],onSelect:x=>{x.value==="always"&&Re(!0);let g=x.value==="deny"?"deny":"allow";Ft.resolve(g),Uo(null),H("chat")}})));case"updateManager":return i.createElement(fo,{title:"Select Preferred Update Manager",subtitle:"NOTE: If you are unsure about these, go with NPM",items:[{label:"NPM (Standard)",value:"npm"},{label:"PNPM (Recommended)",value:"pnpm"},{label:"BUN (Ultra Fast)",value:"bun"},{label:"YARN (Classic)",value:"yarn"},{label:"Custom Command",value:"custom"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){H("settings");return}x.value==="custom"?(Oo({label:"Enter Custom Update Command (Global install recommended):",key:"customUpdateCommand",value:Yt.customUpdateCommand,next:g=>(te(O=>({...O,updateManager:"custom",customUpdateCommand:g})),null)}),H("input")):(te(g=>({...g,updateManager:x.value})),H("settings"))}});case"update":return i.createElement(Gl,{latest:Le,current:Pn,settings:Yt,onClose:()=>H("chat"),onSuccess:()=>{W(x=>(ee(x.length+1),[...x,{id:"update-success-"+Date.now(),role:"system",text:`\u2728 **[UPDATE COMPLETED]** Flux Flow successfully upgraded to v${Le}.
593
- \u{1F680} **Restart Flux Flow to see changes.**`,isMeta:!0}])),H("chat")},onUpdateSettings:x=>{H("updateManager")}});case"terminalApproval":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: TERMINAL COMMAND OVERSIGHT"),i.createElement(k,{marginTop:1},i.createElement(y,null,"Agent requested to run: ",i.createElement(y,{color:"yellow",bold:!0},ne(Ft?.args||"{}").command||"Unknown Command"))),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Risk Assessment Required",items:[{label:"\u{1F680} Run",value:"allow"},{label:"\u274C Deny",value:"deny"}],onSelect:x=>{Ft.resolve(x.value),Uo(null),H("chat")}})));default:return i.createElement(k,{flexDirection:"column",marginTop:1,flexShrink:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(k,null,zn?i.createElement(k,null,Sr&&!Sr&&i.createElement(qu,null),i.createElement(y,{color:"magenta",bold:!0,italic:!0},Sr&&!Sr?" ":"",zn.toUpperCase()),wr&&i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ",wr)):i.createElement(y,{color:"cyan",dimColor:!0,italic:!0}," ",l.length>0&&J?"Press ESC again to clear input":"READY FOR COMMAND...")),i.createElement(k,null,i.createElement(y,{color:"gray",bold:!0},"[ "),i.createElement(y,{color:"white"},Bn||Ye),i.createElement(y,{color:"gray",bold:!0}," ]"))),i.createElement(k,{borderStyle:"round",borderColor:gn?"magenta":"cyan",paddingX:1,paddingY:0,width:"100%"},i.createElement(k,{flexDirection:"column",width:"100%"},i.createElement(k,{flexDirection:"row",width:"100%",paddingY:0},i.createElement(k,{flexShrink:0,width:4},i.createElement(y,{color:gn?"magenta":"cyan",bold:!0},gn?"\u2726 ":"\u{1F4A0} ")),i.createElement(k,{flexGrow:1},i.createElement(k,{flexGrow:1,position:"relative"},l===""&&i.createElement(k,{position:"absolute",paddingLeft:0},Et&&!Zt?i.createElement(y,{color:"yellow"},ie?" Terminal is waiting for user input. Press TAB to interact":" Press TAB to interact with terminal..."):Et&&Zt?i.createElement(y,{color:"yellow",bold:!0}," [ TERMINAL FOCUSED ] Type to interact, press TAB to exit..."):J===1?i.createElement(y,{color:"cyan",bold:!0}," Press ESC again to ",l.length>0?"clear input":"revert codebase to checkpoint","..."):i.createElement(y,{color:"gray"},Wo?" Press ESC again to cancel the request.":gn?" Enter a prompt to steer the agent.":` Send message or /cmd ... (${Ls.shortcut} for newline), @file`)),i.createElement(ua,{key:`input-${f}`,focus:!Zt,showCursor:pt,lastFocusEventTime:Wt.current,value:l,columns:h.columns,onChange:x=>{let g=x.replace(/\r\n/g,`
592
+ \u{1F30A}\u26A1 Resuming Flux Flow Session...`,isMeta:!0}),W(D),X("chat"),W(M=>{let $=[...M,{id:"sys-"+Date.now(),role:"system",text:`\u{1F4E1} SESSION RESUMED: [${x}]`,isMeta:!0}];return te($.length),$})}},onDelete:async x=>await ei(x),onClose:()=>X("chat")}));case"memory":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Ki,{onClose:()=>X("chat")}));case"parserDownload":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Vi,{onClose:()=>X("settings")}));case"profile":return i.createElement(qs,{initialData:ve,onSave:x=>{nt(x),W(g=>[...g,{id:Date.now(),role:"system",text:`\u2705 Profile updated: ${x.name} (${x.nickname})`}]),X("chat")},onCancel:()=>X("chat")});case"resolution":return i.createElement(k,{width:"100%",alignItems:"center",justifyContent:"center"},i.createElement(Ju,{data:_e,onResolve:x=>{bo(null),X("chat"),setTimeout(()=>{Xe(x,!0)},500)},onEdit:x=>{bo(null),X("chat"),u(x)}}));case"approval":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"yellow",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: FILE WRITE PERMISSION"),i.createElement(y,{marginTop:1},"The agent is attempting to modify: ",i.createElement(y,{color:"cyan"},ne(Pe?.args||"{}").path||"Unknown File")),Ko()?i.createElement(k,{marginTop:1,paddingX:1},i.createElement(y,{color:"cyan",italic:!0},"\u26A1\uFE0F FluxFlow Companion is active. Review the changes in your editor.")):i.createElement(k,{marginTop:1,borderStyle:"single",borderColor:"#333",paddingX:1,flexDirection:"column"},i.createElement(y,{color:"gray"},"--- PROPOSED CONTENT / DIFF ---"),(()=>{let x=ne(Pe?.args||"{}"),g=[],D=new Set;if(Object.keys(x).forEach($=>{let R=$.match(/^(replaceContent|newContent|content_to_replace|content_to_add|TargetContent|ReplacementContent|replacementContent)(\d+)?$/);if(R){let C=R[2]?parseInt(R[2]):1;D.add(C)}}),Array.from(D).sort(($,R)=>$-R).forEach($=>{let R,C;$===1?(R=x.replaceContent1??x.content_to_replace1??x.replaceContent??x.content_to_replace??x.TargetContent??null,C=x.newContent1??x.content_to_add1??x.newContent??x.content_to_add??x.ReplacementContent??x.replacementContent??null):(R=x[`replaceContent${$}`]??x[`content_to_replace${$}`]??null,C=x[`newContent${$}`]??x[`content_to_add${$}`]??null),(R!==null||C!==null)&&g.push({replace:R,new:C})}),g.length>0)return i.createElement(k,{flexDirection:"column",marginTop:1},g.map(($,R)=>{let C=$.replace!==null,L=$.new!==null;return i.createElement(k,{key:R,flexDirection:"column",marginTop:R>0?1:0},g.length>1&&i.createElement(y,{color:"gray"},"Block ",R+1,":"),C&&i.createElement(k,null,i.createElement(y,{color:"red",wrap:"anywhere",bold:!0},"- ",$.replace)),L&&i.createElement(k,{marginTop:C?1:0},i.createElement(y,{color:"green",wrap:"anywhere",bold:!0},"+ ",$.new.replace(/\[\/n\]?/g,"\\n"))))}));let M=x.content||x.ReplacementContent||x.content_to_add||x.replacementContent||x.newContent||null;return i.createElement(y,{color:"white",wrap:"anywhere"},(M?M.replace(/\[\/n\]?/g,"\\n"):null)||"Updating file content...")})()),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Action Required",items:[{label:"\u2705 Accept this time",value:"allow"},{label:"\u{1F510} Accept for this session",value:"always"},{label:"\u274C Don't accept",value:"deny"}],onSelect:x=>{x.value==="always"&&xo(!0);let g=x.value==="deny"?"deny":"allow";Pe.resolve(g),Rt(null),X("chat")}})));case"updateManager":return i.createElement(fo,{title:"Select Preferred Update Manager",subtitle:"NOTE: If you are unsure about these, go with NPM",items:[{label:"NPM (Standard)",value:"npm"},{label:"PNPM (Recommended)",value:"pnpm"},{label:"BUN (Ultra Fast)",value:"bun"},{label:"YARN (Classic)",value:"yarn"},{label:"Custom Command",value:"custom"},{label:"Back",value:"settings"}],onSelect:x=>{if(x.value==="settings"||x.value==="Back"){X("settings");return}x.value==="custom"?(vo({label:"Enter Custom Update Command (Global install recommended):",key:"customUpdateCommand",value:Ht.customUpdateCommand,next:g=>(ee(D=>({...D,updateManager:"custom",customUpdateCommand:g})),null)}),X("input")):(ee(g=>({...g,updateManager:x.value})),X("settings"))}});case"update":return i.createElement(Hl,{latest:$e,current:Dn,settings:Ht,onClose:()=>X("chat"),onSuccess:()=>{W(x=>(te(x.length+1),[...x,{id:"update-success-"+Date.now(),role:"system",text:`\u2728 **[UPDATE COMPLETED]** Flux Flow successfully upgraded to v${$e}.
593
+ \u{1F680} **Restart Flux Flow to see changes.**`,isMeta:!0}])),X("chat")},onUpdateSettings:x=>{X("updateManager")}});case"terminalApproval":return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"red",paddingX:2,paddingY:1,width:"100%"},i.createElement(y,{color:"red",bold:!0,underline:!0},"\u{1F510} SECURITY GATE: TERMINAL COMMAND OVERSIGHT"),i.createElement(k,{marginTop:1},i.createElement(y,null,"Agent requested to run: ",i.createElement(y,{color:"yellow",bold:!0},ne(Pe?.args||"{}").command||"Unknown Command"))),i.createElement(k,{marginTop:1},i.createElement(fo,{title:"Risk Assessment Required",items:[{label:"\u{1F680} Run",value:"allow"},{label:"\u274C Deny",value:"deny"}],onSelect:x=>{Pe.resolve(x.value),Rt(null),X("chat")}})));default:return i.createElement(k,{flexDirection:"column",marginTop:1,flexShrink:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(k,null,$n?i.createElement(k,null,Pn&&!Pn&&i.createElement(zu,null),i.createElement(y,{color:"magenta",bold:!0,italic:!0},Pn&&!Pn?" ":"",$n.toUpperCase()),zn&&i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ",zn)):i.createElement(y,{color:"cyan",dimColor:!0,italic:!0}," ",l.length>0&&yr?"Press ESC again to clear input":"READY FOR COMMAND...")),i.createElement(k,null,i.createElement(y,{color:"gray",bold:!0},"[ "),i.createElement(y,{color:"white"},_n||je),i.createElement(y,{color:"gray",bold:!0}," ]"))),i.createElement(k,{borderStyle:"round",borderColor:Do?"magenta":"cyan",paddingX:1,paddingY:0,width:"100%"},i.createElement(k,{flexDirection:"column",width:"100%"},i.createElement(k,{flexDirection:"row",width:"100%",paddingY:0},i.createElement(k,{flexShrink:0,width:4},i.createElement(y,{color:Do?"magenta":"cyan",bold:!0},Do?"\u2726 ":"\u{1F4A0} ")),i.createElement(k,{flexGrow:1},i.createElement(k,{flexGrow:1,position:"relative"},l===""&&i.createElement(k,{position:"absolute",paddingLeft:0},wt&&!It?i.createElement(y,{color:"yellow"},Gr?" Terminal is waiting for user input. Press TAB to interact":" Press TAB to interact with terminal..."):wt&&It?i.createElement(y,{color:"yellow",bold:!0}," [ TERMINAL FOCUSED ] Type to interact, press TAB to exit..."):yr===1?i.createElement(y,{color:"cyan",bold:!0}," Press ESC again to ",l.length>0?"clear input":"revert codebase to checkpoint","..."):i.createElement(y,{color:"gray"},Os?" Press ESC again to cancel the request.":Do?" Enter a prompt to steer the agent.":` Send message or /cmd ... (${Ds.shortcut} for newline), @file`)),i.createElement(ma,{key:`input-${f}`,focus:!It,showCursor:ht,lastFocusEventTime:Nt.current,value:l,columns:h.columns,onChange:x=>{let g=x.replace(/\r\n/g,`
594
594
  `).replace(/\r/g,`
595
595
  `).replace(/\\\s*\n/g,`
596
- `);u(g),L(!1)},onSubmit:wt,maxRows:3,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))))}};return i.createElement(k,{flexDirection:"column",width:"100%"},_?i.createElement(Hu,{width:r?.columns||80,height:r?.rows||24,selectedIndex:v}):i.createElement(i.Fragment,null,i.createElement(k,{flexDirection:"column",width:"100%",flexGrow:1},Hr.items.map((x,g)=>i.createElement(Ys,{key:x.id||g,msg:x,showFullThinking:ue,columns:r?.columns||80}))),i.createElement(k,{flexDirection:"column",padding:1,width:"100%"},(Vt==="chat"||["ask","approval","terminalApproval"].includes(Vt))&&i.createElement(k,{flexDirection:"column",width:"100%"},i.createElement(xa,{messages:$t.slice(Fs),showFullThinking:ue,columns:Math.max(20,(r?.columns||80)-1)}),Et&&i.createElement(k,{marginTop:1},i.createElement(as,{command:Et,output:Qt,isFocused:Zt,isPty:$o}))),ye?i.createElement(k,{borderStyle:"double",borderColor:"magenta",padding:1,flexShrink:0},i.createElement(y,{color:"magenta"},"\u{1F30A} Starting Flux Flow...")):be?wo():i.createElement(k,{borderStyle:"round",borderColor:"gray",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",bold:!0},"\u{1F511}",Ie(2),"API KEY REQUIRED")),i.createElement(k,{paddingX:1,flexDirection:"column"},mt===0?i.createElement(i.Fragment,null,i.createElement(y,null,"Select your Preferred Provider:"),i.createElement(k,{marginTop:1},i.createElement(fo,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"}],onSelect:x=>{z(x.value),ce(1)}}))):i.createElement(i.Fragment,null,i.createElement(y,null,"Please enter your ",B," API Key to initialize the agent (If billing is enabled set Tier to paid in /settings \u2192 other \u2192 API Tier)."),i.createElement(k,{marginTop:1},i.createElement(y,{color:"cyan",bold:!0},"\u{1F4A0} "),i.createElement(oc,{value:Ao,onChange:co,onSubmit:Ae,mask:"*"})),i.createElement(k,{marginTop:1},i.createElement(y,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},mt===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),o&&i.createElement(k,{borderStyle:"round",borderColor:"red",paddingX:2,marginY:0,width:"100%"},i.createElement(y,{color:"red",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),i.createElement(y,{color:"white"},"Press "),i.createElement(y,{color:"red",bold:!0},"CTRL + C"),i.createElement(y,{color:"white"}," again to exit (",n,"s). Press "),i.createElement(y,{color:"cyan",bold:!0},"ESC"),i.createElement(y,{color:"white"}," to cancel.")),i.createElement(k,{flexShrink:0,width:"100%"},i.createElement(wa,{mode:d,thinkingLevel:j,tokens:fe.tokens,tokensTotal:fe.tokens,chatId:Ue,isMemoryEnabled:Yt.memory,apiTier:Ge,aiProvider:B})),Vt==="exit"&&(()=>{let x=Date.now()-Qi,g=ot+Gt,O=g>0?(ot/g*100).toFixed(1):"0.0",N=hr+Vn,M=N>0?(hr/N*100).toFixed(1):"0.0",$=N>0?(Vn/N*100).toFixed(1):"0.0";return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"red",width:Math.min(100,(r?.columns||100)-2),marginTop:0,marginBottom:0},i.createElement(k,{marginBottom:1},i.createElement(y,{bold:!0},sc(["blue","purple"])("Agent powering down. Goodbye!"))),i.createElement(k,{flexDirection:"column"},i.createElement(y,{color:"white",bold:!0,underline:!0},"Interaction Summary"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Session ID:")),i.createElement(y,{color:"white"},Ue)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tool Calls:")),i.createElement(y,{color:"white"},ot+Gt+en," ( ",i.createElement(y,{color:"green"},"\u2713 ",ot)," ",i.createElement(y,{color:"yellow"},"\u2298 ",en)," ",i.createElement(y,{color:"red"},"\u2715 ",Gt)," )")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Success Rate:")),i.createElement(y,{color:"white"},O,"%")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Code Changes:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",ks)," ",i.createElement(y,{color:"red"},"-",Is))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-xt))),at>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:16},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(at))),xt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(xt)))),xr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},xr)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((_n||0)*1e3).toFixed(0))," credits")))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"Performance"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Wall Time:")),i.createElement(y,{color:"white"},Ro(x))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Agent Active:")),i.createElement(y,{color:"white"},Ro(N))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},Ro(hr)," (",M,"%)")),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},Ro(Vn)," (",$,"%)"))))})(),Ce.length>0&&(()=>{let g=Math.max(0,Math.min(T-2,Ce.length-5)),O=Ce.slice(g,g+5),N=Ce.length-(g+O.length);return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:0,paddingY:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(y,{color:"gray",bold:!0,dimColor:!0},Ce[0]?.cmd?.startsWith("@")?"\u{1F4C1} FILE SUGGESTIONS":"\u{1F50D} COMMAND SUGGESTIONS"),Ce[0]?.cmd?.startsWith("@")?i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):l.startsWith("/model")&&Ge==="Free"?(()=>{let M="https://aistudio.google.com/billing",$="billing";return B==="DeepSeek"?(M="https://platform.deepseek.com/usage",$="billing"):B==="OpenRouter"&&(M="https://openrouter.ai/settings/profile",$="profile"),i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",i.createElement(y,{color:"cyan",underline:!0},`\x1B]8;;${M}\x07${$}\x1B]8;;\x07`)," & /settings")})():null),O.map((M,$)=>{let E=g+$===T,D=M.cmd==="gemma-4-31b-it"&&Ge!=="Free";return i.createElement(k,{key:M.cmd,flexDirection:"row",backgroundColor:E?"#2a2a2a":void 0,paddingX:1},i.createElement(k,{width:3},i.createElement(y,{color:E?"cyan":"gray",bold:E},E?" \u276F":" ")),i.createElement(k,{width:55},i.createElement(y,{color:D?"gray":E?"yellow":"white",bold:E,dimColor:D&&!E},M.cmd?.startsWith("@[")&&M.cmd?.endsWith("]")?(()=>{let G=M.cmd.slice(2,-1).split(/[/\\]/);return G[G.length-1]})():M.cmd)),i.createElement(k,{flexGrow:1},i.createElement(y,{color:"gray",italic:!0,dimColor:!E},M.desc)))}),Ce.length>5&&i.createElement(k,{paddingX:1,height:1},N>0?i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ... (",N," more commands available)"):i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})())))}var Ms,ic,Hu,Qi,nc,ks,Is,Xu,ac,Pn,Ku,rc,qu,Vu,pr,zu,Ju,uc=re(async()=>{da();ya();Ta();Sa();await Ia();Ma();Aa();kr();await Bl();os();$r();Ul();Rl();await Hl();Kl();un();ql();Vl();zl();hs();Ws();Xt();Bt();rn();await Dr();ec();Wn();_i();Ms=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let o=t=>{let n=t.toLowerCase();for(let[s,r]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(s)&&String(r).toLowerCase().includes(n))return!0;return!1};return e==="cursor"||process.env.CURSOR_SETTINGS_DIR||o("cursor")?"Cursor":e==="windsurf"||o("windsurf")?"Windsurf":o("antigravity")?"Antigravity":e==="trae"||o("trae")?"Trae":e==="codium"||o("codium")||o("vscode-oss")?"VSCodium":o("positron")?"Positron":e==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||o("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||o("intellij")?"JetBrains":"Terminal"},ic=e=>{let o=e==="VS Code",t=[];return o?(t.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):t.push({label:`Download for ${e} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Continue to CLI only",action:"dismiss"}),t},Hu=({width:e,height:o,selectedIndex:t})=>{let n=Ms(),s=ic(n);return i.createElement(k,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:o},i.createElement(k,{marginBottom:1},i.createElement(y,null,pr)),i.createElement(k,{flexDirection:"column",borderStyle:"double",borderColor:"cyan",paddingX:3,paddingY:1,width:Math.min(80,e-4)},i.createElement(y,{bold:!0,color:"cyan",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),i.createElement(k,{marginY:1,flexDirection:"column",alignItems:"left"},i.createElement(y,null,"You're in ",i.createElement(y,{bold:!0,color:"cyan"},n),", but the ",i.createElement(y,{bold:!0,color:"magenta"},"FluxFlow-CLI Companion")," is not installed."),i.createElement(k,{flexDirection:"column",marginY:1},i.createElement(y,{color:"gray"}," \u2705 Real-time file & cursor tracking"),i.createElement(y,{color:"gray"}," \u2705 Auto-open files created by agent"),i.createElement(y,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),i.createElement(y,{color:"gray"}," \u2705 Direct IDE context sharing"),i.createElement(y,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),i.createElement(y,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),i.createElement(y,{color:"gray"}," \u2705 Live Status in IDE"),i.createElement(y,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),i.createElement(k,{flexDirection:"column",marginTop:1},s.map((r,l)=>i.createElement(k,{key:l},i.createElement(y,{color:t===l?"yellow":"white",bold:t===l},t===l?" \u276F ":" ",r.label)))),i.createElement(k,{marginTop:1,alignItems:"center",justifyContent:"center"},i.createElement(y,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},Qi=Date.now(),nc="https://fluxflow-cli.onrender.com/changelog.html",ks=0,Is=0,Xu=Kn.join(Kn.dirname(Gu(import.meta.url)),"../package.json"),ac=JSON.parse(ao.readFileSync(Xu,"utf8")),Pn=ac.version,Ku=ac.date||"2026-05-20",rc=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],qu=()=>{let[e,o]=V(0);return io(()=>{let t=setInterval(()=>{o(n=>(n+1)%1e3)},33);return()=>clearInterval(t)},[]),i.createElement(y,{color:"magenta"},rc[Math.floor(e/3)%rc.length])},Vu=({data:e,onResolve:o,onEdit:t})=>i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,null,"The agent already finished the task before your hint was consumed.")),i.createElement(k,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},i.createElement(y,{italic:!0,color:"gray"},'"',e,'"')),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"cyan"},"How would you like to proceed?")),i.createElement(k,{marginTop:0},i.createElement(fo,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?o(e):t(e)}}))),pr=sc(["#00ffff","#0077ff","#ff00ff"]).multiline(`\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
596
+ `);u(g),O(!1)},onSubmit:Xe,maxRows:3,keyBindings:{submit:x=>x.return&&!x.shift&&!x.ctrl,newline:x=>x.return&&x.shift||x.return&&x.ctrl}})))))))}};return i.createElement(k,{flexDirection:"column",width:"100%"},P?i.createElement(Ku,{width:r?.columns||80,height:r?.rows||24,selectedIndex:A}):i.createElement(i.Fragment,null,i.createElement(k,{flexDirection:"column",width:"100%",flexGrow:1},jr.items.map((x,g)=>i.createElement(Ws,{key:x.id||g,msg:x,showFullThinking:me,columns:r?.columns||80}))),i.createElement(k,{flexDirection:"column",padding:1,width:"100%"},(Qt==="chat"||["ask","approval","terminalApproval"].includes(Qt))&&i.createElement(k,{flexDirection:"column",width:"100%"},i.createElement(wa,{messages:Fe.slice(wr),showFullThinking:me,columns:Math.max(20,(r?.columns||80)-1)}),wt&&i.createElement(k,{marginTop:1},i.createElement(ss,{command:wt,output:eo,isFocused:It,isPty:$o}))),Se?i.createElement(k,{borderStyle:"double",borderColor:"magenta",padding:1,flexShrink:0},i.createElement(y,{color:"magenta"},"\u{1F30A} Starting Flux Flow...")):be?At():i.createElement(k,{borderStyle:"round",borderColor:"gray",padding:0,flexDirection:"column",flexShrink:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:1},i.createElement(y,{color:"yellow",bold:!0},"\u{1F511}",Oe(2),"API KEY REQUIRED")),i.createElement(k,{paddingX:1,flexDirection:"column"},ft===0?i.createElement(i.Fragment,null,i.createElement(y,null,"Select your Preferred Provider:"),i.createElement(k,{marginTop:1},i.createElement(fo,{items:[{label:"Google (Free/Paid)",value:"Google"},{label:"DeepSeek (Paid)",value:"DeepSeek"},{label:"OpenRouter (Free/Paid) [EXPERIMENTAL]",value:"OpenRouter"},{label:"NVIDIA [EXPERIMENTAL]",value:"NVIDIA"}],onSelect:x=>{J(x.value),de(1)}}))):i.createElement(i.Fragment,null,i.createElement(y,null,"Please enter your ",N," API Key to initialize the agent (If billing is enabled set Tier to paid in /settings \u2192 other \u2192 API Tier)."),i.createElement(k,{marginTop:1},i.createElement(y,{color:"cyan",bold:!0},"\u{1F4A0} "),i.createElement(nc,{value:Mo,onChange:co,onSubmit:ie,mask:"*"})),i.createElement(k,{marginTop:1},i.createElement(y,{color:"gray",italic:!0},"(Press ESC to go back to provider selection)")))),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"gray",dimColor:!0,italic:!0},ft===0?"(Use arrows to select and Enter to confirm)":"(Press Enter to confirm and initialize)"))),o&&i.createElement(k,{borderStyle:"round",borderColor:"red",paddingX:2,marginY:0,width:"100%"},i.createElement(y,{color:"red",bold:!0},"\u{1F534} EXIT CONFIRMATION: "),i.createElement(y,{color:"white"},"Press "),i.createElement(y,{color:"red",bold:!0},"CTRL + C"),i.createElement(y,{color:"white"}," again to exit (",n,"s). Press "),i.createElement(y,{color:"cyan",bold:!0},"ESC"),i.createElement(y,{color:"white"}," to cancel.")),i.createElement(k,{flexShrink:0,width:"100%"},i.createElement(Sa,{mode:d,thinkingLevel:Y,tokens:he.tokens,tokensTotal:he.tokens,chatId:We,isMemoryEnabled:Ht.memory,apiTier:He,aiProvider:N})),Qt==="exit"&&(()=>{let x=Date.now()-Zi,g=et+Xt,D=g>0?(et/g*100).toFixed(1):"0.0",_=mr+Vn,M=_>0?(mr/_*100).toFixed(1):"0.0",$=_>0?(Vn/_*100).toFixed(1):"0.0";return i.createElement(k,{flexDirection:"column",borderStyle:"round",paddingX:3,paddingY:1,borderColor:"red",width:Math.min(100,(r?.columns||100)-2),marginTop:0,marginBottom:0},i.createElement(k,{marginBottom:1},i.createElement(y,{bold:!0},ic(["blue","purple"])("Agent powering down. Goodbye!"))),i.createElement(k,{flexDirection:"column"},i.createElement(y,{color:"white",bold:!0,underline:!0},"Interaction Summary"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Session ID:")),i.createElement(y,{color:"white"},We)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tool Calls:")),i.createElement(y,{color:"white"},et+Xt+Uo," ( ",i.createElement(y,{color:"green"},"\u2713 ",et)," ",i.createElement(y,{color:"yellow"},"\u2298 ",Uo)," ",i.createElement(y,{color:"red"},"\u2715 ",Xt)," )")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Success Rate:")),i.createElement(y,{color:"white"},D,"%")),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Code Changes:")),i.createElement(y,{color:"white"},i.createElement(y,{color:"green"},"+",bs)," ",i.createElement(y,{color:"red"},"-",Cs))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Tokens Consumed:")),i.createElement(y,{color:"white"},so(ae))),ae>0&&i.createElement(i.Fragment,null,i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Input Tokens:")),i.createElement(y,{color:"white"},so(ae-yt))),st>0&&i.createElement(k,{marginLeft:4},i.createElement(k,{width:16},i.createElement(y,{color:"grey"},"\xBB Cached:")),i.createElement(y,{color:"white"},so(st))),yt>0&&i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Output Tokens:")),i.createElement(y,{color:"white"},so(yt)))),pr>0&&i.createElement(i.Fragment,null,i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Images Made:")),i.createElement(y,{color:"white"},pr)),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Image Credits:")),i.createElement(y,{color:"white"},Number(((On||0)*1e3).toFixed(0))," credits")))),i.createElement(k,{flexDirection:"column",marginTop:1},i.createElement(y,{color:"white",bold:!0,underline:!0},"Performance"),i.createElement(k,{marginTop:1},i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Wall Time:")),i.createElement(y,{color:"white"},en(x))),i.createElement(k,null,i.createElement(k,{width:20},i.createElement(y,{color:"blue"},"Agent Active:")),i.createElement(y,{color:"white"},en(_))),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB API Time:")),i.createElement(y,{color:"white"},en(mr)," (",M,"%)")),i.createElement(k,{marginLeft:2},i.createElement(k,{width:18},i.createElement(y,{color:"grey"},"\xBB Tool Time:")),i.createElement(y,{color:"white"},en(Vn)," (",$,"%)"))))})(),Ae.length>0&&(()=>{let g=Math.max(0,Math.min(w-2,Ae.length-5)),D=Ae.slice(g,g+5),_=Ae.length-(g+D.length);return i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:0,paddingY:0,width:"100%"},i.createElement(k,{paddingX:1,marginBottom:0,justifyContent:"space-between",width:"100%"},i.createElement(y,{color:"gray",bold:!0,dimColor:!0},Ae[0]?.cmd?.startsWith("@")?"\u{1F4C1} FILE SUGGESTIONS":"\u{1F50D} COMMAND SUGGESTIONS"),Ae[0]?.cmd?.startsWith("@")?i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"(Use '#Lstart-Lend' to specify line numbers)"):l.startsWith("/model")&&He==="Free"?(()=>{let M="https://aistudio.google.com/billing",$="billing";return N==="DeepSeek"?(M="https://platform.deepseek.com/usage",$="billing"):N==="OpenRouter"?(M="https://openrouter.ai/settings/profile",$="profile"):N==="NVIDIA"&&(M="https://build.nvidia.com/settings/api-keys",$="billing"),i.createElement(y,{color:"gray",dimColor:!0,italic:!0},"Paid API has more models. Configure ",i.createElement(y,{color:"cyan",underline:!0},`\x1B]8;;${M}\x07${$}\x1B]8;;\x07`)," & /settings")})():null),D.map((M,$)=>{let C=g+$===w,L=M.cmd==="gemma-4-31b-it"&&He!=="Free";return i.createElement(k,{key:M.cmd,flexDirection:"row",backgroundColor:C?"#2a2a2a":void 0,paddingX:1},i.createElement(k,{width:3},i.createElement(y,{color:C?"cyan":"gray",bold:C},C?" \u276F":" ")),i.createElement(k,{width:55},i.createElement(y,{color:L?"gray":C?"yellow":"white",bold:C,dimColor:L&&!C},M.cmd?.startsWith("@[")&&M.cmd?.endsWith("]")?(()=>{let j=M.cmd.slice(2,-1).split(/[/\\]/);return j[j.length-1]})():M.cmd)),i.createElement(k,{flexGrow:1},i.createElement(y,{color:"gray",italic:!0,dimColor:!C},M.desc)))}),Ae.length>5&&i.createElement(k,{paddingX:1,height:1},_>0?i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," ... (",_," more commands available)"):i.createElement(y,{color:"gray",dimColor:!0,italic:!0}," (End of list)")))})())))}var ks,ac,Ku,Zi,rc,bs,Cs,Vu,lc,Dn,qu,sc,zu,Ju,dr,Qu,Zu,dc=re(async()=>{fa();Ta();Ea();ba();await Ma();va();Oa();kr();await Ul();es();$r();Rl();Wl();await Xl();Vl();un();ql();zl();Jl();fs();Rs();qt();Yt();rn();await Or();tc();Rn();Pi();ks=()=>{let e=(process.env.TERM_PROGRAM||"").toLowerCase();if(process.env.WT_SESSION)return"Windows Terminal";let o=t=>{let n=t.toLowerCase();for(let[s,r]of Object.entries(process.env))if(!["PATH","PWD","CWD","PS1","LS_COLORS","PROMPT"].includes(s)&&String(r).toLowerCase().includes(n))return!0;return!1};return e==="cursor"||process.env.CURSOR_SETTINGS_DIR||o("cursor")?"Cursor":e==="windsurf"||o("windsurf")?"Windsurf":o("antigravity")?"Antigravity":e==="trae"||o("trae")?"Trae":e==="codium"||o("codium")||o("vscode-oss")?"VSCodium":o("positron")?"Positron":e==="vscode"||process.env.VSCODE_GIT_IPC_HANDLE||o("vscode")?"VS Code":process.env.INTELLIJ_TERMINAL_COMMAND_BLOCKS||o("intellij")?"JetBrains":"Terminal"},ac=e=>{let o=e==="VS Code",t=[];return o?(t.push({label:"Install Manually (VSIX)",url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Install from VS Code Marketplace",url:"https://marketplace.visualstudio.com/items?itemName=fluxflow-cli.fluxflow-cli-companion"})):t.push({label:`Download for ${e} (GitHub)`,url:"https://github.com/KushalRoyChowdhury/fluxflow-cli/releases"}),t.push({label:"Continue to CLI only",action:"dismiss"}),t},Ku=({width:e,height:o,selectedIndex:t})=>{let n=ks(),s=ac(n);return i.createElement(k,{flexDirection:"column",alignItems:"center",justifyContent:"center",width:e,height:o},i.createElement(k,{marginBottom:1},i.createElement(y,null,dr)),i.createElement(k,{flexDirection:"column",borderStyle:"double",borderColor:"cyan",paddingX:3,paddingY:1,width:Math.min(80,e-4)},i.createElement(y,{bold:!0,color:"cyan",textAlign:"center"},"\u{1F680} UPGRADE YOUR WORKFLOW"),i.createElement(k,{marginY:1,flexDirection:"column",alignItems:"left"},i.createElement(y,null,"You're in ",i.createElement(y,{bold:!0,color:"cyan"},n),", but the ",i.createElement(y,{bold:!0,color:"magenta"},"FluxFlow-CLI Companion")," is not installed."),i.createElement(k,{flexDirection:"column",marginY:1},i.createElement(y,{color:"gray"}," \u2705 Real-time file & cursor tracking"),i.createElement(y,{color:"gray"}," \u2705 Auto-open files created by agent"),i.createElement(y,{color:"gray"}," \u2705 Native DIFF viewer for AI edits"),i.createElement(y,{color:"gray"}," \u2705 Direct IDE context sharing"),i.createElement(y,{color:"gray"}," \u2705 Surgical Diagnostic Sync"),i.createElement(y,{color:"gray"}," \u2705 Native Right-Click \u276F Chat integration"),i.createElement(y,{color:"gray"}," \u2705 Live Status in IDE"),i.createElement(y,{color:"gray"}," \u2705 Clickable terminal-to-code links"))),i.createElement(k,{flexDirection:"column",marginTop:1},s.map((r,l)=>i.createElement(k,{key:l},i.createElement(y,{color:t===l?"yellow":"white",bold:t===l},t===l?" \u276F ":" ",r.label)))),i.createElement(k,{marginTop:1,alignItems:"center",justifyContent:"center"},i.createElement(y,{dimColor:!0,italic:!0},"(Use arrows to navigate, Enter to select)"))))},Zi=Date.now(),rc="https://fluxflow-cli.onrender.com/changelog.html",bs=0,Cs=0,Vu=Xn.join(Xn.dirname(Xu(import.meta.url)),"../package.json"),lc=JSON.parse(ao.readFileSync(Vu,"utf8")),Dn=lc.version,qu=lc.date||"2026-05-20",sc=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],zu=()=>{let[e,o]=z(0);return io(()=>{let t=setInterval(()=>{o(n=>(n+1)%1e3)},33);return()=>clearInterval(t)},[]),i.createElement(y,{color:"magenta"},sc[Math.floor(e/3)%sc.length])},Ju=({data:e,onResolve:o,onEdit:t})=>i.createElement(k,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:0,width:"100%"},i.createElement(k,{paddingX:1},i.createElement(y,{color:"magenta",bold:!0,underline:!0},"\u{1F7E3} STEERING HINT RESOLUTION")),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,null,"The agent already finished the task before your hint was consumed.")),i.createElement(k,{marginTop:1,backgroundColor:"#222",paddingX:2,width:"100%"},i.createElement(y,{italic:!0,color:"gray"},'"',e,'"')),i.createElement(k,{paddingX:1,marginTop:1},i.createElement(y,{color:"cyan"},"How would you like to proceed?")),i.createElement(k,{marginTop:0},i.createElement(fo,{title:"Select Action",items:[{label:"Send Anyway",value:"send"},{label:"Edit Prompt",value:"edit"}],onSelect:n=>{n==="send"?o(e):t(e)}}))),dr=ic(["#00ffff","#0077ff","#ff00ff"]).multiline(`\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
597
597
  \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551
598
598
  \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551
599
599
  \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551
600
600
  \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D
601
- \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D`),zu=e=>{let o=[],t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n=0,s;for(;(s=t.exec(e))!==null;){let r=s[1],l=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=l;a<e.length;a++){let d=e[a];if(f){if(d===f){let p=0;for(let h=a-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let p=a+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){m=p;break}}}if(m!==-1){let a=e.substring(n,s.index);a.trim()&&o.push({type:"output",content:a});let d=e.substring(l+1,c);o.push({type:"tool",toolName:r.trim(),args:d.trim()}),n=m+1,t.lastIndex=n}else break}if(n<e.length){let r=e.substring(n);r.trim()&&o.push({type:"output",content:r})}return o},Ju=(()=>{let e=null,o=0;return t=>{let n=Date.now();if(e&&n-o<5e3)return e;let s=[],r=l=>{try{let u=ao.readdirSync(l);for(let f of u){if(["node_modules",".git",".gemini","dist","build",".next",".cache","out"].includes(f))continue;let m=Kn.join(l,f);ao.statSync(m).isDirectory()?r(m):s.push({name:f,relativePath:Kn.relative(process.cwd(),m)})}}catch{}};return r(t),e=s,o=n,s}})()});import{spawn as Qu}from"child_process";import{fileURLToPath as dc}from"url";var Zu=4096,ed=dc(import.meta.url).endsWith(".js");if(ed&&!process.execArgv.some(e=>e.includes("max-old-space-size")))Qu(process.execPath,[`--max-old-space-size=${Zu}`,dc(import.meta.url),...process.argv.slice(2)],{stdio:"inherit"}).on("exit",o=>process.exit(o||0));else{let e=process.argv.slice(2),o=e.includes("--help")&&e[e.indexOf("--help")+1]==="commands",t=e.includes("--help")&&!o,n=e.includes("--version")||e.includes("-v"),s=e[0]==="--update";if(n||t||o||s){let p=await import("fs"),h=await import("path"),{fileURLToPath:S}=await import("url"),T=h.join(h.dirname(S(import.meta.url)),"../package.json"),I=JSON.parse(p.readFileSync(T,"utf8")).version;if(n&&(console.log(`v${I}`),process.exit(0)),t&&(console.log(`FluxFlow CLI Arguments:
601
+ \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D`),Qu=e=>{let o=[],t=/\[\s*tool:functions\.([a-z0-9_]+)\s*\(/gi,n=0,s;for(;(s=t.exec(e))!==null;){let r=s[1],l=s.index+s[0].length-1,u=0,f=null,m=-1,c=-1;for(let a=l;a<e.length;a++){let d=e[a];if(f){if(d===f){let p=0;for(let h=a-1;h>=0&&e[h]==="\\";h--)p++;p%2===0&&(f=null)}}else if(d==='"'||d==="'"||d==="`")f=d;else if(d==="(")u++;else if(d===")"&&(u--,u===0)){c=a;let p=a+1;for(;p<e.length&&/\s/.test(e[p]);)p++;if(p<e.length&&e[p]==="]"){m=p;break}}}if(m!==-1){let a=e.substring(n,s.index);a.trim()&&o.push({type:"output",content:a});let d=e.substring(l+1,c);o.push({type:"tool",toolName:r.trim(),args:d.trim()}),n=m+1,t.lastIndex=n}else break}if(n<e.length){let r=e.substring(n);r.trim()&&o.push({type:"output",content:r})}return o},Zu=(()=>{let e=null,o=0;return t=>{let n=Date.now();if(e&&n-o<5e3)return e;let s=[],r=l=>{try{let u=ao.readdirSync(l);for(let f of u){if(["node_modules",".git",".gemini","dist","build",".next",".cache","out"].includes(f))continue;let m=Xn.join(l,f);ao.statSync(m).isDirectory()?r(m):s.push({name:f,relativePath:Xn.relative(process.cwd(),m)})}}catch{}};return r(t),e=s,o=n,s}})()});import{spawn as ed}from"child_process";import{fileURLToPath as mc}from"url";var td=4096,od=mc(import.meta.url).endsWith(".js");if(od&&!process.execArgv.some(e=>e.includes("max-old-space-size")))ed(process.execPath,[`--max-old-space-size=${td}`,mc(import.meta.url),...process.argv.slice(2)],{stdio:"inherit"}).on("exit",o=>process.exit(o||0));else{let e=process.argv.slice(2),o=e.includes("--help")&&e[e.indexOf("--help")+1]==="commands",t=e.includes("--help")&&!o,n=e.includes("--version")||e.includes("-v"),s=e[0]==="--update";if(n||t||o||s){let p=await import("fs"),h=await import("path"),{fileURLToPath:E}=await import("url"),w=h.join(h.dirname(E(import.meta.url)),"../package.json"),I=JSON.parse(p.readFileSync(w,"utf8")).version;if(n&&(console.log(`v${I}`),process.exit(0)),t&&(console.log(`FluxFlow CLI Arguments:
602
602
  --mode <flux|flow> Set startup mode (flux: Agent / flow: Chat)
603
603
  --model <model_name> Set startup AI model
604
604
  --key <key@provider> Set API key and provider
@@ -641,4 +641,4 @@ Selection: ${De}`,isAskRecord:!0}]),me(De)}}),H("ask")})},async()=>{if(Do.curren
641
641
  /changelog View latest updates
642
642
  /fluxflow init Create FluxFlow.md template
643
643
  /update check Check for new version
644
- /update latest Install latest release`),process.exit(0)),s){let L=e[1];if(L==="check"){let _=e[2]==="latest";try{let b=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;b||(console.error("Error: Could not retrieve latest version."),process.exit(1)),console.log(_?`Latest version: v${b}`:b!==I?`A new version of FluxFlow is available: v${b} (current: v${I}). Run "fluxflow --update latest" to upgrade.`:`FluxFlow is up to date (v${I}).`)}catch(R){console.error("Error checking for updates:",R.message),process.exit(1)}process.exit(0)}else if(L==="latest"){console.log("Checking latest version and settings...");try{let v=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;v||(console.error("Error: Could not retrieve latest version."),process.exit(1)),v===I&&(console.log(`FluxFlow is already up to date (v${I}).`),process.exit(0));let b=async()=>{let B=(await import("react")).default,{useState:z}=B,{render:mt,Box:ce,Text:Le}=await import("ink"),Je=(await import("ink-select-input")).default,ue=(await import("ink-text-input")).default;return new Promise(tt=>{let Ye=[{label:"NPM",value:"npm"},{label:"PNPM",value:"pnpm"},{label:"Yarn",value:"yarn"},{label:"Bun",value:"bun"},{label:"Custom Command",value:"custom"}],_e=({label:pt,isSelected:lo})=>B.createElement(ce,{width:"100%"},B.createElement(Le,{color:lo?"cyan":"gray",bold:lo},"\u2514\u2500 ",lo?"\u25C9":"\u25CB"," ",pt)),Me,je=()=>{let[pt,lo]=z("select"),[Wt,be]=z(""),rt=co=>{co.value==="custom"?lo("custom"):ye({manager:co.value})},Ao=co=>{ye({manager:"custom",customCommand:co})};return pt==="custom"?B.createElement(ce,{flexDirection:"column",marginY:1},B.createElement(ce,{marginBottom:1},B.createElement(Le,{color:"magenta",bold:!0},"\u{1F527} Enter custom update command:")),B.createElement(ce,{flexDirection:"row"},B.createElement(Le,{color:"cyan",bold:!0}," \u276F "),B.createElement(ue,{value:Wt,onChange:be,onSubmit:Ao})),B.createElement(ce,{marginTop:1},B.createElement(Le,{color:"gray",dimColor:!0,italic:!0}," (Press Enter to confirm)"))):B.createElement(ce,{flexDirection:"column",marginY:1},B.createElement(ce,{marginBottom:1},B.createElement(Le,{color:"magenta",bold:!0},"\u{1F4E6} Select a package manager for the update:")),B.createElement(Je,{items:Ye,onSelect:rt,itemComponent:_e,indicatorComponent:()=>null}))},ye=pt=>{Me&&Me(),tt(pt)},{unmount:ft}=mt(B.createElement(je,null));Me=ft})},A,F="",Q;try{let{loadSettings:B}=await Promise.resolve().then(()=>(os(),aa));Q=await B(),A=Q?.systemSettings?.updateManager||Q?.updateManager}catch{}if(!A){let B=await b();A=B.manager,F=B.customCommand}let j="";A==="pnpm"?j=`pnpm add -g fluxflow-cli@${v}`:A==="bun"?j=`bun add -g fluxflow-cli@${v}`:A==="yarn"?j=`yarn global add fluxflow-cli@${v}`:A==="custom"?j=F||Q?.customUpdateCommand||`npm install -g fluxflow-cli@${v}`:j=`npm install -g fluxflow-cli@${v}`,console.log(`Updating FluxFlow to v${v} using ${A}...`),console.log(`Running: ${j}`);let{execSync:Z}=await import("child_process");Z(j,{stdio:"inherit"}),console.log(`\x1B[32m\u2705 Update successful! FluxFlow updated to v${v}.\x1B[0m`)}catch(_){console.error("\x1B[31m\u274C Update failed:\x1B[0m",_.message),process.exit(1)}process.exit(0)}else console.error("Unknown update command. Available options: --update check, --update check latest, --update latest"),process.exit(1)}}let{default:r}=await import("react"),{render:l}=await import("ink"),{default:u}=await uc().then(()=>cc);process.env.NODE_NO_WARNINGS="1";let f=["cuimp","Found existing binary","Binary verified","curl.exe not found","Falling back to .bat file","DeprecationWarning"],m=console.log,c=console.warn,a=console.error,d=p=>{let h=p.map(String).join(" ");return f.some(S=>h.includes(S))};console.log=(...p)=>!d(p)&&m(...p),console.warn=(...p)=>!d(p)&&c(...p),console.error=(...p)=>!d(p)&&a(...p),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),l(r.createElement(u,{args:process.argv.slice(2)}),{exitOnCtrlC:!1})}
644
+ /update latest Install latest release`),process.exit(0)),s){let O=e[1];if(O==="check"){let P=e[2]==="latest";try{let S=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;S||(console.error("Error: Could not retrieve latest version."),process.exit(1)),console.log(P?`Latest version: v${S}`:S!==I?`A new version of FluxFlow is available: v${S} (current: v${I}). Run "fluxflow --update latest" to upgrade.`:`FluxFlow is up to date (v${I}).`)}catch(U){console.error("Error checking for updates:",U.message),process.exit(1)}process.exit(0)}else if(O==="latest"){console.log("Checking latest version and settings...");try{let A=(await(await fetch("https://registry.npmjs.org/fluxflow-cli",{cache:"no-store"})).json())["dist-tags"]?.latest;A||(console.error("Error: Could not retrieve latest version."),process.exit(1)),A===I&&(console.log(`FluxFlow is already up to date (v${I}).`),process.exit(0));let S=async()=>{let N=(await import("react")).default,{useState:J}=N,{render:ft,Box:de,Text:$e}=await import("ink"),qe=(await import("ink-select-input")).default,me=(await import("ink-text-input")).default;return new Promise(Ze=>{let je=[{label:"NPM",value:"npm"},{label:"PNPM",value:"pnpm"},{label:"Yarn",value:"yarn"},{label:"Bun",value:"bun"},{label:"Custom Command",value:"custom"}],Be=({label:ht,isSelected:lo})=>N.createElement(de,{width:"100%"},N.createElement($e,{color:lo?"cyan":"gray",bold:lo},"\u2514\u2500 ",lo?"\u25C9":"\u25CB"," ",ht)),Le,Ge=()=>{let[ht,lo]=J("select"),[Nt,be]=J(""),ze=co=>{co.value==="custom"?lo("custom"):Se({manager:co.value})},Mo=co=>{Se({manager:"custom",customCommand:co})};return ht==="custom"?N.createElement(de,{flexDirection:"column",marginY:1},N.createElement(de,{marginBottom:1},N.createElement($e,{color:"magenta",bold:!0},"\u{1F527} Enter custom update command:")),N.createElement(de,{flexDirection:"row"},N.createElement($e,{color:"cyan",bold:!0}," \u276F "),N.createElement(me,{value:Nt,onChange:be,onSubmit:Mo})),N.createElement(de,{marginTop:1},N.createElement($e,{color:"gray",dimColor:!0,italic:!0}," (Press Enter to confirm)"))):N.createElement(de,{flexDirection:"column",marginY:1},N.createElement(de,{marginBottom:1},N.createElement($e,{color:"magenta",bold:!0},"\u{1F4E6} Select a package manager for the update:")),N.createElement(qe,{items:je,onSelect:ze,itemComponent:Be,indicatorComponent:()=>null}))},Se=ht=>{Le&&Le(),Ze(ht)},{unmount:pt}=ft(N.createElement(Ge,null));Le=pt})},v,F="",V;try{let{loadSettings:N}=await Promise.resolve().then(()=>(es(),ca));V=await N(),v=V?.systemSettings?.updateManager||V?.updateManager}catch{}if(!v){let N=await S();v=N.manager,F=N.customCommand}let Y="";v==="pnpm"?Y=`pnpm add -g fluxflow-cli@${A}`:v==="bun"?Y=`bun add -g fluxflow-cli@${A}`:v==="yarn"?Y=`yarn global add fluxflow-cli@${A}`:v==="custom"?Y=F||V?.customUpdateCommand||`npm install -g fluxflow-cli@${A}`:Y=`npm install -g fluxflow-cli@${A}`,console.log(`Updating FluxFlow to v${A} using ${v}...`),console.log(`Running: ${Y}`);let{execSync:Z}=await import("child_process");Z(Y,{stdio:"inherit"}),console.log(`\x1B[32m\u2705 Update successful! FluxFlow updated to v${A}.\x1B[0m`)}catch(P){console.error("\x1B[31m\u274C Update failed:\x1B[0m",P.message),process.exit(1)}process.exit(0)}else console.error("Unknown update command. Available options: --update check, --update check latest, --update latest"),process.exit(1)}}let{default:r}=await import("react"),{render:l}=await import("ink"),{default:u}=await dc().then(()=>uc);process.env.NODE_NO_WARNINGS="1";let f=["cuimp","Found existing binary","Binary verified","curl.exe not found","Falling back to .bat file","DeprecationWarning"],m=console.log,c=console.warn,a=console.error,d=p=>{let h=p.map(String).join(" ");return f.some(E=>h.includes(E))};console.log=(...p)=>!d(p)&&m(...p),console.warn=(...p)=>!d(p)&&c(...p),console.error=(...p)=>!d(p)&&a(...p),process.stdout.write("\x1B[2J\x1B[3J\x1B[H"),process.stdout.isTTY&&(process.stdout.write("\x1B]0;FluxFlow\x07"),process.stdout.write("\x1B]633;P;TerminalTitle=FluxFlow\x07")),l(r.createElement(u,{args:process.argv.slice(2)}),{exitOnCtrlC:!1})}